text
stringlengths
184
4.48M
from django.test import TestCase from django.contrib.auth import get_user_model # Create your tests here. class CustomerUserTests(TestCase): def test_create_user(self): User = get_user_model() user = User.objects.create_user( username="Devin", email='devin@gmail.com', password='testpass123' ) self.assertEqual(user.username, 'Devin') self.assertEqual(user.email, "devin@gmail.com") self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) def test_create_superuser(self): User = get_user_model() admin_user = User.objects.create_superuser( username="superadmin", email='superadmin@gmail.com', password='testpass123' ) self.assertEqual(admin_user.username, 'superadmin') self.assertEqual(admin_user.email, "superadmin@gmail.com") self.assertTrue(admin_user.is_active) self.assertTrue(admin_user.is_staff) self.assertTrue(admin_user.is_superuser)
import algosdk from "algosdk"; import AlgoMonetaryManager from "../../algo/AlgoMonetaryManager"; import AlgoClient from "../../algo/AlogClient"; import { ALGO_MIN_ACCOUNT_BALANCE, ALGO_MIN_TRANSACTION_FEE, } from "../../algo/constants"; import IdentityClient from "../identity/IdentityClient"; import { UserType } from "../identity/types"; import { PlatoUserAccount } from "./types"; export default class PlatoUserManager { private readonly algoMonetaryManager: AlgoMonetaryManager; constructor(private readonly algoClient: AlgoClient) { this.algoMonetaryManager = new AlgoMonetaryManager(algoClient); } createUserAccount(): PlatoUserAccount { const account = algosdk.generateAccount(); return { address: account.addr, secretKey: account.sk, mnemonic: algosdk.secretKeyToMnemonic(account.sk), }; } async initAccount( assetHolderMnemonic: string, customerMnemonic: string, identityAppId: number, platoAsaId: number, userType: UserType, latitude?: string, longitude?: string, refererAddress?: string ): Promise<void> { const identityClient = new IdentityClient(this.algoClient, identityAppId); const { addr: customerAddress } = algosdk.mnemonicToSecretKey(customerMnemonic); const numberOfHoldingAssets = 2; // Algo Coin + Plato token // TODO: review initial number of txn const numberOptInTransactions = 5; // opt in the identity contract and PLATO token const totalAccountBalance = numberOptInTransactions * ALGO_MIN_TRANSACTION_FEE + numberOfHoldingAssets * ALGO_MIN_ACCOUNT_BALANCE + IdentityClient.OPT_IN_COST; const algoTransferTxn = this.algoMonetaryManager.createAlgoTransferTransaction( assetHolderMnemonic, customerAddress, totalAccountBalance ); const optInPlatoAsaTxn = this.algoMonetaryManager.createAssetOptInTransaction( customerMnemonic, platoAsaId ); const optInIdentityAppTxn = identityClient.createOptInTransaction({ userMnemonic: customerMnemonic, userType, latitude, longitude, refererAddress, }); await this.algoClient.sendAtomicTransaction( algoTransferTxn, optInPlatoAsaTxn, optInIdentityAppTxn ); } }
<?php /**\addtogroup scheduled_task * @{ */ Fakoli::usingFeature("auto_form"); class TaskScheduleHelper { static function drawScheduleBox($id, $value, $readOnly = false) { echo "<table id='{$id}' class='task_schedule'><thead><tr><th>&nbsp;</th>"; for($i = 0; $i < 7; ++$i) { $day = jddayofweek($i, 2); echo "<th class='schedule_day'>{$day}</th>"; } echo "</tr></thead>"; echo "<tbody>"; for($hour = 0; $hour < 24; ++$hour) { $desc = str_pad($hour, 2, '0', STR_PAD_LEFT).":00"; echo "<tr>"; echo "<th class='schedule_period'>$desc</td>"; for($i = 0; $i < 7; ++$i) { $idx = "{$i}:{$desc}"; $class = (strpos($value, $idx) !== FALSE) ? "period selected" : "period"; echo "<td class='{$class}' data-period='$idx'></td>"; } echo "</tr>"; } echo "</tbody></table>"; } static function calculatePeriod($datetime = null) { $d = new DateTime($datetime); $day = $d->format("N") - 1; $hour = $d->format("H"); $sp = "{$day}:{$hour}:00"; trace("Schedule Period for $datetime is $sp", 3); return $sp; } } class TaskScheduleFieldRenderer extends FieldRenderer { function TaskScheduleFieldRenderer($parent) { $this->FieldRenderer($parent); $this->annotateBefore = true; } function renderScript($field) { if ($this->parent->readOnlyForm || $this->parent->isReadOnly($field)) return; $id = "{$this->parent->id}_{$field}"; ?> <script type="text/javascript" src="/components/scheduled_task/js/task_schedule_selector.js"></script> <script type='text/javascript'> window.addEvent('load', function() { new TaskScheduleSelector('<?echo $id?>_table', '<?echo $id?>'); }); </script> <? } function drawScheduleBox($field, $readOnly = false) { $value = $this->parent->data->get($field); echo "<input type='hidden' id='{$this->parent->id}_{$field}' name='{$field}' value='{$value}'/>"; TaskScheduleHelper::drawScheduleBox("{$this->parent->id}_{$field}_table", $value, $readOnly); } function renderField($field) { $this->_startField($field); $this->drawScheduleBox($field); $this->_endField($field); } function renderReadOnly($field) { $this->_startField($field); $this->drawScheduleBox($field, true); $this->_endField($field); } } // Register the field renderer AutoForm::registerFieldRendererClass(TaskSchedule, TaskScheduleFieldRenderer); /**@}*/?>
<!DOCTYPE html> <html> <head> <title>Analisis y Visualizacion de Datos</title> <!-- Carga de la biblioteca Chart.js desde un CDN --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <h1>Ingrese sus datos en la tabla</h1> <table id="data-table"> <tr> <th>Categoria</th> <th>Valor</th> </tr> <tr> <td><input type="number" class="x-input"></td> <td><input type="number" class="y-input"></td> </tr> </table> <button onclick="addRow()">Agregar fila</button> <button onclick="generateGraph()">Generar Grafico</button> <canvas id="myChart" width="400" height="200"></canvas> <script> let data = []; function addRow() { const xInput = document.createElement("input"); xInput.type = "number"; xInput.classList.add("x-input"); const yInput = document.createElement("input"); yInput.type = "number"; yInput.classList.add("y-input"); const newRow = document.createElement("tr"); const xCell = document.createElement("td"); const yCell = document.createElement("td"); xCell.appendChild(xInput); yCell.appendChild(yInput); newRow.appendChild(xCell); newRow.appendChild(yCell); document.getElementById("data-table").appendChild(newRow); } function getTableData() { data = []; const tableRows = document.querySelectorAll("#data-table tr"); for (let i = 1; i < tableRows.length; i++) { const row = tableRows[i]; const xValue = parseFloat(row.querySelector(".x-input").value); const yValue = parseFloat(row.querySelector(".y-input").value); data.push({ x: xValue, y: yValue }); } } function generateGraph() { getTableData(); // Ordenar los datos por el valor de X (opcional) data.sort((a, b) => a.x - b.x); const ctx = document.getElementById("myChart").getContext("2d"); new Chart(ctx, { type: "line", data: { datasets: [{ label: "Datos ingresados", data: data, borderColor: "rgba(75, 192, 192, 1)", backgroundColor: "rgba(75, 192, 192, 0.2)", fill: true, }], }, options: { scales: { x: { type: "linear", position: "bottom", }, }, }, }); } </script> </body> </html>
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable, of} from 'rxjs'; import {catchError, map, tap} from 'rxjs/operators'; import {Hero} from '../hero'; import {MessageService} from './message.service'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; @Injectable({ providedIn: 'root' }) export class HeroService { private heroesUrl = 'api/heroes'; constructor( private http: HttpClient, private messageService: MessageService) { } getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl).pipe( tap(() => this.log(`fetched heroes`)), catchError(this.handleError('getHeroes', [])) ); } getHero(id: number): Observable<Hero> { const url = `${this.heroesUrl}/${id}`; return this.http.get<Hero>(url).pipe( tap(() => this.log(`fetched hero id=${id}`)), catchError(this.handleError<Hero>(`getHero id=${id}`)) ); } updateHero(hero: Hero): Observable<any> { return this.http.put(this.heroesUrl, hero, httpOptions).pipe( tap(_ => this.log(`updated hero id=${hero.id}`)), catchError(this.handleError<any>('updateHero')) ); } addHero(hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe( tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)), catchError(this.handleError<Hero>('addHero')) ); } deleteHero(hero: Hero | number): Observable<Hero> { const id = typeof hero === 'number' ? hero : hero.id; const url = `${this.heroesUrl}/${id}`; return this.http.delete<Hero>(url, httpOptions).pipe( tap(_ => this.log(`deleted hero id=${id}`)), catchError(this.handleError<Hero>('deleteHero')) ); } searchHeroes(term: string): Observable<Hero[]> { if (!term.trim()) { // if not search term, return empty hero array. return of([]); } return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe( tap(_ => this.log(`found heroes matching "${term}"`)), catchError(this.handleError<Hero[]>('searchHeroes', [])) ); } private log(message: string): void { this.messageService.add(`HeroService: ${message}`); } private handleError<T>(operation = 'operation', result?: T): (e: any) => Observable<T> { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.log(`${operation} failed: ${error.message}`); return of(result as T); }; } }
// ignore_for_file: deprecated_member_use, file_names import 'package:flutter/material.dart'; class WidgetRaisedButton extends StatelessWidget { final String text; final void Function() press; final Color color, textColor; const WidgetRaisedButton({ Key? key, required this.text, required this.press, required this.color, required this.textColor, }) : super(key: key); @override Widget build(BuildContext context) { return FractionallySizedBox( widthFactor: 1, child: RaisedButton( color: color, hoverColor: Colors.black, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), padding: const EdgeInsets.symmetric(horizontal: 80, vertical: 14), child: Text( text, style: TextStyle(color: textColor, fontSize: 16), ), onPressed: press, ), ); } }
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Test find TextFormField widgets', (tester) async { await tester.pumpWidget(const MyApp()); await tester.pump(); final nameTextField = find.byKey(const Key('nameTextField')); final phoneTextField = find.byKey(const Key('phoneTextField')); final emailTextField = find.byKey(const Key('emailTextField')); expect(nameTextField, findsOneWidget); expect(phoneTextField, findsOneWidget); expect(emailTextField, findsOneWidget); }); testWidgets('Test Form Validation and Submission (Success)', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); await tester.enterText(find.byKey(const Key('nameTextField')), 'John Doe'); await tester.enterText( find.byKey(const Key('phoneTextField')), '1234567890'); await tester.enterText( find.byKey(const Key('emailTextField')), 'john.doe@example.com'); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.text('John Doe'), findsOneWidget); expect(find.text('1234567890'), findsOneWidget); expect(find.text('john.doe@example.com'), findsOneWidget); }); testWidgets('Test Form Validation and Submission (Failure)', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); await tester.enterText(find.byKey(const Key('nameTextField')), '123'); await tester.enterText(find.byKey(const Key('phoneTextField')), 'abc'); await tester.enterText( find.byKey(const Key('emailTextField')), 'wrongEmail'); await tester.ensureVisible(find.byKey(const Key('submitButton'))); await tester.tap(find.byKey(const Key('submitButton'))); await tester.pumpAndSettle(); expect(find.text('Enter Correct Name'), findsOneWidget); expect(find.text('Enter Correct Phone Number'), findsOneWidget); expect(find.text('Enter Correct Email Address'), findsOneWidget); }); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Form Validation'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: Center( child: Text(appTitle, style: Theme.of(context).textTheme.titleLarge!.copyWith( color: Colors.white, )), ), backgroundColor: Colors.blue[500], ), body: const MyCustomForm(), ), ); } } class MyCustomForm extends StatefulWidget { const MyCustomForm({super.key}); @override State<MyCustomForm> createState() => _MyCustomFormState(); } class _MyCustomFormState extends State<MyCustomForm> { final yourname = TextEditingController(); final studentid = TextEditingController(); final youremail = TextEditingController(); @override void dispose() { yourname.dispose(); studentid.dispose(); youremail.dispose(); super.dispose(); } final _formKey = GlobalKey<FormState>(); final nameRegex = RegExp(r"^[a-zA-Z]"); final digitRegex = RegExp(r"^[0-9]*$"); final emailRegex = RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+"); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const ImageSection( image: 'images/tak.jpg', ), const ButtonSection(), TextFormField( key: const Key('nameTextField'), controller: yourname, decoration: const InputDecoration(labelText: "Enter Name"), validator: (value) { if (value == null || value.isEmpty) { return 'Enter Correct Name'; } else if (!nameRegex.hasMatch(value)) { return "Enter Correct Name"; } return null; }, ), const SizedBox( height: 30, ), TextFormField( key: const Key('phoneTextField'), controller: studentid, decoration: const InputDecoration(labelText: "Enter Phone Number"), validator: (value) { if (value == null || value.isEmpty) { return 'Enter Correct Phone Number'; } else if (value.length != 9 && value.length != 10) { return "Enter Correct Phone Number"; } else if (!digitRegex.hasMatch(value)) { return "Enter Correct Phone Number"; } return null; }, ), const SizedBox( height: 30, ), TextFormField( key: const Key('emailTextField'), controller: youremail, decoration: const InputDecoration(labelText: "Enter Email"), validator: (value) { if (value == null || value.isEmpty) { return 'Enter Correct Email Address'; } else if (!emailRegex.hasMatch(value)) { return "Enter Correct Email Address"; } return null; }, ), const SizedBox( height: 30, ), ElevatedButton( key: const Key('submitButton'), onPressed: () { // Validate returns true if the form is valid, or false otherwise. if (_formKey.currentState!.validate()) { // If true do showDialog( context: context, builder: (context) { return AlertDialog( content: Column( children: [ Text(yourname.text), Text(studentid.text), Text(youremail.text), ], ), ); }, ); } }, //tooltip: 'Show me the value!', child: const Text('Submit Data')), ], ), ), ), ), ); } } class ImageSection extends StatelessWidget { const ImageSection({super.key, required this.image}); final String image; @override Widget build(BuildContext context) { return Image.asset( image, width: 600, height: 240, fit: BoxFit.cover, ); } } class ButtonSection extends StatelessWidget { const ButtonSection({super.key}); @override Widget build(BuildContext context) { return const SizedBox( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 60, vertical: 0), child: Icon( Icons.favorite, color: Colors.pink, size: 24.0, ), ), Padding( padding: EdgeInsets.symmetric(horizontal: 60, vertical: 0), child: Icon( Icons.audiotrack, color: Colors.green, size: 30.0, ), ), Padding( padding: EdgeInsets.symmetric(horizontal: 60, vertical: 0), child: Icon( Icons.beach_access, color: Colors.blue, size: 36.0, ), ), ], ) ], ), ); } }
import React, { useState } from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import "./css/RegisterPage.css"; import { toast } from "react-toastify"; const RegisterPage = () => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isError, setIsError] = useState({ name: "", email: "", password: "", }); const navigate = useNavigate(); const validate = () => { let isError = false; const errors = { name: "", email: "", password: "", }; if (name.length < 4) { isError = true; errors.name = "At least 4 characters required"; } if (!/.+@.+\..+/.test(email)) { isError = true; errors.email = "Email address is invalid"; } if (password.length < 6) { isError = true; errors.password = "At least 6 characters required"; } setIsError(errors); return !isError; }; const handleSubmit = async (e) => { e.preventDefault(); if (validate()) { try { const response = await axios.post("http://localhost:5000/register", { name, email, password, }); localStorage.setItem("token", response.data.token); navigate("/favorites"); } catch (error) { toast.error("User already exists"); console.log("Error registering", error); } } }; return ( <div className="loginWrapper"> <div className="login-box"> <h2>Register</h2> <form onSubmit={handleSubmit} noValidate> <div className="user-box"> <input type="text" required value={name} onChange={(e) => setName(e.target.value)} className={isError.name.length > 0 ? "is-invalid" : ""} /> <label>{isError.name.length > 0 ? isError.name : "Name"}</label> </div> <div className="user-box"> <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className={isError.email.length > 0 ? "is-invalid" : ""} /> <label>{isError.email.length > 0 ? isError.email : "Email"}</label> </div> <div className="user-box"> <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} className={isError.password.length > 0 ? "is-invalid" : ""} /> <label> {isError.password.length > 0 ? isError.password : "Password"} </label> </div> <button className="button" type="submit"> Register </button> </form> <button className="button" onClick={() => navigate("/login")}> Login instead </button> </div> </div> ); }; export default RegisterPage;
import { useForm } from "@inertiajs/react"; export default function Create({ categories }: any) { const { data, setData, post, errors } = useForm({ name: "", price: "", image: null as File | null, description: "", category_id: "", }); const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); /* console.log(data); */ post("/product"); }; return ( <div> <form onSubmit={handleSubmit} className="grid gap-4 w-1/2 mx-auto py-16" > <select name="category_id" value={data.category_id} onChange={(e) => setData("category_id", e.target.value)} > <option value="">Seleccione una categoría</option> {categories.map((category: any) => ( <option key={category.id} value={category.id}> {category.name} </option> ))} </select> <input type="text" name="name" value={data.name} placeholder="Nombre del Producto" onChange={(e) => setData("name", e.target.value)} /> {errors.name && <p className="text-red-500">{errors.name}</p>} <input type="number" name="price" value={data.price} onChange={(e) => setData("price", e.target.value)} placeholder="Precio del Producto" /> {errors.price && <p className="text-red-500">{errors.price}</p>} <input type="file" name="image" onChange={(e) => setData("image", e.target.files![0])} accept="image/*" /> {errors.image && <p className="text-red-500">{errors.image}</p>} <textarea name="description" value={data.description} onChange={(e) => setData("description", e.target.value)} placeholder="Descripción del Producto" /> {errors.description && ( <p className="text-red-500">{errors.description}</p> )} <button type="submit" className="bg-blue-500 text-white py-2 px-4 rounded" > Guardar </button> </form> </div> ); }
<template> <div> <form> <label for="nome">Nome</label> <input type="text" name="nome" id="nome" v-model="novoUsuario.nome"> <label for="email">Email</label> <input type="email" name="email" id="email" v-model="novoUsuario.email"> <label for="senha">Senha</label> <input type="password" name="senha" id="senha" v-model="novoUsuario.senha"> <label for="cep">CEP</label> <input type="text" name="cep" id="cep" v-model.lazy="cep"><span v-if="mensagem">{{mensagem}}</span> <label for="rua">Rua</label> <input type="text" name="rua" id="rua" v-model="novoUsuario.rua"> <label for="numero">Número</label> <input type="number" name="numero" id="numero" v-model="novoUsuario.numero"> <label for="bairro">Bairro</label> <input type="text" name="bairro" id="bairro" v-model="novoUsuario.bairro"> <label for="cidade">Cidade</label> <input type="text" name="cidade" id="cidade" v-model="novoUsuario.cidade"> <label for="estado">Estado</label> <input type="text" name="estado" id="estado" v-model="novoUsuario.estado"> <button @click.prevent="enviarDados"> <slot class="slot"></slot> </button> </form> </div> </template> <script> export default { data(){ return{ cep:"", mensagem:"", novoUsuario:{ nome:"", email:"", senha:"", cep:"", rua:"", numero:"", bairro:"", cidade:"", estado:"", }, } }, methods:{ enviarDados(){ this.$store.commit("UPDATE_USUARIO", this.novoUsuario) this.logarUsuarioCriado() }, async logarUsuarioCriado(){ if(this.$store.state.login === false){ try { await this.$store.dispatch("criarUsuario", this.$store.state.usuario); await this.$router.push({name:"usuario"}) await this.$store.dispatch("getUsuario",{usuario:this.$store.state.usuario.email,senha:this.$store.state.usuario.senha}); if(this.$store.state.login === true){ await this.$store.commit("MUDAR_MENSAGEM","Usuário criado com sucesso!" ) }} catch(error){ console.log(error) } } } }, watch:{ cep(){ if(this.cep){ fetch(`https://viacep.com.br/ws/${this.cep}/json/`).then(response=> { if(response.status === 400){ if(this.cep.length<8){ this.mensagem = "o cep tem que ter 8 digitos" }else{ this.mensagem = "cep não encotrado" } this.novoUsuario.cep = "" this.novoUsuario.rua = "" this.novoUsuario.bairro = "" this.novoUsuario.cidade = "" this.novoUsuario.estado = "" } else{ response.json().then(result => { this.cep = result.cep this.novoUsuario.cep = result.cep this.novoUsuario.rua = result.logradouro this.novoUsuario.bairro = result.bairro this.novoUsuario.cidade = result.localidade this.novoUsuario.estado = result.uf this.mensagem = "" }) } }) } }, } } </script> <style scoped> button{ margin-top:30px ; font-size: 18px; padding: 0; border: none; background: none; } div{ margin: 0 auto; width: 400px; padding: 0; } div form{ display: grid; grid-auto-columns: 1fr 1fr; } label{ font-size: 24px; grid-column: 1; text-align: left; } input{ padding: 10px; height: 40px; border: 3px solid white; margin-bottom:10px; border-radius:30px ; font-size: 24px; transition: 0.3s all; box-shadow: 0px 5px 10px 3px gray; grid-column: 1/-1; max-width: 400px; } input:hover,input:focus{ outline: none; border: 3px solid #8877FF; box-shadow: 0px 5px 10px 3px #8877FF; } #cep{ max-width: 200px; } span{ font-size: 16px; position: relative; padding: 0; color: red; top: -53px; left:130px; padding: 0; margin: 0; display: inline; } input:last-child{ margin-bottom: 32px; } </style>
import sys import os import random import pandas as pd sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from generate_data.base_data import get_base_variables from equations.up_and_out_call_Brown import price_up_and_out_call_brown from generate_data.find_beta import find_optimal_beta # Initial values h_values = range(85, 100) t_values = [i * 0.1 for i in range(2, 51)] sigma_values = [i * 0.05 for i in range(4, 13)] m_values = [5, 25, 50] # Additional layer for m values def main(): # Get base variables _, r, _, _, S0, K, trading_days, _, _, q = get_base_variables() # Removed m from here n = 10**6 # Store the samples and results samples = [] total_iterations = len(h_values) * len(m_values) * 30 # 30 for the number of T and sigma combinations current_iteration = 0 for H in h_values: for m in m_values: # Additional loop for m sampled_ts = random.sample(t_values,40) sampled_sigmas = random.sample(sigma_values, 7) for T, sigma in zip(sampled_ts, sampled_sigmas): # Calculate exact price price, _, _ = price_up_and_out_call_brown(m, r, T, sigma, S0, K, H, q, n) # Find optimal beta best_beta, _ = find_optimal_beta(S0, K, r, q, sigma, m, H, T, price) samples.append({ 'S0': S0, 'K': K, 'r': r, 'm': m, 'T': T, 'H': H, 'sigma': sigma, 'trading_days': trading_days, 'exact_price': price, 'best_beta': best_beta # Replace with actual beta }) current_iteration += 1 print(f"Progress: {current_iteration}/{total_iterations} iterations completed", end='\r') # Convert to DataFrame and save samples_df = pd.DataFrame(samples).round(4) samples_df.to_csv('sample_data.csv', index=False) print("\nData saved to 'sample_data.csv'.") if __name__ == "__main__": main()
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; //댓글을 볼 수 있는 페이지 class CommentPage extends StatelessWidget { final DocumentSnapshot document; CommentPage(this.document); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('댓글'), ), body: StreamBuilder<QuerySnapshot>( stream: _commentStream(), builder: (context, snapshot) { //데이터(댓글)가 없다면 로딩 if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } //데이터를 map으로 변경 -> ListTile로 변경 -> 타입을 리스트 변경 return ListView( children: snapshot.data.documents.map((doc) { return ListTile( leading: Text(doc['writer']), title: Text(doc['comment']), ); }).toList(), ); }), ); } //댓글이 목록으로 옴 Stream<QuerySnapshot> _commentStream() { return Firestore.instance .collection('post') .document(document.documentID) //post 컬렉션 안에 문서에서 comment(댓글) 컬렉션을 생성해서 .collection('comment') .snapshots(); } }
/* Monster_Fatguy.cpp AI for the fat guy on the putra level */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "../Projectile.h" class rvMonsterHarvester : public idAI { public: CLASS_PROTOTYPE(rvMonsterHarvester); rvMonsterHarvester(void); void InitSpawnArgsVariables(void); void Spawn(void); void Save(idSaveGame *savefile) const; void Restore(idRestoreGame *savefile); virtual bool Attack(const char *attackName, jointHandle_t joint, idEntity *target, const idVec3 &pushVelocity = vec3_origin); virtual bool UpdateAnimationControllers(void); bool CanTurn(void) const; virtual int GetDamageForLocation(int damage, int location); virtual void Damage(idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location); virtual bool SkipImpulse(idEntity *ent, int id); protected: enum { WHIP_LEFT, WHIP_CENTER, WHIP_RIGHT, WHIP_MAX }; enum { PART_ARM_R, PART_ARM_L, PART_LEG_FR, PART_LEG_FL, PART_LEG_BR, PART_LEG_BL, PART_TANK_R, PART_TANK_L, PARTS_MAX }; idStr partLocation[PARTS_MAX]; idStr partSurf[PARTS_MAX]; idStr partJoint[PARTS_MAX]; int partHealth[PARTS_MAX]; void DestroyPart(int part); rvAIAction actionWhipAttack; rvAIAction actionSprayAttack; rvAIAction actionRocketAttack; rvAIAction actionGrenadeAttack; jointHandle_t whipJoints[WHIP_MAX]; idEntityPtr<idEntity> whipProjectiles[WHIP_MAX]; jointHandle_t jointLeftMuzzle; jointHandle_t jointRightMuzzle; virtual bool CheckActions(void); virtual int FilterTactical(int availableTactical); const char *GetMeleeAttackAnim(const idVec3 &target); bool PlayMeleeAttackAnim(const idVec3 &target, int blendFrames); const char *GetRangedAttackAnim(const idVec3 &target); bool PlayRangedAttackAnim(const idVec3 &target, int blendFrames); int maxShots; int minShots; int shots; int nextTurnTime; int sweepCount; private: void DropLeg(int part); // Custom actions bool CheckAction_WhipAttack(rvAIAction *action, int animNum); virtual bool CheckAction_MeleeAttack(rvAIAction *action, int animNum); virtual bool CheckAction_RangedAttack(rvAIAction *action, int animNum); bool CheckAction_SprayAttack(rvAIAction *action, int animNum); bool CheckAction_RocketAttack(rvAIAction *action, int animNum); bool CheckAction_GrenadeAttack(rvAIAction *action, int animNum); stateResult_t State_Killed(const stateParms_t &parms); stateResult_t State_Dead(const stateParms_t &parms); // Torso States stateResult_t State_Torso_WhipAttack(const stateParms_t &parms); stateResult_t State_Torso_ClawAttack(const stateParms_t &parms); stateResult_t State_Torso_RangedAttack(const stateParms_t &parms); stateResult_t State_Torso_TurnRight90(const stateParms_t &parms); stateResult_t State_Torso_TurnLeft90(const stateParms_t &parms); stateResult_t State_Torso_SprayAttack(const stateParms_t &parms); stateResult_t State_Torso_RocketAttack(const stateParms_t &parms); CLASS_STATES_PROTOTYPE(rvMonsterHarvester); }; CLASS_DECLARATION(idAI, rvMonsterHarvester) END_CLASS /* rvMonsterHarvester::rvMonsterHarvester */ rvMonsterHarvester::rvMonsterHarvester(void) { } void rvMonsterHarvester::InitSpawnArgsVariables(void) { whipJoints[WHIP_LEFT] = animator.GetJointHandle(spawnArgs.GetString("joint_whip_left")); whipJoints[WHIP_RIGHT] = animator.GetJointHandle(spawnArgs.GetString("joint_whip_right")); whipJoints[WHIP_CENTER] = animator.GetJointHandle(spawnArgs.GetString("joint_whip_center")); maxShots = spawnArgs.GetInt("maxShots", "1"); minShots = spawnArgs.GetInt("minShots", "1"); for (int part = 0; part < PARTS_MAX; part++) { partLocation[part] = spawnArgs.GetString(va("part_%d_location", part), ""); partSurf[part] = spawnArgs.GetString(va("part_%d_surf", part), ""); partJoint[part] = spawnArgs.GetString(va("part_%d_joint", part), ""); } jointLeftMuzzle = animator.GetJointHandle(spawnArgs.GetString("joint_muzzle_left_arm")); jointRightMuzzle = animator.GetJointHandle(spawnArgs.GetString("joint_muzzle_right_arm")); } /* rvMonsterHarvester::Spawn */ void rvMonsterHarvester::Spawn(void) { // Custom actions actionWhipAttack.Init(spawnArgs, "action_whipAttack", "Torso_WhipAttack", AIACTIONF_ATTACK); actionSprayAttack.Init(spawnArgs, "action_sprayAttack", "Torso_SprayAttack", AIACTIONF_ATTACK); actionRocketAttack.Init(spawnArgs, "action_rocketAttack", "Torso_RocketAttack", AIACTIONF_ATTACK); actionGrenadeAttack.Init(spawnArgs, "action_grenadeAttack", NULL, AIACTIONF_ATTACK); int i; for (i = 0; i < WHIP_MAX; i++) { whipProjectiles[i] = NULL; } InitSpawnArgsVariables(); shots = 0; for (int part = 0; part < PARTS_MAX; part++) { partHealth[part] = spawnArgs.GetInt(va("part_%d_health", part), "500"); } } /* rvMonsterHarvester::Save */ void rvMonsterHarvester::Save(idSaveGame *savefile) const { actionWhipAttack.Save(savefile); actionSprayAttack.Save(savefile); actionRocketAttack.Save(savefile); actionGrenadeAttack.Save(savefile); int i; for (i = 0; i < WHIP_MAX; i++) { savefile->WriteObject(whipProjectiles[i]); } savefile->WriteInt(nextTurnTime); savefile->WriteInt(sweepCount); savefile->WriteInt(shots); for (int part = 0; part < PARTS_MAX; part++) { savefile->WriteInt(partHealth[part]); } } /* rvMonsterHarvester::Restore */ void rvMonsterHarvester::Restore(idRestoreGame *savefile) { actionWhipAttack.Restore(savefile); actionSprayAttack.Restore(savefile); actionRocketAttack.Restore(savefile); actionGrenadeAttack.Restore(savefile); int i; for (i = 0; i < WHIP_MAX; i++) { savefile->ReadObject(reinterpret_cast<idClass *&>(whipProjectiles[i])); } savefile->ReadInt(nextTurnTime); savefile->ReadInt(sweepCount); savefile->ReadInt(shots); for (int part = 0; part < PARTS_MAX; part++) { savefile->ReadInt(partHealth[part]); } InitSpawnArgsVariables(); } /* rvMonsterHarvester::UpdateAnimationControllers */ bool rvMonsterHarvester::UpdateAnimationControllers(void) { idVec3 origin; idMat3 axis; idVec3 dir; idVec3 localDir; idVec3 target; if (!idAI::UpdateAnimationControllers()) { return false; } return true; } /* rvMonsterHarvester::SkipImpulse */ bool rvMonsterHarvester::SkipImpulse(idEntity *ent, int id) { return true; } void rvMonsterHarvester::DropLeg(int part) { jointHandle_t joint = INVALID_JOINT; const char *legDef = NULL; switch (part) { case PART_LEG_FR: joint = animator.GetJointHandle("r_toe_front"); legDef = "def_leg_part1"; break; case PART_LEG_FL: joint = animator.GetJointHandle("l_toe_front"); legDef = "def_leg_part2"; break; case PART_LEG_BR: joint = animator.GetJointHandle("r_toe_back"); legDef = "def_leg_part4"; break; case PART_LEG_BL: joint = animator.GetJointHandle("l_toe_back"); legDef = "def_leg_part3"; break; } if (joint != INVALID_JOINT) { idEntity *leg = gameLocal.SpawnEntityDef(spawnArgs.GetString(legDef)); if (leg) { idVec3 jointOrg; idMat3 jointAxis; animator.GetJointTransform(joint, gameLocal.GetTime(), jointOrg, jointAxis); jointOrg = renderEntity.origin + (jointOrg * renderEntity.axis); leg->GetPhysics()->SetOrigin(jointOrg); leg->GetPhysics()->SetAxis(jointAxis * renderEntity.axis); leg->PlayEffect("fx_trail", vec3_origin, jointAxis, true, vec3_origin, true); if (leg->IsType(idDamagable::GetClassType())) { // don't be destroyed for at least 5 seconds ((idDamagable *)leg)->invincibleTime = gameLocal.GetTime() + 5000; } // push it if (jointOrg.z > GetPhysics()->GetOrigin().z + 20.0f) { // leg was blown off while in the air... jointHandle_t attachJoint = animator.GetJointHandle(partJoint[part].c_str()); if (attachJoint != INVALID_JOINT) { animator.GetJointTransform(attachJoint, gameLocal.GetTime(), jointOrg, jointAxis); jointOrg = renderEntity.origin + (jointOrg * renderEntity.axis); idVec3 impulse = leg->GetPhysics()->GetCenterMass() - jointOrg; impulse.z = 0; impulse.Normalize(); impulse *= ((gameLocal.random.RandomFloat() * 3.0f) + 2.0f) * 1000; // away impulse.z = (gameLocal.random.CRandomFloat() * 500.0f) + 1000.0f; // up! leg->ApplyImpulse(this, 0, jointOrg, impulse); } } } } } void rvMonsterHarvester::DestroyPart(int part) { idStr explodeFX; idStr trailFX; switch (part) { case PART_ARM_R: if (partHealth[PART_ARM_L] <= 0) { actionRangedAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; // so we don't sit here and do nothing at medium range...? actionRocketAttack.minRange = actionRangedAttack.minRange; } explodeFX = "fx_destroy_part_arm"; trailFX = "fx_destroy_part_trail_arm"; break; case PART_ARM_L: if (partHealth[PART_ARM_R] <= 0) { actionRangedAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; // so we don't sit here and do nothing at medium range...? actionRocketAttack.minRange = actionRangedAttack.minRange; } explodeFX = "fx_destroy_part_arm"; trailFX = "fx_destroy_part_trail_arm"; break; // FIXME: spawn leg func_movables case PART_LEG_FR: DropLeg(part); actionMeleeAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; animPrefix = "dmg_frt"; painAnim = "damaged"; explodeFX = "fx_destroy_part_leg"; trailFX = "fx_destroy_part_trail_leg"; break; case PART_LEG_FL: DropLeg(part); actionMeleeAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; animPrefix = "dmg_flt"; painAnim = "damaged"; explodeFX = "fx_destroy_part_leg"; trailFX = "fx_destroy_part_trail_leg"; break; case PART_LEG_BR: DropLeg(part); actionMeleeAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; animPrefix = "dmg_brt"; painAnim = "damaged"; explodeFX = "fx_destroy_part_leg"; trailFX = "fx_destroy_part_trail_leg"; break; case PART_LEG_BL: DropLeg(part); actionMeleeAttack.fl.disabled = true; actionSprayAttack.fl.disabled = true; animPrefix = "dmg_blt"; painAnim = "damaged"; explodeFX = "fx_destroy_part_leg"; trailFX = "fx_destroy_part_trail_leg"; break; case PART_TANK_R: if (partHealth[PART_TANK_L] <= 0) { actionRocketAttack.fl.disabled = true; // so we don't sit here and do nothing at long range...? actionRangedAttack.maxRange = actionRocketAttack.maxRange; } explodeFX = "fx_destroy_part_tank"; trailFX = "fx_destroy_part_trail_tank"; break; case PART_TANK_L: if (partHealth[PART_TANK_R] <= 0) { actionRocketAttack.fl.disabled = true; // so we don't sit here and do nothing at long range...? actionRangedAttack.maxRange = actionRocketAttack.maxRange; } explodeFX = "fx_destroy_part_tank"; trailFX = "fx_destroy_part_trail_tank"; break; } HideSurface(partSurf[part].c_str()); PlayEffect(explodeFX, animator.GetJointHandle(partJoint[part].c_str())); PlayEffect(trailFX, animator.GetJointHandle(partJoint[part].c_str()), true); // make sure it plays this pain actionTimerPain.Reset(actionTime); } /* rvMonsterHarvester::CanTurn */ bool rvMonsterHarvester::CanTurn(void) const { if (!idAI::CanTurn()) { return false; } return (move.anim_turn_angles != 0.0f || move.fl.moving); } /* rvMonsterHarvester::GetDamageForLocation */ int rvMonsterHarvester::GetDamageForLocation(int damage, int location) { // If the part was hit only do damage to it const char *dmgGroup = GetDamageGroup(location); if (dmgGroup) { for (int part = 0; part < PARTS_MAX; part++) { if (idStr::Icmp(dmgGroup, partLocation[part].c_str()) == 0) { if (partHealth[part] > 0) { partHealth[part] -= damage; painAnim = "pain"; if (partHealth[part] <= 0) { if (animPrefix.Length() && (part == PART_LEG_FR || part == PART_LEG_FL || part == PART_LEG_BR || part == PART_LEG_BL)) { // just blew off a leg and already had one blown off... DestroyPart(part); // we dead health = 0; return damage; } else { // FIXME: big pain? DestroyPart(part); } } else { if (!animPrefix.Length()) { switch (part) { case PART_LEG_FR: painAnim = "leg_pain_fr"; break; case PART_LEG_FL: painAnim = "leg_pain_fl"; break; case PART_LEG_BR: painAnim = "leg_pain_br"; break; case PART_LEG_BL: painAnim = "leg_pain_bl"; break; } } } if (pain.threshold < damage && health > 0) // if ( move.anim_turn_angles == 0.0f ) { // not in the middle of a turn AnimTurn(0, true); PerformAction("Torso_Pain", 2, true); } } // pain.takenThisFrame = damage; return 0; } } } if (health <= spawnArgs.GetInt("death_damage_threshold") && spawnArgs.GetInt("death_damage_threshold") > damage) { // doesn't meet the minimum damage requirements to kill us return 0; } return idAI::GetDamageForLocation(damage, location); } /* rvMonsterHarvester::Damage */ void rvMonsterHarvester::Damage(idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location) { if (attacker == this) { // don't take damage from ourselves return; } idAI::Damage(inflictor, attacker, dir, damageDefName, damageScale, location); } /* rvMonsterHarvester::CheckAction_SprayAttack */ bool rvMonsterHarvester::CheckAction_SprayAttack(rvAIAction *action, int animNum) { if (!enemy.ent || !enemy.fl.inFov || !CheckFOV(GetEnemy()->GetEyePosition(), 20.0f)) { return false; } if (!IsEnemyRecentlyVisible() || enemy.ent->DistanceTo(enemy.lastKnownPosition) > 128.0f) { return false; } if (GetEnemy()->GetPhysics()->GetLinearVelocity().Compare(vec3_origin)) { // not moving return false; } return true; } /* rvMonsterHarvester::CheckAction_RocketAttack */ bool rvMonsterHarvester::CheckAction_RocketAttack(rvAIAction *action, int animNum) { if (!enemy.ent) { return false; } if (!IsEnemyRecentlyVisible() || enemy.ent->DistanceTo(enemy.lastKnownPosition) > 128.0f) { return false; } return true; } /* rvMonsterHarvester::CheckAction_GrenadeAttack */ bool rvMonsterHarvester::CheckAction_GrenadeAttack(rvAIAction *action, int animNum) { if (!enemy.ent || CheckFOV(GetEnemy()->GetEyePosition(), 270.0f)) { return false; } if (!IsEnemyRecentlyVisible() || enemy.ent->DistanceTo(enemy.lastKnownPosition) > 128.0f) { return false; } return true; } /* rvMonsterHarvester::CheckAction_WhipAttack */ bool rvMonsterHarvester::CheckAction_WhipAttack(rvAIAction *action, int animNum) { if (!enemy.ent) { return false; } return true; } /* rvMonsterHarvester::CheckAction_MeleeAttack */ bool rvMonsterHarvester::CheckAction_MeleeAttack(rvAIAction *action, int animNum) { if (!enemy.ent || !enemy.fl.inFov) { return false; } if (!CheckFOV(enemy.ent->GetPhysics()->GetOrigin(), 90)) { return false; } if (!GetMeleeAttackAnim(enemy.ent->GetEyePosition())) { return false; } return true; } /* rvMonsterHarvester::CheckAction_RangedAttack */ bool rvMonsterHarvester::CheckAction_RangedAttack(rvAIAction *action, int animNum) { return (idAI::CheckAction_RangedAttack(action, animNum) && enemy.ent && GetRangedAttackAnim(enemy.ent->GetEyePosition())); } /* rvMonsterHarvester::CheckActions */ bool rvMonsterHarvester::CheckActions(void) { // such a dirty hack... I'm not sure what is actually wrong, but somehow nextTurnTime is getting to be a rediculously high number. // I have some more significant bugs that really need to be solved, so for now, this will have to do. if (nextTurnTime > gameLocal.time + 500) { nextTurnTime = gameLocal.time - 1; } // If not moving, try turning in place if (!move.fl.moving && gameLocal.time > nextTurnTime) { float turnYaw = idMath::AngleNormalize180(move.ideal_yaw - move.current_yaw); if (turnYaw > lookMax[YAW] * 0.6f || (turnYaw > 0 && GetEnemy() && !enemy.fl.inFov)) { PerformAction("Torso_TurnLeft90", 4, true); return true; } else if (turnYaw < -lookMax[YAW] * 0.6f || (turnYaw < 0 && GetEnemy() && !enemy.fl.inFov)) { PerformAction("Torso_TurnRight90", 4, true); return true; } } if (CheckPainActions()) { return true; } if (PerformAction(&actionWhipAttack, (checkAction_t)&rvMonsterHarvester::CheckAction_WhipAttack, NULL)) { return true; } if (PerformAction(&actionSprayAttack, (checkAction_t)&rvMonsterHarvester::CheckAction_SprayAttack, &actionTimerRangedAttack)) { return true; } if (PerformAction(&actionRocketAttack, (checkAction_t)&rvMonsterHarvester::CheckAction_RocketAttack, &actionTimerRangedAttack)) { return true; } if (PerformAction(&actionGrenadeAttack, (checkAction_t)&rvMonsterHarvester::CheckAction_GrenadeAttack, &actionTimerRangedAttack)) { return true; } return idAI::CheckActions(); } /* rvMonsterHarvester::FilterTactical */ int rvMonsterHarvester::FilterTactical(int availableTactical) { return availableTactical & (AITACTICAL_TURRET_BIT | AITACTICAL_RANGED_BITS | AITACTICAL_MELEE_BIT); } /* States */ CLASS_STATES_DECLARATION(rvMonsterHarvester) STATE("State_Killed", rvMonsterHarvester::State_Killed) STATE("State_Dead", rvMonsterHarvester::State_Dead) STATE("Torso_WhipAttack", rvMonsterHarvester::State_Torso_WhipAttack) STATE("Torso_ClawAttack", rvMonsterHarvester::State_Torso_ClawAttack) STATE("Torso_RangedAttack", rvMonsterHarvester::State_Torso_RangedAttack) STATE("Torso_TurnRight90", rvMonsterHarvester::State_Torso_TurnRight90) STATE("Torso_TurnLeft90", rvMonsterHarvester::State_Torso_TurnLeft90) STATE("Torso_SprayAttack", rvMonsterHarvester::State_Torso_SprayAttack) STATE("Torso_RocketAttack", rvMonsterHarvester::State_Torso_RocketAttack) END_CLASS_STATES /* rvMonsterHarvester::State_Killed */ stateResult_t rvMonsterHarvester::State_Killed(const stateParms_t &parms) { DisableAnimState(ANIMCHANNEL_LEGS); int numLegsLost = 0; for (int i = PART_LEG_FR; i <= PART_LEG_BL; i++) { if (partHealth[i] <= 0) { numLegsLost++; } } if (numLegsLost > 1) { // dmg_death when 2 legs are blown off PlayAnim(ANIMCHANNEL_TORSO, "dmg_death", 0); } else { PlayAnim(ANIMCHANNEL_TORSO, "death", 0); } PostState("State_Dead"); return SRESULT_DONE; } /* rvMonsterHarvester::State_Dead */ stateResult_t rvMonsterHarvester::State_Dead(const stateParms_t &parms) { if (!AnimDone(ANIMCHANNEL_TORSO, 0)) { // Make sure all animation stops StopAnimState(ANIMCHANNEL_TORSO); StopAnimState(ANIMCHANNEL_LEGS); if (head) { StopAnimState(ANIMCHANNEL_HEAD); } return SRESULT_WAIT; } return idAI::State_Dead(parms); } /* rvMonsterHarvester::State_Torso_WhipAttack */ stateResult_t rvMonsterHarvester::State_Torso_WhipAttack(const stateParms_t &parms) { enum { STAGE_ATTACK, STAGE_ATTACK_WAIT, }; switch (parms.stage) { case STAGE_ATTACK: { if (!enemy.ent) { return SRESULT_DONE; } idEntity *ent; int i; for (i = 0; i < WHIP_MAX; i++) { gameLocal.SpawnEntityDef(*gameLocal.FindEntityDefDict(spawnArgs.GetString("def_attack_whip")), &ent, false); idProjectile *proj = dynamic_cast<idProjectile *>(ent); if (!proj) { delete ent; continue; } proj->Create(this, vec3_origin, idVec3(0, 0, 1)); proj->Launch(vec3_origin, idVec3(0, 0, 1), vec3_origin); whipProjectiles[i] = proj; ent->BindToJoint(this, whipJoints[i], false); ent->SetOrigin(vec3_origin); ent->SetAxis(mat3_identity); } DisableAnimState(ANIMCHANNEL_LEGS); PlayAnim(ANIMCHANNEL_TORSO, "range_attack", parms.blendFrames); return SRESULT_STAGE(STAGE_ATTACK_WAIT); } case STAGE_ATTACK_WAIT: if (AnimDone(ANIMCHANNEL_TORSO, parms.blendFrames)) { int i; for (i = 0; i < WHIP_MAX; i++) { delete whipProjectiles[i]; whipProjectiles[i] = NULL; } return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::Attack */ bool rvMonsterHarvester::Attack(const char *attackName, jointHandle_t joint, idEntity *target, const idVec3 &pushVelocity) { // NOTE: this stops spawning of projectile, but not muzzle flash... oh well... if (joint == jointLeftMuzzle && partHealth[PART_ARM_L] <= 0) { // can't fire from this muzzle - arm gone return false; } if (joint == jointRightMuzzle && partHealth[PART_ARM_R] <= 0) { // can't fire from this muzzle - arm gone return false; } return idAI::Attack(attackName, joint, target, pushVelocity); } /* rvMonsterHarvester::GetMeleeAttackAnim */ const char *rvMonsterHarvester::GetMeleeAttackAnim(const idVec3 &target) { idVec3 dir; idVec3 localDir; float yaw; const char *animName; // Get the local direction vector dir = target - GetPhysics()->GetOrigin(); dir.Normalize(); viewAxis.ProjectVector(dir, localDir); // Get the yaw relative to forward yaw = idMath::AngleNormalize180(localDir.ToAngles()[YAW]); if (yaw < -10.0f) { if (partHealth[PART_LEG_FR] <= 0) { return NULL; } animName = "attack_rleg_fw_rt"; } else if (yaw > 10.0f) { if (partHealth[PART_LEG_FL] <= 0) { return NULL; } animName = "attack_lleg_fw_lt"; } else { if (gameLocal.random.RandomFloat() < 0.5f || partHealth[PART_LEG_FR] <= 0) { if (partHealth[PART_LEG_FL] <= 0) { return NULL; } animName = "attack_lleg_fw"; } else { if (partHealth[PART_LEG_FR] <= 0) { return NULL; } animName = "attack_rleg_fw"; } } return animName; } /* rvMonsterHarvester::PlayMeleeAttackAnim */ bool rvMonsterHarvester::PlayMeleeAttackAnim(const idVec3 &target, int blendFrames) { const char *animName = GetMeleeAttackAnim(target); if (animName) { PlayAnim(ANIMCHANNEL_TORSO, animName, blendFrames); return true; } return false; } /* rvMonsterHarvester::GetRangedAttackAnim */ const char *rvMonsterHarvester::GetRangedAttackAnim(const idVec3 &target) { idVec3 dir; idVec3 localDir; float yaw; const char *animName = NULL; // Get the local direction vector dir = target - GetPhysics()->GetOrigin(); dir.Normalize(); viewAxis.ProjectVector(dir, localDir); // Get the yaw relative to forward yaw = idMath::AngleNormalize180(localDir.ToAngles()[YAW]); if (yaw < -20.0f) { if (partHealth[PART_ARM_R] <= 0) { return NULL; } animName = "fire_right"; } else if (yaw > 20.0f) { if (partHealth[PART_ARM_L] <= 0) { return NULL; } animName = "fire_left"; } else { animName = "fire_forward"; } return animName; } /* rvMonsterHarvester::PlayRangedAttackAnim */ bool rvMonsterHarvester::PlayRangedAttackAnim(const idVec3 &target, int blendFrames) { const char *animName = GetRangedAttackAnim(target); if (animName) { if (!move.fl.moving) { DisableAnimState(ANIMCHANNEL_LEGS); } PlayAnim(ANIMCHANNEL_TORSO, animName, blendFrames); return true; } return false; } /* rvMonsterHarvester::State_Torso_ClawAttack */ stateResult_t rvMonsterHarvester::State_Torso_ClawAttack(const stateParms_t &parms) { enum { STAGE_ATTACK, STAGE_ATTACK_WAIT, }; switch (parms.stage) { case STAGE_ATTACK: { if (!enemy.ent) { return SRESULT_DONE; } // Predict a bit if (!PlayMeleeAttackAnim(enemy.ent->GetEyePosition(), parms.blendFrames)) { return SRESULT_DONE; } return SRESULT_STAGE(STAGE_ATTACK_WAIT); } case STAGE_ATTACK_WAIT: if (AnimDone(ANIMCHANNEL_TORSO, parms.blendFrames)) { // animator.ClearAllJoints ( ); // leftChainOut = false; // rightChainOut = false; return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::State_Torso_RangedAttack */ stateResult_t rvMonsterHarvester::State_Torso_RangedAttack(const stateParms_t &parms) { enum { STAGE_INIT, STAGE_ATTACK, STAGE_ATTACK_WAIT, }; switch (parms.stage) { case STAGE_INIT: if (!enemy.ent) { return SRESULT_DONE; } shots = (minShots + gameLocal.random.RandomInt(maxShots - minShots + 1)) * combat.aggressiveScale; return SRESULT_STAGE(STAGE_ATTACK); case STAGE_ATTACK: if (!enemy.ent || !PlayRangedAttackAnim(enemy.ent->GetEyePosition(), 0)) { return SRESULT_DONE; } return SRESULT_STAGE(STAGE_ATTACK_WAIT); case STAGE_ATTACK_WAIT: if (AnimDone(ANIMCHANNEL_TORSO, 0)) { shots--; if (GetEnemy() && !enemy.fl.inFov) { // just stop } else if (shots > 0 || !GetEnemy()) { return SRESULT_STAGE(STAGE_ATTACK); } // animator.ClearAllJoints ( ); // leftChainOut = false; // rightChainOut = false; return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::State_Torso_TurnRight90 */ stateResult_t rvMonsterHarvester::State_Torso_TurnRight90(const stateParms_t &parms) { enum { STAGE_INIT, STAGE_WAIT }; switch (parms.stage) { case STAGE_INIT: DisableAnimState(ANIMCHANNEL_LEGS); PlayAnim(ANIMCHANNEL_TORSO, "turn_90_rt", parms.blendFrames); AnimTurn(90.0f, true); return SRESULT_STAGE(STAGE_WAIT); case STAGE_WAIT: if (move.fl.moving || AnimDone(ANIMCHANNEL_TORSO, 0) || !strstr(animator.CurrentAnim(ANIMCHANNEL_TORSO)->AnimName(), "turn_90_rt")) { AnimTurn(0, true); nextTurnTime = gameLocal.time + 250; return SRESULT_DONE; } if (GetEnemy() && !CheckFOV(GetEnemy()->GetEyePosition(), 270.0f)) { // enemy behind me if (actionGrenadeAttack.timer.IsDone(gameLocal.GetTime())) { // timer okay // toss some nades at him PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("r_side_can_tip")); Attack("grenade", animator.GetJointHandle("r_side_can_tip"), enemy.ent); PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("l_side_can_tip")); Attack("grenade", animator.GetJointHandle("l_side_can_base"), enemy.ent); PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("back_can_tip")); Attack("grenade", animator.GetJointHandle("back_can_base"), enemy.ent); actionGrenadeAttack.timer.Clear(gameLocal.GetTime() + gameLocal.random.RandomInt(1000) + 500); } } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::State_Torso_TurnLeft90 */ stateResult_t rvMonsterHarvester::State_Torso_TurnLeft90(const stateParms_t &parms) { enum { STAGE_INIT, STAGE_WAIT }; switch (parms.stage) { case STAGE_INIT: DisableAnimState(ANIMCHANNEL_LEGS); PlayAnim(ANIMCHANNEL_TORSO, "turn_90_lt", parms.blendFrames); AnimTurn(90.0f, true); return SRESULT_STAGE(STAGE_WAIT); case STAGE_WAIT: if (move.fl.moving || AnimDone(ANIMCHANNEL_TORSO, 0) || !strstr(animator.CurrentAnim(ANIMCHANNEL_TORSO)->AnimName(), "turn_90_lt")) { AnimTurn(0, true); nextTurnTime = gameLocal.time + 250; return SRESULT_DONE; } if (GetEnemy() && !CheckFOV(GetEnemy()->GetEyePosition(), 270.0f)) { // enemy behind me if (actionGrenadeAttack.timer.IsDone(gameLocal.GetTime())) { // timer okay // toss some nades at him PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("r_side_can_tip")); Attack("grenade", animator.GetJointHandle("r_side_can_tip"), enemy.ent); PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("l_side_can_tip")); Attack("grenade", animator.GetJointHandle("l_side_can_base"), enemy.ent); PlayEffect("fx_grenade_muzzleflash", animator.GetJointHandle("back_can_tip")); Attack("grenade", animator.GetJointHandle("back_can_base"), enemy.ent); actionGrenadeAttack.timer.Clear(gameLocal.GetTime() + gameLocal.random.RandomInt(1000) + 500); } } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::State_Torso_SprayAttack */ stateResult_t rvMonsterHarvester::State_Torso_SprayAttack(const stateParms_t &parms) { enum { STAGE_START, STAGE_SWEEP, STAGE_END, STAGE_FINISH }; switch (parms.stage) { case STAGE_START: DisableAnimState(ANIMCHANNEL_LEGS); sweepCount = 0; PlayAnim(ANIMCHANNEL_TORSO, "fire_forward_spray_start", 0); return SRESULT_STAGE(STAGE_SWEEP); case STAGE_SWEEP: if (AnimDone(ANIMCHANNEL_TORSO, 0)) { sweepCount++; PlayAnim(ANIMCHANNEL_TORSO, "fire_forward_spray_loop", 0); return SRESULT_STAGE(STAGE_END); } return SRESULT_WAIT; case STAGE_END: if (AnimDone(ANIMCHANNEL_TORSO, 0)) { if (enemy.fl.inFov && sweepCount < 3 && !gameLocal.random.RandomInt(2)) { return SRESULT_STAGE(STAGE_SWEEP); } else { PlayAnim(ANIMCHANNEL_TORSO, "fire_forward_spray_end", 0); return SRESULT_STAGE(STAGE_FINISH); } } return SRESULT_WAIT; case STAGE_FINISH: if (AnimDone(ANIMCHANNEL_TORSO, 0)) { return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* rvMonsterHarvester::State_Torso_RocketAttack */ stateResult_t rvMonsterHarvester::State_Torso_RocketAttack(const stateParms_t &parms) { enum { STAGE_INIT, STAGE_START_WAIT, STAGE_FIRE, STAGE_WAIT }; switch (parms.stage) { case STAGE_INIT: if (animPrefix.Length()) { // don't play an anim return SRESULT_STAGE(STAGE_FIRE); } PlayAnim(ANIMCHANNEL_TORSO, "missile_fire_start", parms.blendFrames); return SRESULT_STAGE(STAGE_START_WAIT); case STAGE_START_WAIT: if (AnimDone(ANIMCHANNEL_TORSO, 0) || idStr::Icmp("missile_fire_start", animator.CurrentAnim(ANIMCHANNEL_TORSO)->AnimName())) { return SRESULT_STAGE(STAGE_FIRE); } return SRESULT_WAIT; case STAGE_FIRE: if (partHealth[PART_TANK_L] > 0) { PlayEffect("fx_rocket_muzzleflash", animator.GetJointHandle("l_hopper_muzzle_flash")); Attack("rocket", animator.GetJointHandle("l_hopper_muzzle_flash"), enemy.ent); } if (partHealth[PART_TANK_R] > 0) { PlayEffect("fx_rocket_muzzleflash", animator.GetJointHandle("r_hopper_muzzle_flash")); Attack("rocket", animator.GetJointHandle("r_hopper_muzzle_flash"), enemy.ent); } if (animPrefix.Length()) { // don't play an anim return SRESULT_DONE; } PlayAnim(ANIMCHANNEL_TORSO, "attack_rocket", parms.blendFrames); return SRESULT_STAGE(STAGE_WAIT); case STAGE_WAIT: if (AnimDone(ANIMCHANNEL_TORSO, 0) || idStr::Icmp("attack_rocket", animator.CurrentAnim(ANIMCHANNEL_TORSO)->AnimName())) { return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; }
library ieee; use ieee.std_logic_1164.all; library std; use std.textio; use work.lib.all; entity processor_control is port ( clock : in std_logic; reset : in std_logic; alu_zero : in std_logic; mem_done : in std_logic; opcode : in opcodes; mem_src : out T_mem_src; mem_op : out T_mem_op; alu_srcA : out T_alu_srcA; alu_srcB : out T_alu_srcB; alu_cmd : out T_alu_cmd; pc_write : out std_logic; ir_write : out std_logic; pc_src : out T_pc_src; reg1_src : out T_reg1_src; reg_cmd : out T_reg_cmd; reg_src : out T_reg_src; mdr_write : out std_logic ); end entity processor_control; architecture behavior of processor_control is signal current_state : processor_state; signal next_state : processor_state; type output_vector is record mem_src : T_mem_src; mem_op : T_mem_op; alu_srcA : T_alu_srcA; alu_srcB : T_alu_srcB; alu_cmd : T_alu_cmd; -- not always constant pc_write : std_logic; -- not always constant ir_write : std_logic; -- not always constant pc_src : T_pc_src; reg1_src : T_reg1_src; reg_cmd : T_reg_cmd; -- not always constant reg_src : T_reg_src; mdr_write : std_logic; -- not always constant end record; type output_array is array (processor_state) of output_vector; -- Note: the following entries are not constant and will be handled later -- in the code. They are: -- * fetch(pc_write) -- * fetch(ir_write) -- * r_execute(alu_cmd) -- * branch_completion(pc_write) -- * load_execute(mdr_write) -- * i_execute(reg_cmd) -- * shift_execute(alu_cmd) constant outputs : output_array := (fetch => (pc, read, pc, incr, add, '1', '1', alu, rs1, none, alu_out, '0'), decode => (pc, none, A, B, add, '0', '0', alu, rs1, none, alu_out, '0'), r_execute => (pc, none, A, B, add, '0', '0', alu, rs1, none, alu_out, '0'), r_save => (pc, none, A, B, add, '0', '0', alu, rs1, word, alu_out, '0'), branch_execute => (pc, none, A, B, sub, '0', '0', alu, rd, none, alu_out, '0'), branch_completion => (pc, none, A, B, add, '0', '0', A, rs1, none, alu_out, '0'), store => (A, write, A, B, add, '0', '0', alu, rs1, none, alu_out, '0'), load_execute => (A, read, A, B, add, '0', '0', alu, rs1, none, alu_out, '1'), load_save => (pc, none, A, B, add, '0', '0', alu, rs1, word, mdr, '0'), call => (pc, none, A, B, add, '1', '0', A, rs1, word, pc, '0'), jump => (pc, none, A, B, add, '1', '0', imm, rs1, none, alu_out, '0'), i_execute => (pc, none, A, B, add, '0', '0', alu, rs1, none, imm, '0'), shift_execute => (pc, none, A, imm, add, '0', '0', alu, rs1, none, alu_out, '0'), shift_save => (pc, none, A, B, add, '0', '0', alu, rs1, word, alu_out, '0')); begin -- behavior sync : process (clock, reset) variable l : textio.line; begin -- process sync if reset = '0' then current_state <= fetch; elsif rising_edge(clock) then current_state <= next_state; textio.write(l, now); textio.write(l, string'(" Entering state " & processor_state'image(next_state) & "**************************")); textio.writeline(textio.output, l); end if; end process sync; fsm : process (current_state, mem_done, opcode) begin -- process fsm -- report "fsm update" severity note; case current_state is when fetch => case mem_done is when '1' => next_state <= decode; when others => next_state <= fetch; end case; when decode => case opcode is when add | sub | aand => next_state <= r_execute; when nnor | mult | slt => next_state <= r_execute; when bne | beq => next_state <= branch_execute; when call => next_state <= call; when jump => next_state <= jump; when load => next_state <= load_execute; when store => next_state <= store; when lui | li => next_state <= i_execute; when shl | shr => next_state <= shift_execute; when others => null; end case; when r_execute => next_state <= r_save; when r_save => next_state <= fetch; when branch_execute => next_state <= branch_completion; when branch_completion => next_state <= fetch; when store => next_state <= fetch; when load_save => next_state <= fetch; when call => next_state <= fetch; when jump => next_state <= fetch; when i_execute => next_state <= fetch; when shift_execute => next_state <= shift_save; when shift_save => next_state <= fetch; when load_execute => case mem_done is when '1' => next_state <= load_save; when others => next_state <= load_execute; end case; when others => null; end case; end process fsm; output : process (current_state, mem_done, opcode, alu_zero) variable tmp : output_vector; begin -- process output tmp := outputs(current_state); case current_state is when decode | r_save | branch_execute | store | load_save | call | jump | shift_save => (mem_src, mem_op, alu_srcA, alu_srcB, alu_cmd, pc_write, ir_write, pc_src, reg1_src, reg_cmd, reg_src, mdr_write) <= outputs(current_state); when fetch => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= tmp.alu_cmd; pc_write <= mem_done; ir_write <= mem_done; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= tmp.reg_cmd; reg_src <= tmp.reg_src; mdr_write <= tmp.mdr_write; when r_execute => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= r_to_arith(opcode); pc_write <= tmp.pc_write; ir_write <= tmp.ir_write; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= tmp.reg_cmd; reg_src <= tmp.reg_src; mdr_write <= tmp.mdr_write; when branch_completion => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= tmp.alu_cmd; pc_write <= branch_to_pc(opcode, alu_zero); ir_write <= tmp.ir_write; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= tmp.reg_cmd; reg_src <= tmp.reg_src; mdr_write <= tmp.mdr_write; when load_execute => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= tmp.alu_cmd; pc_write <= tmp.pc_write; ir_write <= tmp.ir_write; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= tmp.reg_cmd; reg_src <= tmp.reg_src; mdr_write <= mem_done; when i_execute => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= tmp.alu_cmd; pc_write <= tmp.pc_write; ir_write <= tmp.ir_write; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= i_to_reg(opcode); reg_src <= tmp.reg_src; mdr_write <= tmp.mdr_write; when shift_execute => mem_src <= tmp.mem_src; mem_op <= tmp.mem_op; alu_srcA <= tmp.alu_srcA; alu_srcB <= tmp.alu_srcB; alu_cmd <= shift_to_arith(opcode); pc_write <= tmp.pc_write; ir_write <= tmp.ir_write; pc_src <= tmp.pc_src; reg1_src <= tmp.reg1_src; reg_cmd <= tmp.reg_cmd; reg_src <= tmp.reg_src; mdr_write <= tmp.mdr_write; when others => null; end case; end process output; end behavior;
// TEST: pass // TYPE: expr /* STDOUT: hi 123! bla u 6 äöü e1 e2 e3 e4 e5 e6 e7 */ fn printf {C} (fmt:*u8,...) : i32; fn abort {C} () : void; fn assert(e:bool) : void { if (!e) abort(); }; var a : u32 = 123; var b : u32; b = a + b + 5; if (b != 128) abort(); printf(&"hi %d!\n"[], 123); printf(&"%s %c\n"[], &"bla"[], "hu"[1]); var c : u32[10]; c[3] = 1; c[4] = 5; printf(&"%d\n"[], c[3] + c[4]); // must not return pointers to temporaries var sc : u32[] = c[]; if (&sc[] != &c[0]) abort(); // arrays are values, slices are fat pointers var d = c; d[3] = 2; if (c[3] == d[3] || d[3] != 2) abort(); if (c[3] != sc[3]) abort(); //var e : u32[] = (&c[0])[0..10]; assert(#"abc" == 3); assert(#sc == 10); assert(#c == 10); var bla = "abc\n\td"; assert(#bla == 6 && bla[3] == '\n' && bla[5] == 'd'); printf(&"äöü\n"[]); // check some stuff about sideeffects (see checked output in STDOUT test header) fn ok(a:u32) : bool { printf(&"e%d\n"[], a); return true; }; fn notok() : bool { abort(); return false; }; assert((ok(1) || notok()) == true); assert((ok(2) && ok(3)) == true); assert((ok(4) ? ok(5) : notok()) == true); assert((!ok(6) ? notok() : ok(7)) == true); assert((true ? 1 : 2) == 1); assert((false ? 1 : 2) == 2); var i : u32 = 5; var u : u32; u = 2; while (i) { i = i - 1; u = u * 2; }; assert(u == 64); struct foo { a : u32 = 123; b : u16; //c, d, e : u16; }; var z : foo = (foo) { .b = 1 } ; assert(z.a == 123 && z.b == 1); var az : u32[4] = (u32[4]) { 1, 2 }; assert(az[0] == 1 && az[1] == 2 && az[2] == 0 && az[3] == 0); var az2 : u32[] = (u32[]) { 1, 2 }; assert(#az2 == 2); assert(az2[0] == 1 && az2[1] == 2); var t : (u32, u16); var t2 : (u32, u16); t = t2; var az3 : foo[3] = (foo[3]) { }; assert((az3[0]).a == 123); var az4 : foo[3]; assert((az4[0]).a == 123); // void values/types are first class var v : void = (); fn vfn(z:void):void { var x : () = z; return z; }; v = vfn(v);
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { UsersModule } from './users/users.module'; import { TypeOrmModule } from '@nestjs/typeorm'; import { BooksModule } from './books/books.module'; import { AuthModule } from './auth/auth.module'; import 'dotenv/config'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: process.env.HOSTNAME_DB, username: process.env.USERNAME_DB, password: process.env.PASSWORD_DB, port: 3306, database: process.env.NAME_DB, entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), AuthModule, UsersModule, BooksModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
import React, { useState } from 'react'; import SubmitButton from '../SubmitButton'; import DateTimePicker from 'react-datetime-picker'; import { addHours, addMinutes } from 'date-fns'; import styled from 'styled-components'; const FormWrapper = styled.div` & > form > div { margin-bottom: 11px; } `; const DateTimePickerWrapper = styled.div` & .react-datetime-picker { max-width: 280px; width: 100%; } & .react-datetime-picker__wrapper { padding: 7px 11px; border-radius: 5px; } `; const InputForm = ({ setSelectedTimestamp }) => { const [selectedTimestamp, onDateChange] = useState( addMinutes(new Date(), 15) ); const handleOnSaveTimer = (event) => { event.preventDefault(); localStorage.setItem('selectedTimestamp', selectedTimestamp); setSelectedTimestamp(selectedTimestamp); }; return ( <FormWrapper> <form> <div> <label htmlFor="chosen-date">When should your timer end?</label> </div> <DateTimePickerWrapper> <DateTimePicker onChange={onDateChange} maxDate={addHours(new Date(), 24)} minDate={new Date()} minTime={new Date()} value={selectedTimestamp} minDetails="hour" maxDetails="second" clearIcon={null} showLeadingZeros /> </DateTimePickerWrapper> <div className="button-row"> <SubmitButton onClickFn={handleOnSaveTimer} /> </div> </form> </FormWrapper> ); }; export default InputForm;
.. _oran-o2-application-b50a0c899e66: O-RAN O2 Application .. rubric:: |context| In the context of hosting a |RAN| Application on |prod|, the |O-RAN| O2 Application provides and exposes the |IMS| and |DMS| service APIs of the O2 interface between the O-Cloud (|prod|) and the Service Management & Orchestration (SMO), in the |O-RAN| Architecture. The O2 interfaces enable the management of the O-Cloud (|prod|) infrastructure and the deployment life-cycle management of |O-RAN| cloudified |NFs| that run on O-Cloud (|prod|). See `O-RAN O2 General Aspects and Principles 2.0 <https://orandownloadsweb.azurewebsites.net/specifications>`__, and `INF O2 documentation <https://docs.o-ran-sc.org/projects/o-ran-sc-pti-o2/en/latest/>`__. The |O-RAN| O2 application is integrated into |prod| as a system application. The |O-RAN| O2 application package is saved in |prod| during system installation, but it is not applied by default. System administrators can follow the procedures below to install and uninstall the |O-RAN| O2 application. .. contents:: :local: :depth: 1 ------- Install ------- .. rubric:: |prereq| Configure the internal Ceph storage for the O2 application persistent storage, see |stor-doc|: :ref:`Configure the Internal Ceph Storage Backend <configure-the-internal-ceph-storage-backend>`. Enable |PVC| support in ``oran-o2`` namespace, see |stor-doc|: :ref:`Enable ReadWriteOnce PVC Support in Additional Namespaces <enable-readwriteonce-pvc-support-in-additional-namespaces>`. .. rubric:: |proc| You can install |O-RAN| O2 application on |prod| from the command line. #. Locate the O2 application tarball in ``/usr/local/share/applications/helm``. For example: .. code-block:: bash /usr/local/share/applications/helm/oran-o2-<version>.tgz #. Download ``admin_openrc.sh`` from the |prod| admin dashboard. * Visit `http://<oam-floating-ip-address>:8080/project/api_access/` * Click the **Download OpenStack RC File"/"OpenStack RC File** button #. Copy the file to the controller host. #. Source the platform environment. .. code-block:: bash $ source ./admin_openrc.sh ~(keystone_admin)]$ #. Upload the application. .. code-block:: bash ~(keystone_admin)]$ system application-upload /usr/local/share/applications/helm/oran-o2-<version>.tgz #. Prepare the override ``yaml`` file. #. Create a service account for |SMO| application. Create a `ServiceAccount` which can be used to provide |SMO| application with minimal access permission credentials. .. code-block:: bash export SMO_SERVICEACCOUNT=smo1 cat <<EOF > smo-serviceaccount.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: pod-reader rules: - apiGroups: [""] # "" indicates the core API group resources: ["pods"] verbs: ["get", "watch", "list"] --- apiVersion: v1 kind: ServiceAccount metadata: name: ${SMO_SERVICEACCOUNT} namespace: default --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: read-pods namespace: default roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: pod-reader subjects: - kind: ServiceAccount name: ${SMO_SERVICEACCOUNT} namespace: default EOF kubectl apply -f smo-serviceaccount.yaml #. Create a secret for service account and obtain an access token. Create a secret with the type `service-account-token` and pass the `ServiceAccount` in the annotation section as shown below: .. code-block:: bash export SMO_SECRET=smo1-secret cat <<EOF > smo-secret.yaml apiVersion: v1 kind: Secret metadata: name: ${SMO_SECRET} annotations: kubernetes.io/service-account.name: ${SMO_SERVICEACCOUNT} type: kubernetes.io/service-account-token EOF kubectl apply -f smo-secret.yaml export SMO_TOKEN_DATA=$(kubectl get secrets $SMO_SECRET -o jsonpath='{.data.token}' | base64 -d -w 0) #. Create certificates for the O2 service. Obtain an intermediate or Root CA-signed certificate and key from a trusted intermediate or Root Certificate Authority (CA). Refer to the documentation for the external Root |CA| that you are using on how to create a public certificate and private key pairs signed by an intermediate or Root |CA| for HTTPS. For lab purposes, see |sec-doc|: :ref:`Create Certificates Locally using openssl <create-certificates-locally-using-openssl>` to create an Intermediate or test Root |CA| certificate and key, and use it to locally sign test certificates. The resulting files, from either an external |CA| or locally generated for the lab with openssl, should be: * Local |CA| certificate - ``my-root-ca-cert.pem`` * Server certificate - ``my-server-cert.pem`` * Server key - ``my-server-key.pem`` .. note:: If using a server certificate signed by a local |CA| (i.e. lab scenario above), this local |CA| certificate (e.g. my-root-ca-cert.pem from lab scenario above) must be shared with the |SMO| application for the O2 server certificate verification. #. Prepare the O2 service application configuration file. As per the Cloudification and Orchestration use case defined in O-RAN Working Group 6, the following information should be generated by |SMO|: * O-Cloud Gload ID - ``OCLOUD_GLOBAL_ID`` * SMO Register URL - ``SMO_REGISTER_URL`` See `O-RAN Cloudification and Orchestration Use Cases and Requirements for O-RAN Virtualized RAN <https://orandownloadsweb.azurewebsites.net/specifications>`__. .. code-block:: bash API_HOST_EXTERNAL_FLOATING=$(echo ${OS_AUTH_URL} | awk -F / '{print $3}' | cut -d: -f1) cat <<EOF > app.conf [DEFAULT] ocloud_global_id = ${OCLOUD_GLOBAL_ID} smo_register_url = ${SMO_REGISTER_URL} smo_token_data = ${SMO_TOKEN_DATA} [OCLOUD] OS_AUTH_URL = ${OS_AUTH_URL} OS_USERNAME = ${OS_USERNAME} OS_PASSWORD = ${OS_PASSWORD} API_HOST_EXTERNAL_FLOATING = ${API_HOST_EXTERNAL_FLOATING} [API] [WATCHER] [PUBSUB] EOF #. Retrieve the |CA| certificate from your |SMO| vendor. If the |SMO| application provides service via HTTPS, and the server certificate is self-signed, the |CA| certficate should be retrieved from the |SMO|. This procedure assumes that the name of the certificate is ``smo-ca.pem`` #. Populate the override yaml file. Refer to the previous step for the required override values. .. code-block:: bash APPLICATION_CONFIG=$(base64 app.conf -w 0) SERVER_CERT=$(base64 my-server-cert.pem -w 0) SERVER_KEY=$(base64 my-server-key.pem -w 0) SMO_CA_CERT=$(base64 smo-ca.pem -w 0) cat <<EOF > o2service-override.yaml applicationconfig: ${APPLICATION_CONFIG} servercrt: ${SERVER_CERT} serverkey: ${SERVER_KEY} smocacrt: ${SMO_CA_CERT} EOF To deploy other versions of an image required for a quick solution, to have early access to the features (eg. oranscinf/pti-o2imsdms:|v_oranscinf-pti-o2imsdms|), and to authenticate images that are hosted by a private registry, follow the steps below: #. Create a `docker-registry` secret in ``oran-o2`` namespace. .. code-block:: bash export O2SERVICE_IMAGE_REG=<docker-server-endpoint> kubectl create secret docker-registry private-registry-key \ --docker-server=${O2SERVICE_IMAGE_REG} --docker-username=${USERNAME} \ --docker-password=${PASSWORD} -n oran-o2 #. Refer to the ``imagePullSecrets`` in override file. .. parsed-literal:: cat <<EOF > o2service-override.yaml imagePullSecrets: - private-registry-key o2ims: serviceaccountname: admin-oran-o2 images: tags: o2service: ${O2SERVICE_IMAGE_REG}/docker.io/oranscinf/pti-o2imsdms:|v_oranscinf-pti-o2imsdms| postgres: ${O2SERVICE_IMAGE_REG}/docker.io/library/postgres:9.6 redis: ${O2SERVICE_IMAGE_REG}/docker.io/library/redis:alpine pullPolicy: IfNotPresent logginglevel: "DEBUG" applicationconfig: ${APPLICATION_CONFIG} servercrt: ${SERVER_CERT} serverkey: ${SERVER_KEY} smocacrt: ${SMO_CA_CERT} EOF #. Update the overrides for the oran-o2 application. .. code-block:: bash ~(keystone_admin)]$ system helm-override-update oran-o2 oran-o2 oran-o2 --values o2service-override.yaml # Check the overrides ~(keystone_admin)]$ system helm-override-show oran-o2 oran-o2 oran-o2 #. Run the :command:`system application-apply` command to apply the updates. .. code-block:: bash ~(keystone_admin)]$ system application-apply oran-o2 #. Monitor the status using the command below. .. code-block:: bash ~(keystone_admin)]$ watch -n 5 system application-list OR .. code-block:: bash ~(keystone_admin)]$ watch kubectl get all -n oran-o2 .. rubric:: |result| You have launched services in the above namespace. .. rubric:: |postreq| You will need to integrate |prod| with an |SMO| application that performs management of O-Cloud infrastructure and the deployment life cycle management of O-RAN cloudified |NFs|. See the following API reference for details: - `API O-RAN O2 interface <https://docs.o-ran-sc.org/projects/o-ran-sc-pti-o2/en/g-release/api.html>`__ --------- Uninstall --------- .. rubric:: |proc| You can uninstall the |O-RAN| O2 application on |prod| from the command line. #. Uninstall the application. Remove O2 application related resources. .. code-block:: bash ~(keystone_admin)]$ system application-remove oran-o2 #. Delete the application. Remove the uninstalled O2 application’s definition, including the manifest and helm charts and helm chart overrides, from the system. .. code-block:: bash ~(keystone_admin)]$ system application-delete oran-o2 .. rubric:: |result| You have uninstalled the O2 application from the system.
from flet import * from utils.colors import * from utils.validation import Validator class Signup(Container): def __init__(self, page: Page): super().__init__() self.alignment = alignment.center self.validator = Validator() self.expand = True self.bgcolor = blue self.error_border = border.all(width=1,color='red') self.name_box = Container( content= TextField( border=InputBorder.NONE, content_padding=padding.only( top=0, bottom=0, right=0,left=0 ), hint_style=TextStyle( size=12, color='#858796' ), hint_text='Seu nome completo', text_style=TextStyle( size=14, color='black' ), ), border=border.all(width=1, color='#bdcbf4'), border_radius=30 ) self.email_box = Container( content= TextField( border=InputBorder.NONE, content_padding=padding.only( top=0, bottom=0, right=0,left=0 ), hint_style=TextStyle( size=12, color='#858796' ), hint_text='Entre com seu email...', text_style=TextStyle( size=14, color='black' ), ), border=border.all(width=1, color='#bdcbf4'), border_radius=30 ) self.password_box = Container( content=TextField( border=InputBorder.NONE, content_padding=padding.only( top=0, bottom=0, right=0, left=0 ), hint_style=TextStyle( size=12, color='#858796' ), hint_text='Senha...', text_style=TextStyle( size=14, color='black' ), password=True ), border=border.all(width=1, color='#bdcbf4'), border_radius=30 ) Container( content=Text( value='Login' ) ) self.content = Column( alignment='center', horizontal_alignment='center', controls=[ Container( width=500, padding=40, bgcolor='white', content=Column( horizontal_alignment='center', controls=[ Text( value="Criar uma conta!", size=16, color='black', text_align='center' ), Container(height=0), self.name_box, self.email_box, self.password_box, Container(height=0), Container( alignment=alignment.center, bgcolor='#4e73df', height=40, border_radius=30, content=Text( value='Criar a conta' ), on_click=self.signup ), Container( content=Text( value='Esqueci a senha', color='#4e73df', size=12 ), on_click=lambda _: self.page.go( '/forgotpassword' ) ), Container( content=Text( value='Já tem a conta? Fazer Login!', color='#4e73df', size=12 ), on_click=lambda _: self.page.go( '/login' ) ), ] ) ) ] ) def signup(self,e): if not self.validator.is_correct_name(self.name_box.content.value): self.name_box.border = self.error_border self.name_box.update()
/** * Copyright (c) 2015, Lucee Assosication Switzerland. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime.orm; import lucee.runtime.Component; import lucee.runtime.PageContext; import lucee.runtime.db.DataSource; import lucee.runtime.exp.PageException; import lucee.runtime.type.Array; import lucee.runtime.type.Query; import lucee.runtime.type.Struct; public interface ORMSession { /** * flush all elements in all sessions (for all datasources) * * @param pc * @throws PageException */ public void flushAll(PageContext pc) throws PageException; /** * flush all elements in the default sessions * * @param pc * @throws PageException */ public void flush(PageContext pc) throws PageException; /** * flush all elements in a specific sessions defined by datasource name * * @param pc * @throws PageException */ public void flush(PageContext pc, String datasource) throws PageException; /** * delete elememt from datasource * * @param pc * @param obj * @throws PageException */ public void delete(PageContext pc, Object obj) throws PageException; /** * insert entity into datasource, even the entry already exist * * @param pc * @param obj * @param forceInsert * @throws PageException */ public void save(PageContext pc, Object obj, boolean forceInsert) throws PageException; /** * Reloads data for an entity that is already loaded. This method refetches * data from the database and repopulates the entity with the refreshed * data. * * @param obj */ public void reload(PageContext pc, Object obj) throws PageException; /** * creates a entity matching the given name * * @param entityName * @return */ public Component create(PageContext pc, String entityName) throws PageException; /** * Attaches the specified entity to the current ORM session. It copies the * state of the given object onto the persistent object with the same * identifier and returns the persistent object. * If there is no persistent instance currently associated with the session, * it is loaded. The given instance is not associated with the session. User * have to use the returned object from this session. * * @param pc * @param obj * @throws PageException */ public Component merge(PageContext pc, Object obj) throws PageException; /** * clear all elements in the default sessions * * @param pc * @throws PageException */ public void clear(PageContext pc) throws PageException; /** * clear all elements in a specific sessions defined by datasource name * * @param pc * @param dataSource * @throws PageException */ public void clear(PageContext pc, String dataSource) throws PageException; /** * load and return a Object that match given filter, if there is more than * one Object matching the filter, only the first Object is returned * * @param name * @param filter * @return */ public Component load(PageContext pc, String name, Struct filter) throws PageException; public Query toQuery(PageContext pc, Object obj, String name) throws PageException; /** * load and return a Object that match given id, if there is more than one * Object matching the id, only the first Object is returned * * @param name * @param id */ public Component load(PageContext pc, String name, String id) throws PageException; /** * load and return a array of Objects matching given filter * * @param name * @param filter * @return */ public Array loadAsArray(PageContext pc, String name, Struct filter) throws PageException; /** * load and return a array of Objects matching given filter * * @param name * @param filter * @param options * @return */ public Array loadAsArray(PageContext pc, String name, Struct filter, Struct options) throws PageException; /** * @param pc * @param name * @param filter * @param options * @param order * @return * @throws PageException */ public Array loadAsArray(PageContext pc, String name, Struct filter, Struct options, String order) throws PageException; /** * load and return a array of Objects matching given id * * @param name * @param id */ public Array loadAsArray(PageContext pc, String name, String id) throws PageException; /** * @param pc * @param name * @param id * @param order * @return * @throws PageException */ public Array loadAsArray(PageContext pc, String name, String id, String order) throws PageException; /** * load and return a array of Objects matching given sampleEntity * * @param pc * @param obj */ public Array loadByExampleAsArray(PageContext pc, Object obj) throws PageException; /** * load and return a Object that match given sampleEntity, if there is more * than one Object matching the id, only the first Object is returned * * @param pc * @param obj */ public Component loadByExample(PageContext pc, Object obj) throws PageException; public void evictCollection(PageContext pc, String entity, String collection) throws PageException; public void evictCollection(PageContext pc, String entity, String collection, String id) throws PageException; public void evictEntity(PageContext pc, String entity) throws PageException; public void evictEntity(PageContext pc, String entity, String id) throws PageException; public void evictQueries(PageContext pc) throws PageException; public void evictQueries(PageContext pc, String cacheName) throws PageException; public void evictQueries(PageContext pc, String cacheName, String datasource) throws PageException; public Object executeQuery(PageContext pc, String dataSourceName, String hql, Array params, boolean unique, Struct queryOptions) throws PageException; public Object executeQuery(PageContext pc, String dataSourceName, String hql, Struct params, boolean unique, Struct queryOptions) throws PageException; /** * close all elements in all sessions * * @param pc * @throws PageException */ public void closeAll(PageContext pc) throws PageException; /** * close all elements in the default sessions * * @param pc * @throws PageException */ public void close(PageContext pc) throws PageException; /** * close all elements in a specific sessions defined by datasource name * * @param pc * @param datasource * @throws PageException */ public void close(PageContext pc, String datasource) throws PageException; /** * is session valid or not * * @return is session valid */ public boolean isValid(DataSource ds); public boolean isValid(); /** * engine from session * * @return engine */ public ORMEngine getEngine(); public Object getRawSession(String dataSourceName) throws PageException; public Object getRawSessionFactory(String dataSourceName) throws PageException; public ORMTransaction getTransaction(String dataSourceName, boolean autoManage) throws PageException; public String[] getEntityNames(); public DataSource[] getDataSources(); }
import { App, Stack, StackProps } from 'aws-cdk-lib'; import { EventBus, Rule } from 'aws-cdk-lib/aws-events'; import { LambdaFunction, EventBus as BusTarget } from 'aws-cdk-lib/aws-events-targets'; import { Runtime } from 'aws-cdk-lib/aws-lambda'; import { NodejsFunction, SourceMapMode } from 'aws-cdk-lib/aws-lambda-nodejs'; import path from 'path'; export interface EventStoreStackProps extends StackProps { eventSourceBus: EventBus; } /** * Infrastructure for EventStore goes in this siloed stack */ export class EventStoreStack extends Stack { readonly eventStorer: NodejsFunction; constructor(scope: App, id: string, props: EventStoreStackProps) { super(scope, id, props); // Create Lambda Function this.eventStorer = new NodejsFunction(this, 'EventStorer', { functionName: 'SpandexUnchainedEventStorer', description: 'Event Handler Function for Storing to the Event Repo', runtime: Runtime.NODEJS_16_X, entry: path.join(__dirname, '..', '..', '..', '..', 'event-handlers', 'event-storage', 'src', 'app', 'app-aws.ts'), bundling: { minify: true, sourceMap: true, sourceMapMode: SourceMapMode.INLINE }, environment: { awsRegion: props.env?.region ?? 'us-west-2', eventStoreName: 'NoneCurrently' } }); // Trigger lambda from target bus via Rule new Rule(this, 'EventStoreTriggerRule', { ruleName: 'EventStoreTriggerRule', description: 'Rule allowing the event storer lambda to be triggered by the attached bus', eventBus: props.eventSourceBus, eventPattern: { source: [`SpandexUnchained`] }, targets: [new LambdaFunction(this.eventStorer)], enabled: true }); } }
################################################################### ################# Random Forest Classification setwd("F:\\DataMining_R\\3_LectureData") library(caret) lp=read.csv("LoanPay.csv") head(lp) summary(lp) lp[is.na(lp)] = 0 #replace NA with 0 nameList=c("loan_status","Principal","terms","age","education","Gender","past_due_days") df= lp[,colnames(lp) %in% nameList] head(df) ### 1) Data split set.seed(99) Train = createDataPartition(df$loan_status, p=0.75, list=FALSE) #split data in 75%-25% ratio training = df[ Train, ] #75% data for training testing = df[ -Train, ] #25% testing # define training control train_control <- trainControl(method="cv", number=10) #10 fold cv fit1= train(loan_status~., data=training, method="rf", trControl=train_control,importance=TRUE) #see the performance on the training data fit1 plot(fit1) ######## evaluate variable importance varImp(fit1) plot(varImp(fit1), top = 5) ########## predict on unseen data pred1 = predict(fit1, testing) confusionMatrix(pred1, testing$loan_status)
import random import numpy as np from matplotlib import pyplot as plt from nearest_neighbour import learnknn, predictknn from utils import gensmallm LABELS = [2, 3, 5, 6] CORRUPTED_FACTOR = 0.15 def run_knn_over_sample_size(k: int, sample_size_max: int, sample_sizes_steps: int, repeats: int, title: str): print(f"Running knn with k={k}, sample_size_max={sample_size_max} " f"sample_sizes_steps={sample_sizes_steps}, repeats={repeats}" f"...") train_sample_sizes = np.linspace(1, sample_size_max, num=sample_sizes_steps, dtype=int) avg_errors, min_errors, max_errors = [], [], [] for sample_size in train_sample_sizes: print(f"sample_size: {sample_size}") avg_error, min_error, max_error = calculate_errors_with_repeats(sample_size, k, repeats, is_corrupted=False) avg_errors.append(avg_error) min_errors.append(min_error) max_errors.append(max_error) error_bar = calculate_error_bar(avg_errors, min_errors, max_errors) show_results(x_axis=train_sample_sizes, y_axis=np.array(avg_errors), repeats=repeats, error_bar=error_bar, title=title, x_label='sample size') print("done!") def run_knn_over_k(max_k: int, sample_size, repeats: int, title: str, is_corrupted): print(f"Running knn with max_k={max_k}, " f"sample_size={sample_size}, repeats={repeats}" f"...") k_values = np.linspace(1, max_k, num=max_k, dtype=int) avg_errors, min_errors, max_errors = [], [], [] for k in k_values: print(f"k: {k}") avg_error, min_error, max_error = calculate_errors_with_repeats(sample_size, k, repeats, is_corrupted) avg_errors.append(avg_error) min_errors.append(min_error) max_errors.append(max_error) error_bar = calculate_error_bar(avg_errors, min_errors, max_errors) show_results(x_axis=k_values, y_axis=np.array(avg_errors), repeats=repeats, error_bar=error_bar, title=title, x_label='k') print("done!") def calculate_error_bar(avg_errors, min_errors, max_errors): avg_errors, min_errors, max_errors = np.array(avg_errors), np.array(min_errors), np.array(max_errors) avg_distance_min = avg_errors - min_errors avg_distance_max = max_errors - avg_errors return np.vstack((avg_distance_min, avg_distance_max)) def calculate_errors_with_repeats(train_sample_size: int, k: int, repeats: int, is_corrupted): repeats_errors = [calculate_error(k, train_sample_size, is_corrupted) for _ in range(repeats)] return np.mean(repeats_errors), min(repeats_errors), max(repeats_errors) def calculate_error(k: int, train_sample_size: int, is_corrupted) -> float: train_data = [data[f'train{label}'] for label in LABELS] test_data = [data[f'test{label}'] for label in LABELS] test_size = sum(map(lambda test: test.shape[0], test_data)) x_train, y_train = gensmallm(train_data, LABELS, train_sample_size) x_test, y_test = gensmallm(test_data, LABELS, test_size) if is_corrupted: corrupt(y_train) corrupt(y_test) classifier = learnknn(k, x_train, y_train) preds = predictknn(classifier, x_test) # fix shape from (n,) -> (n,1) y_test = np.expand_dims(y_test, axis=1) return float(np.mean(y_test != preds)) def corrupt(y): train_corrupted_indices = random.sample(range(len(y)), int(CORRUPTED_FACTOR * len(y))) for train_corrupted_index in train_corrupted_indices: label_to_change = y[train_corrupted_index] y[train_corrupted_index] = random.choice([label for label in LABELS if label != label_to_change]) def show_results(x_axis, y_axis, repeats: int, error_bar, title: str, x_label: str): fig, ax = plt.subplots() ax.set_xlabel(x_label) ax.set_ylabel(f'mean error {repeats} repeats') ax.set_title(f"{title}") plt.errorbar(x=x_axis, y=y_axis, yerr=error_bar, marker='o', ecolor='red', capsize=3) plt.show() if __name__ == '__main__': # before submitting, make sure that the function simple_test runs without errors data = np.load('mnist_all.npz') # question 2a run_knn_over_sample_size(title="Question 2A (k=1)", k=1, sample_size_max=100, sample_sizes_steps=10, repeats=10) # question 2e run_knn_over_k(title="Question 2e (sample=200)", max_k=11, sample_size=200, repeats=10, is_corrupted=False) # question 2f run_knn_over_k(title="Question 2f (sample=200)", max_k=11, sample_size=200, repeats=10, is_corrupted=True)
// // ViewController.swift // project5 // // Created by 1 on 2020/05/08. // Copyright © 2020 wook. All rights reserved. // import UIKit class ViewController: UITableViewController { var allWords = [String]() var usedWords = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //네비게이션 라이트 버튼 추가 navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer)) if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt"){ if let startWords = try? String(contentsOf: startWordsURL){ allWords = startWords.components(separatedBy: "\n") } }else{ if allWords.isEmpty{ allWords = ["silkworm"] } } startGame() } func startGame(){ title = allWords.randomElement() usedWords.removeAll(keepingCapacity: true) tableView.reloadData() } //tableView 생성 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return usedWords.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath) cell.textLabel?.text = usedWords[indexPath.row] return cell } @objc func promptForAnswer(){ let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert) ac.addTextField() let submitAction = UIAlertAction(title: "Submit", style: .default){ [weak self, weak ac] _ in guard let answer = ac?.textFields?[0].text else {return} self?.submit(answer) } ac.addAction(submitAction) present(ac, animated: true) } func submit(_ answer: String){ let lowerAnswer = answer.lowercased() let errorTitle: String let errorMessage: String if isPossible(word: lowerAnswer){ if isOriginal(word: lowerAnswer){ if isReal(word: lowerAnswer){ usedWords.insert(answer, at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) return }else{ errorTitle = "Wrod not recognized" errorMessage = "You can`t just make them up, you know!" } }else{ errorTitle = "Word already used" errorMessage = "Be more original!" } }else{ guard let title = title else{return} errorTitle = "Word not possible" errorMessage = "you can`t spell that word from \(title.lowercased())." } let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(ac, animated: true) } func isPossible(word: String) -> Bool{ guard var tempWord = title?.lowercased() else {return false} for letter in word{ if let position = tempWord.firstIndex(of: letter){ tempWord.remove(at: position) }else{ return false } } return true } func isOriginal(word: String) -> Bool{ return !usedWords.contains(word) } func isReal(word: String) -> Bool{ let checker = UITextChecker() let range = NSRange(location: 0, length: word.utf16.count) let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } }
import type { ComponentProps, FC, PropsWithChildren, ReactNode } from 'react'; import { KeepColors } from '../../Keep/KeepTheme'; export interface KeepCarouselTheme { base: string; indicators: { active: { off: { base: string; color: IndicatorsTypeColors; }; on: { base: string; type: { dot: string; ring: string; bar: string; square: string; squareRing: string; }; color: IndicatorsTypeColors; }; }; base: string; wrapper: string; type: { dot: string; ring: string; bar: string; square: string; squareRing: string; }; }; item: { base: string; wrapper: string; }; control: { base: string; icon: string; }; leftControl: string; rightControl: string; scrollContainer: { base: string; snap: string; }; } export type IndicatorsType = 'dot' | 'ring' | 'bar' | 'square' | 'squareRing'; export interface IndicatorsTypeColors extends Pick<KeepColors, 'white' | 'slate'> { [key: string]: string; } /** * Props for the Carousel component. * @interface CarouselProps * @extends {PropsWithChildren<ComponentProps<'div'>>} */ export interface CarouselProps extends PropsWithChildren<ComponentProps<'div'>> { /** * Determines whether to show indicators for the carousel slides. * @type {boolean} * @default false */ indicators?: boolean; /** * Determines whether to show controls for navigating the carousel. * @type {boolean} * @default false */ showControls?: boolean; /** * The custom component to be used as the left control for the carousel. * @type {ReactNode} * @default "<DefaultLeftControl />" */ leftControl?: ReactNode; /** * The custom component to be used as the right control for the carousel. * @type {ReactNode} * @default "<DefaultRightControl />" */ rightControl?: ReactNode; /** * The children elements to be rendered as carousel slides. * @type {ReactNode} * @default '' */ children?: ReactNode; /** * Determines whether the carousel should slide automatically. * @type {boolean} * @default true */ slide?: boolean; /** * The interval (in milliseconds) between each slide transition. * @type {number} * @default 3000 (3 seconds) */ slideInterval?: number; /** * The type of indicators to be displayed for the carousel slides. * @type {IndicatorsType} * @default 'dot' */ indicatorsType?: IndicatorsType; /** * The color scheme for the indicators. * @type {keyof IndicatorsTypeColors} * @default 'white' */ indicatorsTypeColors?: keyof IndicatorsTypeColors; /** * Additional CSS class name(s) for the carousel component. * @type {string} * @default '' */ className?: string; } export declare const Carousel: FC<CarouselProps>;
//import { homeConstant } from "../../constants/homeConstants"; import { HEADER_QUERY_CONSTANT } from "../../constants/homeConstants"; import { FOOTER_QUERY_CONSTANT } from "../../constants/homeConstants"; import React, { useContext, useEffect } from "react"; import { Container, Row, Col } from "react-bootstrap"; import { contentQuery } from "@/utils/ContentQuery"; import contentfulFetch from "@/utils/graphqlFetch"; import Layout from "@/components/layout/Layout"; import { useRouter } from "next/router"; import { Auth } from "aws-amplify"; import CryptoJS from "crypto-js"; import logo from "@/assets/images/idp-logo.svg"; import Image from "next/image"; import { useForm } from "react-hook-form"; import SEO from "@/components/seo/Seo"; import { localeData } from "@/configs/localeData"; import { utils } from "@/utils/index"; import { AppContext } from "@/context/AppContext"; import LoadingIndicator from "@/components/loadingIndicator/LoadingIndicator"; const registration = ({ serverData }) => { const { register, formState: { errors }, handleSubmit, } = useForm(); const { headerData, footerData, location } = serverData; const { setLocationContext, setPass } = useContext(AppContext); useEffect(() => { setLocationContext(location); }, []); const router = useRouter(); const { setSessionStorage } = utils; const onSubmit = async (data) => { const enEmail = CryptoJS.SHA256(data.email); console.log(`SHA256 Email Encryption: ${enEmail}`); try { await Auth.signUp({ username: data.email, password: data.password, attributes: { email: data.email, name: enEmail.toString(), }, }); console.log( "Sign up successful! Please check your email to verify your account." ); setSessionStorage("email", data.email); setPass(data.password); await router.push(`/${location}/verify`); } catch (error) { alert(error.message); } }; return ( <> <SEO title="Study Abroad, Overseas Education Consultant, Get Free Counselling! | IDP India" description="Study Overseas Consultants in India - Study abroad with IDP education, we help students to study overseas in Australia, USA, Canada, UK & New Zealand." /> <Layout headerData={headerData} footerData={footerData}> <Container> <Row> <Col lg={6} sm={12} className="mt-5"> <div className="signin-contant"> <div className="signin-image"> <Image alt="logo" src={logo} width={240} height={57} /> </div> <h3> IDP has been helping international students for over 50 years </h3> <h4> Our full suite of student placement services and support is available to you </h4> <ul> <li> Supporting you in every step of your study abroad journey </li> <li>Approachable international education experts</li> <li>Get instant offer with IDP FastLane</li> <li>Proud co-owners of IELTS</li> </ul> </div> </Col> <Col lg={6} sm={12} className="my-5"> <div className="signin-form"> <h4>Sign up using your email</h4> <p className="text-center"> Already have an IDP profile? <span className="signInSwitch" onClick={() => router.push(`/${location}/login`)} > sign in. </span> </p> <form onSubmit={handleSubmit(onSubmit)}> <Row> <Col lg={6}> <div className="input-div"> <input {...register("firstName", { required: true })} type="text" placeholder="First Name" /> {errors.firstName?.type === "required" && ( <p className="error">First name is required</p> )} </div> </Col> <Col lg={6}> <div className="input-div"> <input {...register("LastName", { required: true })} type="text" placeholder="Last Name" /> {errors.LastName?.type === "required" && ( <p className="error">Last name is required</p> )} </div> </Col> <Col lg={12}> <div className="input-div"> <input {...register("mobile", { required: true })} type="text" placeholder="Mobile Number" /> {errors.mobile?.type === "required" && ( <p className="error">Mobile Number is required</p> )} </div> </Col> <Col lg={12}> <div className="input-div"> <input {...register("email", { required: true })} type="email" placeholder="Email Address" /> {errors.email?.type === "required" && ( <p className="error">Email Address is required</p> )} </div> </Col> <Col lg={12}> <div className="input-div"> <input {...register("password", { required: true })} type="password" placeholder="Enter Password" /> {errors.password?.type === "required" && ( <p className="error">Enter Password is required</p> )} </div> </Col> <Col lg={12}> <div className="form-check"> <input className="form-check-input" type="checkbox" /> <label className="form-check-label"> I agree to IDPs terms and conditions and privacy policy </label> </div> </Col> <Col lg={12}> <div className="input-div btn-account"> <button>Create An Account</button> </div> </Col> </Row> </form> </div> </Col> </Row> </Container> </Layout> </> ); } export default LoadingIndicator(registration); export async function getServerSideProps(context) { let location, locale; location = context.query.location || context.req.url.split("/")[1]; locale = context.query.lang || localeData[`${location}`]?.defaultLocale; console.log("localtion at register", location); console.log("locale at register", locale); // const { headerQueryConstant, footerQueryConstant } = homeConstant; const headerQuery = contentQuery(HEADER_QUERY_CONSTANT, {}, locale); const footerQuery = contentQuery(FOOTER_QUERY_CONSTANT, {}, locale); const coursePayload = [headerQuery, footerQuery]; let [header, footer] = await Promise.allSettled( coursePayload.map((payload) => contentfulFetch(payload) .then((res) => res) .catch((err) => { console.log("Error", err); }) ) ); let [headerData, footerData] = [ header.value.navbarCollection.items, footer.value.footerCollection.items, ]; return { props: { serverData: { headerData, footerData, location, }, }, }; }
package org.project.bookmanager.datasource; import org.project.bookmanager.entity.Publisher; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Component; import java.util.List; @Component public class PublisherDao { private static final String SELECT_ALL = """ SELECT * FROM `publisher` """; private static final String SELECT_BY_ID = """ SELECT * FROM `publisher` WHERE `publisher_id` = :publisher_id """; private static final String INSERT = """ INSERT INTO `publisher` ( `publisher_id`, `name` ) VALUES ( :publisher_id, :name ) """; private static final String UPDATE = """ UPDATE `publisher` SET `name` = :name WHERE `publisher_id` = :publisher_id """; private static final RowMapper<Publisher> ROW_MAPPER = (rs, rowNum) -> new Publisher( rs.getLong("publisher_id"), rs.getString("name") ); private final NamedParameterJdbcTemplate template; public PublisherDao(NamedParameterJdbcTemplate template) { this.template = template; } public List<Publisher> selectAll() { return template.query(SELECT_ALL, ROW_MAPPER); } public Publisher selectById(long publisherId) { SqlParameterSource params = new MapSqlParameterSource() .addValue("publisher_id", publisherId); return template.queryForObject(SELECT_BY_ID, params, ROW_MAPPER); } public void insert(Publisher publisher) { SqlParameterSource params = new MapSqlParameterSource() .addValue("publisher_id", publisher.publisherId()) .addValue("name", publisher.name()); template.update(INSERT, params); } public void update(Publisher publisher) { SqlParameterSource params = new MapSqlParameterSource() .addValue("publisher_id", publisher.publisherId()) .addValue("name", publisher.name()); template.update(UPDATE, params); } }
import { join } from 'path'; import htmlToText from 'html-to-text'; import nodemailer from 'nodemailer'; import nodemailerSendgrid from 'nodemailer-sendgrid'; import juice from 'juice'; import pug from 'pug'; import envConfig from '../../../config/v1/env/env.config'; import config from '../../../config'; import { HTMLOptions, SendEmailOptions, } from '../../../types/v1/email/email.type'; envConfig(); const configVariables = config(); const transporter = nodemailer.createTransport( { // development mode host: 'smtp.mailtrap.io', port: 2525, auth: { user: '1dd6e3a4e47cfe', pass: '7fa4facf793a1c', }, } // nodemailerSendgrid({ // apiKey: configVariables.sendGrid.SENDGRID_API_KEY, // }) ); // NOTE Tasks: create the html to the email and create a shedule for sending email to the people who haven't confirmed their emails const generateHTML = (file: string, options: HTMLOptions) => { const html = pug.renderFile( join( __dirname, '..', '..', '..', 'views', 'emails', 'confirmAccount', file ), options ); return juice(html); }; const sendEmail = async (options: SendEmailOptions) => { let { to, subject, file, htmlOptions: { confirmationURL, info, year, userName }, } = options; if (!info) { info = "we're excited to have you get started, you are almost ready to start enjoying, CiFullMa. Simply click the big yellow button below to verify your email address."; } const html = generateHTML(file, { confirmationURL, info, year, userName }); const msg = { to, from: configVariables.sendGrid.SENDGRID_EMAIL_FROM, subject, text: htmlToText.htmlToText(html), html, }; await transporter.sendMail(msg); }; export default { sendEmail, generateHTML };
@extends('layouts.admin') @section('titile', 'Create Produk') @push('prepend-style') <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script> @endpush @section('content') <div class="page-heading"> <div class="page-title"> <div class="row"> <div class="col-12 col-md-6 order-md-1 order-last"> <h3>Tambah Produk / Layanan</h3> </div> </div> </div> <section class="section"> <div class="card"> <div class="card-body"> <form action="{{ route('product.store') }}" method="POST", enctype="multipart/form-data"> @csrf <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="name">Nama Produk / Layanan</label> <input type="text" class="form-control" id="name" name="name" placeholder="nama product / layanan" value="{{ old('name') }}" required> </div> <div class="form-group"> <label for="excerpt">Kutipan</label> <textarea type="text" class="form-control" id="excerpt" name="excerpt" placeholder="kutipan" rows="5" required>{{ old('excerpt') }}</textarea> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="slug">Slug</label> <input type="text" class="form-control" id="slug" name="slug" placeholder="slug" value="{{ old('slug') }}" required> </div> <div class="form-group"> <label for="logo">Logo</label> <input type="text" class="form-control" id="logo" name="logo" placeholder="logo" value="{{ old('logo') }}" required> </div> </div> </div> <div class="row mt-3"> <div class="col-md-10"> <div class="form-group"> <label for="my-editor" class="form-label">Deskripsi</label> <textarea name="description" class="my-editor form-control" id="my-editor" cols="30" rows="10" required>{{ old('description') }}</textarea> </div> </div> </div> <div class="row mt-3"> <div class="form-group"> <button class="btn btn-primary" type="submit">Simpan</button> </div> </div> </form> </div> </div> </section> </div> @endsection @push('prepend-script') <script src="https://cdn.ckeditor.com/4.12.1/standard/ckeditor.js"></script> <script> var options = { filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images', filebrowserImageUploadUrl: '/laravel-filemanager/upload?type=Images&_token=', filebrowserBrowseUrl: '/laravel-filemanager?type=Files', filebrowserUploadUrl: '/laravel-filemanager/upload?type=Files&_token=' }; </script> <script> CKEDITOR.replace('my-editor', options) </script> <script type="text/javascript"> $('.date').datepicker({ format: 'yyyy-mm-dd' }); </script> @endpush
/*************************************************************************** * ProbeMode.h -- * * * ***********************IMPORTANT NMAP LICENSE TERMS************************ * * * The Nmap Security Scanner is (C) 1996-2012 Insecure.Com LLC. Nmap is * * also a registered trademark of Insecure.Com LLC. This program is free * * software; you may redistribute and/or modify it under the terms of the * * GNU General Public License as published by the Free Software * * Foundation; Version 2 with the clarifications and exceptions described * * below. This guarantees your right to use, modify, and redistribute * * this software under certain conditions. If you wish to embed Nmap * * technology into proprietary software, we sell alternative licenses * * (contact sales@insecure.com). Dozens of software vendors already * * license Nmap technology such as host discovery, port scanning, OS * * detection, version detection, and the Nmap Scripting Engine. * * * * Note that the GPL places important restrictions on "derived works", yet * * it does not provide a detailed definition of that term. To avoid * * misunderstandings, we interpret that term as broadly as copyright law * * allows. For example, we consider an application to constitute a * * "derivative work" for the purpose of this license if it does any of the * * following: * * o Integrates source code from Nmap * * o Reads or includes Nmap copyrighted data files, such as * * nmap-os-db or nmap-service-probes. * * o Executes Nmap and parses the results (as opposed to typical shell or * * execution-menu apps, which simply display raw Nmap output and so are * * not derivative works.) * * o Integrates/includes/aggregates Nmap into a proprietary executable * * installer, such as those produced by InstallShield. * * o Links to a library or executes a program that does any of the above * * * * The term "Nmap" should be taken to also include any portions or derived * * works of Nmap, as well as other software we distribute under this * * license such as Zenmap, Ncat, and Nping. This list is not exclusive, * * but is meant to clarify our interpretation of derived works with some * * common examples. Our interpretation applies only to Nmap--we don't * * speak for other people's GPL works. * * * * If you have any questions about the GPL licensing restrictions on using * * Nmap in non-GPL works, we would be happy to help. As mentioned above, * * we also offer alternative license to integrate Nmap into proprietary * * applications and appliances. These contracts have been sold to dozens * * of software vendors, and generally include a perpetual license as well * * as providing for priority support and updates. They also fund the * * continued development of Nmap. Please email sales@insecure.com for * * further information. * * * * As a special exception to the GPL terms, Insecure.Com LLC grants * * permission to link the code of this program with any version of the * * OpenSSL library which is distributed under a license identical to that * * listed in the included docs/licenses/OpenSSL.txt file, and distribute * * linked combinations including the two. You must obey the GNU GPL in all * * respects for all of the code used other than OpenSSL. If you modify * * this file, you may extend this exception to your version of the file, * * but you are not obligated to do so. * * * * If you received these files with a written license agreement or * * contract stating terms other than the terms above, then that * * alternative license agreement takes precedence over these comments. * * * * Source is provided to this software because we believe users have a * * right to know exactly what a program is going to do before they run it. * * This also allows you to audit the software for security holes (none * * have been found so far). * * * * Source code also allows you to port Nmap to new platforms, fix bugs, * * and add new features. You are highly encouraged to send your changes * * to the dev@nmap.org mailing list for possible incorporation into the * * main distribution. By sending these changes to Fyodor or one of the * * Insecure.Org development mailing lists, or checking them into the Nmap * * source code repository, it is understood (unless you specify otherwise) * * that you are offering the Nmap Project (Insecure.Com LLC) the * * unlimited, non-exclusive right to reuse, modify, and relicense the * * code. Nmap will always be available Open Source, but this is important * * because the inability to relicense code has caused devastating problems * * for other Free Software projects (such as KDE and NASM). We also * * occasionally relicense the code to third parties as discussed above. * * If you wish to specify special license conditions of your * * contributions, just say so when you send them. * * * * 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 Nmap * * license file for more details (it's in a COPYING file included with * * Nmap, and also available from https://svn.nmap.org/nmap/COPYING * * * ***************************************************************************/ #ifndef __PROBEMODE_H__ #define __PROBEMODE_H__ 1 #include "nping.h" #include "nsock.h" #include <vector> #include "NpingTarget.h" #include "utils_net.h" #include "utils.h" using namespace std; #define PKT_TYPE_TCP_CONNECT 1 #define PKT_TYPE_UDP_NORMAL 2 #define PKT_TYPE_TCP_RAW 3 #define PKT_TYPE_UDP_RAW 4 #define PKT_TYPE_ICMP_RAW 5 #define PKT_TYPE_ARP_RAW 6 /* The sendpkt structure is the data normalProbeMode() function passes to * the nsock event handler. It contains the neccessary information so a * handler can send one probe. */ typedef struct sendpkt{ int type; u8 *pkt; int pktLen; int rawfd; u32 seq; NpingTarget *target; u16 dstport; }sendpkt_t; class ProbeMode { private: nsock_pool nsp; /**< Internal Nsock pool */ bool nsock_init; /**< True if nsock pool has been initialized */ public: ProbeMode(); ~ProbeMode(); void reset(); int init_nsock(); int start(); int cleanup(); nsock_pool getNsockPool(); static int createIPv4(IPv4Header *i, PacketElement *next_element, const char *next_proto, NpingTarget *target); static int createIPv6(IPv6Header *i, PacketElement *next_element, const char *next_proto, NpingTarget *target); static int doIPv6ThroughSocket(int rawfd); static int fillPacket(NpingTarget *target, u16 port, u8 *buff, int bufflen, int *filledlen, int rawfd); static int fillPacketTCP(NpingTarget *target, u16 port, u8 *buff, int bufflen, int *filledlen, int rawfd); static int fillPacketUDP(NpingTarget *target, u16 port, u8 *buff, int bufflen, int *filledlen, int rawfd); static int fillPacketICMP(NpingTarget *target, u8 *buff, int bufflen, int *filledlen, int rawfd); static int fillPacketARP(NpingTarget *target, u8 *buff, int bufflen, int *filledlen, int rawfd); static char *getBPFFilterString(); static void probe_nping_event_handler(nsock_pool nsp, nsock_event nse, void *arg); static void probe_delayed_output_handler(nsock_pool nsp, nsock_event nse, void *mydata); static void probe_tcpconnect_event_handler(nsock_pool nsp, nsock_event nse, void *arg); static void probe_udpunpriv_event_handler(nsock_pool nsp, nsock_event nse, void *arg); }; /* End of class ProbeMode */ /* Handler wrappers */ void nping_event_handler(nsock_pool nsp, nsock_event nse, void *arg); void tcpconnect_event_handler(nsock_pool nsp, nsock_event nse, void *arg); void udpunpriv_event_handler(nsock_pool nsp, nsock_event nse, void *arg); void delayed_output_handler(nsock_pool nsp, nsock_event nse, void *arg); #endif /* __PROBEMODE_H__ */
import { useCallback, useMemo } from "react"; import { useMantineReactTable } from "mantine-react-table"; import { ActivateUserBtn, TableContent } from "../../.." import { useTecnicoStore, useUiTecnico } from "../../../../hooks"; export const TecnicosTable = () => { const { isLoading, tecnicos, setActivateTecnico } = useTecnicoStore(); const { modalActionTecnico } = useUiTecnico(); const columns = useMemo( () => [ { accessorKey: "nmbre_usrio", //access nested data with dot notation header: "Nombres", filterVariant: "autocomplete", }, { accessorKey: "role", //normal accessorKey header: "Role", }, { accessorKey: "lgin", header: "Usuario", }, { accessorKey: "total_soportes", header: "Total Soportes Año Actual", }, { accessorKey: "actvo", header: "Activo", Cell: ({ cell }) => ( <ActivateUserBtn cell={cell} handleActive={handleActive} /> ), }, ], [tecnicos] ); const handleActive = useCallback( (selected) => { setActivateTecnico(selected); modalActionTecnico(1, true); }, [tecnicos] ); const table = useMantineReactTable({ columns, data: tecnicos, //must be memoized or stable (useState, useMemo, defined outside of this component, etc.) enableFacetedValues: true, state: { showProgressBars: isLoading }, }); return ( <TableContent table={table} /> ) }
import MotoGPAdmin from 0xa49cc0ee46c54bfb import MotoGPPack from 0xa49cc0ee46c54bfb import NonFungibleToken from 0x1d7e57aa55817448 import FlowToken from 0x1654653399040a61 import FungibleToken from 0xf233dcee88fe0abe import MotoGPTransfer from 0xa49cc0ee46c54bfb // The SalesContract's role is to enable on-chain sales of MotoGP packs. // Users buy directly from the buyPack method and get the pack deposited into their collection, if all conditions are met. // The contract admin manages sales by adding SKUs to the contract. A SKU is equivalent to a drop. // // Each SKU has a list of serial numbers (equivalent to print numbers), and when the user buys a pack, a serial is selected from the SKUs serial list, // and removed from the list. To make the serial selection hard to predict we employ a logic discussed further below. // // The buyPack method takes a signature as one of its arguments. This signature is generated when the user requests to buy a pack via the MotoGP web site. // The user calls the MotoGP backend signing service. Using a private key, the signing service creates a signature which includes the user's address, a nonce unique to the address which is read from the SalesContract, and the pack type. // The signing service then sends the signature back to user the user, who subsequently send a transaction including the signature to the SalesContract to buy a pack. // Inside the buyPack method, the signature is verified using a public key which is a string field on the contract, and that only the admin can set. // The key is set on the contract, rather than the account, to guarantee it is only used within this contract. // // After the signature has been verified, the first byte is read from the signature and an index is created from it, which is used to // select a serial from the serial list. That serial is then removed, and a pack is minted and deposited into the users collection. In this way, // for every pack purchase, the serial list shrinks by one. // // The user's payment for packs comes from a Flow vault submitted in the buyPack transaction. The payment is deposited into a Flow vault at an address set on the SKU. // pub contract SalesContract { pub fun getVersion(): String { return "1.0.0" } pub let adminStoragePath: StoragePath access(contract) let skuMap: {String : SKU} // account-specific nonce to prevent a user from submitting the same transaction twice access(contract) let nonceMap: {Address : UInt64} // the public key used to verify a buyPack signature access(contract) var verificationKey: String // map to track if a serial has already been added for a pack type. A duplicate would throw an // exception on mint in buyPack from the Pack contract. access(contract) let serialMap: { UInt64 : { UInt64 : Bool}} // Used like so : { packType : { serial: true/false } // An SKU is equivalent to a drop or "sale event" with start and end time, and max supply pub struct SKU { // Unix timestamp in seconds (not milliseconds) when the SKU starts access(contract) var startTime: UInt64; // Unix timestamp in seconds (not milliseconds) when the SKU ends access(contract) var endTime: UInt64; // max total number of NFTs which can be minted during this SKU access(contract) var totalSupply: UInt64; // list of serials, from which one will be chosen and removed for each NFT mint. access(contract) var serialList: [UInt64] // map to check that a buyer doesn't buy more than allowed max from a SKU access(contract) let buyerCountMap: { Address: UInt64 } // price of the NFT in FLOW tokens access(contract) var price: UFix64 // max number of NFTs the buyer can buy access(contract) var maxPerBuyer: UInt64 // address to deposit the payment to. Can be unique for each SKU. access(contract) var payoutAddress: Address // packType + serial determines a unique Pack access(contract) var packType: UInt64 // SKU constructor init(startTime: UInt64, endTime: UInt64, payoutAddress: Address, packType: UInt64){ self.startTime = startTime self.endTime = endTime self.serialList = [] self.buyerCountMap = {} self.totalSupply = UInt64(0) self.maxPerBuyer = UInt64(1) self.price = UFix64(0.0) self.payoutAddress = payoutAddress self.packType = packType } // Setters for modifications after a SKU has been created. // Access via contract helper methods, never directly on the SKU access(contract) fun setStartTime(startTime: UInt64) { self.startTime = startTime } access(contract) fun setEndTime(endTime: UInt64) { self.endTime = endTime } access(contract) fun setPrice(price: UFix64){ self.price = price } access(contract) fun setMaxPerBuyer(maxPerBuyer: UInt64) { self.maxPerBuyer = maxPerBuyer } access(contract) fun setPayoutAddress(payoutAddress: Address) { self.payoutAddress = payoutAddress } // The increaseSupply() method adds lists of serial numbers to a SKU. // Since a SKU's serial number list length can be several thousands, // increaseSupply() may need to be called multiple times to build up a SKU's supply. // Given that the combination type + serial needs to be unique for a mint (else Pack contract will panic), // the increaseSupply() method will panic if a serial is submitted for a type that already has it registered. access(contract) fun increaseSupply(supplyList: [UInt64]){ let oldTotalSupply = UInt64(self.serialList.length) self.serialList = self.serialList.concat(supplyList) self.totalSupply = UInt64(supplyList.length) + oldTotalSupply if !SalesContract.serialMap.containsKey(self.packType) { SalesContract.serialMap[self.packType] = {}; } let statusMap = SalesContract.serialMap[self.packType]! var index: UInt64 = UInt64(0); while index < UInt64(supplyList.length) { let serial = supplyList[index] if statusMap.containsKey(serial) && statusMap[serial]! == true { let msg = "Serial ".concat(serial.toString()).concat(" for packtype").concat(self.packType.toString()).concat(" is already added") panic(msg) } SalesContract.serialMap[self.packType]!.insert(key: serial, true) index = index + UInt64(1) } } } // isCurrencySKU returns true if a SKU's startTime is in the past and it's endTime in the future, based on getCurrentBlock's timestamp. // This method should not be relied on for precise time requirements on front end, as getCurrentBlock().timestamp in a read method may be quite inaccurate. pub fun isCurrentSKU(name: String): Bool { let sku = self.skuMap[name]! let now = UInt64(getCurrentBlock().timestamp) if sku.startTime <= now && sku.endTime > now { return true } return false } pub fun getStartTimeForSKU(name: String): UInt64 { return self.skuMap[name]!.startTime } pub fun getEndTimeForSKU(name: String): UInt64 { return self.skuMap[name]!.endTime } pub fun getTotalSupplyForSKU(name: String): UInt64 { return self.skuMap[name]!.totalSupply } // Remaining supply equals the length of the serialList, since even mint event removes a serial from the list. pub fun getRemainingSupplyForSKU(name: String): UInt64 { return UInt64(self.skuMap[name]!.serialList.length) } // Helper method to check how many NFT an account has purchased for a particular SKU pub fun getBuyCountForAddress(skuName: String, recipient: Address): UInt64 { return self.skuMap[skuName]!.buyerCountMap[recipient] ?? UInt64(0) } pub fun getPriceForSKU(name: String): UFix64 { return self.skuMap[name]!.price } pub fun getMaxPerBuyerForSKU(name: String): UInt64 { return self.skuMap[name]!.maxPerBuyer } // Returns a list of SKUs where start time is in the past and the end time is in the future. // Don't reply on it for precise time requirements. pub fun getActiveSKUs(): [String] { let activeSKUs:[String] = [] let keys = self.skuMap.keys var index = UInt64(0) while index < UInt64(keys.length) { let key = keys[index]! let sku = self.skuMap[key]! let now = UInt64(getCurrentBlock().timestamp) if sku.startTime <= now { // SKU has started if sku.endTime > now {// SKU hasn't ended activeSKUs.append(key) } } index = index + UInt64(1) } return activeSKUs; } pub fun getAllSKUs(): [String] { return self.skuMap.keys } pub fun removeSKU(adminRef: &Admin, skuName: String) { self.skuMap.remove(key: skuName) } // The Admin resource is used as an access lock on certain setter methods pub resource Admin {} // Sets the public key used to verify signature submitted in the buyPack request pub fun setVerificationKey(adminRef: &Admin, verificationKey: String) { pre { adminRef != nil : "adminRef is nil." } self.verificationKey = verificationKey; } // helper used by buyPack method to check if a signature is valid access(contract) fun isValidSignature(signature: String, message: String): Bool { let pk = PublicKey( publicKey: self.verificationKey.decodeHex(), signatureAlgorithm: SignatureAlgorithm.ECDSA_P256 ) let isValid = pk.verify( signature: signature.decodeHex(), signedData: message.utf8, domainSeparationTag: "FLOW-V0.0-user", hashAlgorithm: HashAlgorithm.SHA3_256 ) return isValid } // Returns a nonce per account pub fun getNonce(address: Address): UInt64 { return self.nonceMap[address] ?? 0 as UInt64 } pub fun isActiveSKU(name: String): Bool { let sku = self.skuMap[name]! let now = UInt64(getCurrentBlock().timestamp) if sku.startTime <= now { // SKU has started if sku.endTime > now {// SKU hasn't ended return true } } return false } // Helper method to convert address to String (used for verificaton of signature in buyPack) // public to allow testing pub fun convertAddressToString(address: Address): String { let EXPECTED_ADDRESS_LENGTH = 18 var addrStr = address.toString() //Cadence shortens addresses starting with 0, so 0x0123 becomes 0x123 if addrStr.length == EXPECTED_ADDRESS_LENGTH { return addrStr } let prefix = addrStr.slice(from: 0, upTo: 2) var suffix = addrStr.slice(from: 2, upTo: addrStr.length) let steps = EXPECTED_ADDRESS_LENGTH - addrStr.length var index = 0 while index < steps { suffix = "0".concat(suffix) index = index + 1 } addrStr = prefix.concat(suffix) if addrStr.length != EXPECTED_ADDRESS_LENGTH { panic("Padding address String is wrong length") } return addrStr } pub fun buyPack(signature: String, nonce: UInt32, packType: UInt64, skuName: String, recipient: Address, paymentVaultRef: &FungibleToken.Vault, recipientCollectionRef: &MotoGPPack.Collection{MotoGPPack.IPackCollectionPublic}) { pre { paymentVaultRef.balance >= self.skuMap[skuName]!.price : "paymentVaultRef's balance is lower than price" self.isActiveSKU(name: skuName) == true : "SKU is not active" self.getRemainingSupplyForSKU(name: skuName) > UInt64(0) : "No remaining supply for SKU" self.skuMap[skuName]!.price >= UFix64(0.0) : "Price is zero. Admin needs to set the price" self.skuMap[skuName]!.packType == packType : "Supplied packType doesn't match SKU packType" } post { self.nonceMap[recipient]! == before(self.nonceMap[recipient] ?? UInt64(0)) + UInt64(1) : "Nonce hasn't increased by one" self.skuMap[skuName]!.buyerCountMap[recipient]! == before(self.skuMap[skuName]!.buyerCountMap[recipient] ?? UInt64(0)) + UInt64(1) : "buyerCountMap hasn't increased by one" self.skuMap[skuName]!.buyerCountMap[recipient]! <= self.skuMap[skuName]!.maxPerBuyer : "Max pack purchase count per buyer exceeded" paymentVaultRef.balance == before(paymentVaultRef.balance) - self.skuMap[skuName]!.price : "Decrease in buyer vault balance doesn't match the price" } let sku = self.skuMap[skuName]! let recipientStr = self.convertAddressToString(address: recipient) let message = skuName.concat(recipientStr).concat(nonce.toString()).concat(packType.toString()); let isValid = self.isValidSignature(signature: signature, message: message) if isValid == false { panic("Signature isn't valid"); } // Withdraw payment from the vault ref let payment <- paymentVaultRef.withdraw(amount: sku.price) // Will panic if not enough $ let vault <- payment as! @FlowToken.Vault // Will panic if can't be cast // Get recipient vault and deposit payment let payoutRecipient = getAccount(sku.payoutAddress) let payoutReceiver = payoutRecipient.getCapability(/public/flowTokenReceiver) .borrow<&FlowToken.Vault{FungibleToken.Receiver}>() ?? panic("Could not borrow a reference to the payout receiver") payoutReceiver.deposit(from: <-vault) // Check nonce for account isn't reused, and increment it if self.nonceMap.containsKey(recipient) { let oldNonce: UInt64 = self.nonceMap[recipient]! let baseMessage = "Nonce ".concat(nonce.toString()).concat(" for ").concat(recipient.toString()) if oldNonce >= UInt64(nonce) { panic(baseMessage.concat(" already used")); } if (oldNonce + 1 as UInt64) < UInt64(nonce) { panic(baseMessage.concat(" is not next nonce")); } self.nonceMap[recipient] = oldNonce + UInt64(1) } else { self.nonceMap[recipient] = UInt64(1) } // Use first byte of message as index to select from supply. var index = UInt64(signature.decodeHex()[0]!) // Ensure the index falls within the serial list index = index % UInt64(sku.serialList.length) // **Remove** the selected packNumber from the packNumber list. // By removing the item, we ensure that even if same index is selected again in next tx, it will refer to another item. let packNumber = sku.serialList.remove(at: index); // Mint a pack let nft <- MotoGPPack.createPack(packNumber: packNumber, packType: packType); // Update recipient's buy-count if sku.buyerCountMap.containsKey(recipient) { let oldCount = sku.buyerCountMap[recipient]! sku.buyerCountMap[recipient] = UInt64(oldCount) + UInt64(1) self.skuMap[skuName] = sku } else { sku.buyerCountMap[recipient] = UInt64(1) self.skuMap[skuName] = sku } // Deposit the purchased pack into a temporary collection, to be able to topup the buyer's Flow/storage using the MotoGPTransfer contract let tempCollection <- MotoGPPack.createEmptyCollection() tempCollection.deposit(token: <- nft); // Transfer the pack using the MotoGPTransfer contract, to do Flow/storage topup for recipient MotoGPTransfer.transferPacks(fromCollection: <- tempCollection, toCollection: recipientCollectionRef, toAddress: recipient); } // Emergency-helper method to reset a serial in the map pub fun setSerialStatusInPackTypeMap(adminRef: &Admin, packType: UInt64, serial: UInt64, value: Bool) { pre { adminRef != nil : "adminRef is nil" } if SalesContract.serialMap.containsKey(packType) { SalesContract.serialMap[packType]!.insert(key: serial, value) } } // Allow Admin to add a new SKU pub fun addSKU(adminRef: &Admin, startTime: UInt64, endTime: UInt64, name: String, payoutAddress: Address, packType: UInt64) { pre { adminRef != nil : "adminRef is nil" } let sku = SKU(startTime: startTime, endTime: endTime, payoutAddress: payoutAddress, packType: packType); self.skuMap.insert(key: name, sku) } // Add lists of serials to a SKU pub fun increaseSupplyForSKU(adminRef: &Admin, name: String, supplyList: [UInt64]) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.increaseSupply(supplyList: supplyList) self.skuMap[name] = sku } pub fun setMaxPerBuyerForSKU(adminRef: &Admin, name: String, maxPerBuyer: UInt64) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.setMaxPerBuyer(maxPerBuyer: maxPerBuyer) self.skuMap[name] = sku } pub fun setPriceForSKU(adminRef: &Admin, name: String, price: UFix64) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.setPrice(price: price) self.skuMap[name] = sku } pub fun setEndTimeForSKU(adminRef: &Admin, name: String, endTime: UInt64) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.setEndTime(endTime: endTime) self.skuMap[name] = sku } pub fun setStartTimeForSKU(adminRef: &Admin, name: String, startTime: UInt64) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.setStartTime(startTime: startTime) self.skuMap[name] = sku } pub fun setPayoutAddressForSKU(adminRef: &Admin, name: String, payoutAddress: Address) { pre { adminRef != nil : "adminRef is nil" } let sku = self.skuMap[name]! sku.setPayoutAddress(payoutAddress: payoutAddress) self.skuMap[name] = sku } pub fun getSKU(name: String): SKU { return self.skuMap[name]! } pub fun getVerificationKey(): String { return self.verificationKey } init(){ self.adminStoragePath = /storage/salesContractAdmin self.verificationKey = "" // Crete Admin resource self.account.save(<- create Admin(), to: self.adminStoragePath) self.skuMap = {} self.nonceMap = {} self.serialMap = {} } }
import { conditionalFields, inputField, object, radioButton, selectField, step, upload, } from '../../generator/functions' import { createCamelCaseOptionsV2, createCondition } from '../../generator/helpers' const danovnikBase = [ object( 'ulicaCislo', { required: true }, { objectDisplay: 'columns', objectColumnRatio: '3/1', }, [ inputField('ulica', { title: 'Ulica', required: true }, { size: 'large' }), inputField('cislo', { title: 'Čislo', required: true }, { size: 'large' }), ], ), object( 'obecPsc', { required: true }, { objectDisplay: 'columns', objectColumnRatio: '3/1', }, [ inputField('obec', { title: 'Obec', required: true }, { size: 'large' }), inputField('psc', { title: 'PSČ', required: true, format: 'zip' }, { size: 'large' }), ], ), // TODO Select ciselnik inputField('stat', { title: 'Štát', required: true }, { size: 'large' }), inputField( 'email', { title: 'E-mail', type: 'email' }, { size: 'large', helptext: 'E-mailová adresa nám pomôže komunikovať s vami rýchlejšie.' }, ), inputField( 'telefon', { title: 'Telefónne číslo (v tvare +421...)', type: 'tel' }, { helptext: 'Telefónne číslo nám pomôže komunikovať s vami rýchlejšie.', size: 'default' }, ), ] const fyzickaOsoba = (splnomocnenie: boolean) => [ ...(splnomocnenie ? [] : [ inputField( 'rodneCislo', { title: 'Rodné číslo', required: true }, { size: 'large', helptext: 'Rodné číslo zadávajte s lomítkom. V prípade, že nemáte rodné číslo, uveďte dátum narodenia.', }, ), ]), inputField( 'priezvisko', { title: 'Priezvisko', required: true }, { size: 'large', }, ), object( 'menoTitul', { required: true }, { objectDisplay: 'columns', objectColumnRatio: '3/1', }, [ inputField('meno', { title: 'Meno', required: true }, { size: 'large' }), inputField('titul', { title: 'Titul', required: true }, { size: 'large' }), ], ), ...danovnikBase, ] const fyzickaOsobaPodnikatel = [ inputField( 'ico', { title: 'IČO', required: true }, { size: 'large', }, ), inputField( 'obchodneMenoAleboNazov', { title: 'Obchodné meno alebo názov', required: true }, { size: 'large', }, ), ...danovnikBase, ] const pravnickaOsoba = (splnomocnenie: boolean) => [ ...(splnomocnenie ? [] : [ inputField( 'ico', { title: 'IČO', required: true }, { size: 'large', }, ), selectField( 'pravnaForma', { title: 'Právna forma', required: true, options: [ { value: 'male', title: 'Male', tooltip: 'Male' }, { value: 'female', title: 'Female', tooltip: 'Female' }, ], }, { dropdownDivider: true }, ), ]), inputField( 'obchodneMenoAleboNazov', { title: 'Obchodné meno alebo názov', required: true }, { size: 'large', }, ), ...danovnikBase, ] export default step('udajeODanovnikovi', { title: 'Údaje o daňovníkovi' }, [ radioButton( 'voSvojomMene', { type: 'boolean', title: 'Podávate priznanie k dani z nehnuteľností vo svojom mene?', required: true, options: [ { value: true, title: 'Áno', isDefault: true }, { value: false, title: 'Nie', tooltip: 'TODO' }, ], }, { variant: 'boxed', orientations: 'row' }, ), conditionalFields(createCondition([[['voSvojomMene'], { const: false }]]), [ object('opravnenaOsoba', { required: true }, { objectDisplay: 'boxed', spaceTop: 'default' }, [ upload( 'splnomocnenie', { title: 'Nahrajte splnomocnenie', required: true, multiple: true }, { type: 'dragAndDrop', helptext: 'Keďže ste v predošlom kroku zvolili, že priznanie nepodávate vo svojom mene, je nutné nahratie skenu plnej moci. Následne, po odoslaní formulára je potrebné doručiť originál plnej moci v listinnej podobe na oddelenie miestnych daní, poplatkov a licencií. Splnomocnenie sa neprikladá v prípade zákonného zástupcu neplnoletej osoby. ', }, ), radioButton( 'splnomocnenecTyp', { type: 'string', title: 'Podávate ako oprávnená osoba (splnomocnenec)', required: true, options: createCamelCaseOptionsV2([ { title: 'Fyzická osoba', tooltip: 'Občan SR alebo cudzinec' }, { title: 'Právnicka osoba', tooltip: 'Organizácia osôb alebo majetku vytvorená na nejaký účel (napr. podnikanie)', }, ]), }, { variant: 'boxed' }, ), conditionalFields(createCondition([[['splnomocnenecTyp'], { const: 'fyzickaOsoba' }]]), [ object('fyzickaOsoba', { required: true }, {}, fyzickaOsoba(true)), ]), conditionalFields(createCondition([[['splnomocnenecTyp'], { const: 'pravnickaOsoba' }]]), [ object('pravnickaOsoba', { required: true }, {}, pravnickaOsoba(true)), ]), ]), ]), radioButton( 'priznanieAko', { type: 'string', title: 'Podávate priznanie ako', required: true, options: createCamelCaseOptionsV2([ { title: 'Fyzická osoba', tooltip: 'Občan SR alebo cudzinec' }, { title: 'Fyzická osoba podnikateľ', tooltip: 'SZČO alebo “živnostník”' }, { title: 'Právnicka osoba', tooltip: 'Organizácia osôb alebo majetku vytvorená na nejaký účel (napr. podnikanie)', }, ]), }, { variant: 'boxed' }, ), conditionalFields(createCondition([[['priznanieAko'], { const: 'fyzickaOsoba' }]]), [ object('fyzickaOsoba', { required: true }, {}, fyzickaOsoba(false)), ]), conditionalFields(createCondition([[['priznanieAko'], { const: 'fyzickaOsobaPodnikatel' }]]), [ object('fyzickaOsobaPodnikatel', { required: true }, {}, fyzickaOsobaPodnikatel), ]), conditionalFields(createCondition([[['priznanieAko'], { const: 'pravnickaOsoba' }]]), [ object('pravnickaOsoba', { required: true }, {}, pravnickaOsoba(false)), ]), ])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button>냥냥펀치</button> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> const URL = 'https://api.thecatapi.com/v1/images/search' const btn = document.querySelector('button') const getCats = function () { axios({ method: 'get', url: URL }) .then((response) => { // console.log(response) // console.log(response.data) // console.log(response.data[0].url) // 응답으로부터 필요한 img url만 구하기 const imgUrl = response.data[0].url return imgUrl }) .then((imgUrl) => { const imgTag = document.createElement('img') imgTag.setAttribute('src', imgUrl) document.body.appendChild(imgTag) }) .catch((error) => { console.log(error) }) } btn.addEventListener('click', getCats) </script> </body> </html>
import 'package:flutter/material.dart'; import 'package:mynotes/constants/routes.dart'; import 'package:mynotes/services/cloud/cloud_note.dart'; import 'package:mynotes/services/cloud/firebase_cloud_storage.dart'; import '../../utils/show_loading_dialog.dart'; class NoteListView extends StatefulWidget { final List<CloudNote> allNotes; const NoteListView({required this.allNotes, Key? key}) : super(key: key); @override State<NoteListView> createState() => _NoteListViewState(); } class _NoteListViewState extends State<NoteListView> { late final FirebaseCloudStorage _notesService; @override void initState() { _notesService = FirebaseCloudStorage(); super.initState(); } @override Widget build(BuildContext context) { return ListView.builder( itemCount: widget.allNotes.length, itemBuilder: (context, index) { return ListTile( title: Text(widget.allNotes[index].text), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( icon: const Icon(Icons.delete), onPressed: () async { deleteNote(widget.allNotes[index].documentId); }, ), ], ), onTap: () { Navigator.of(context).pushNamedAndRemoveUntil( addNoteRoute, (route) => true, arguments: widget.allNotes[index], ); }, ); }, ); } Future<void> deleteNote(String id) async { showLoadingDialog(context); await _notesService.deleteNote(documentId: id); Navigator.of(context).pop(false); } }
package com.kejin.view.gesture; import android.content.Context; import android.graphics.RectF; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; public class GestureFrameLayout extends FrameLayout { private final ArrayList<View> controlViews = new ArrayList<>(); private ViewGestureAttacher gestureAttacher; private IGestureListener gestureListener; private boolean gestureEnable = true; public GestureFrameLayout(@NonNull Context context) { super(context); } public GestureFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public GestureFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public GestureFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void setGestureListener(IGestureListener listener) { gestureListener = listener; if (gestureAttacher != null) { gestureAttacher.setGestureListener(listener); } } public void setGestureEnable(boolean enable) { gestureEnable = enable; } @Nullable public ViewGestureAttacher getGestureAttacher() { return gestureAttacher; } public void addControlView(@NonNull View view) { if (!controlViews.contains(view)) { controlViews.add(view); } } public void removeControlView(@NonNull View view) { controlViews.remove(view); } @Nullable public ViewGestureAttacher startControl(int width, int height) { for (View view : controlViews) { LayoutParams params = new LayoutParams(width, height, Gravity.LEFT|Gravity.TOP); if (indexOfChild(view) < 0) { addView(view, params); } else { view.setLayoutParams(params); } } if (gestureAttacher != null && gestureAttacher.isSameImageSize(width, height)) { return gestureAttacher; } if (gestureAttacher != null) { gestureAttacher.release(); gestureAttacher = null; } if (width < 1 || height < 1) { return null; } ViewGestureAttacher attacher = new ViewGestureAttacher(this, width, height); attacher.setScaleType(ImageView.ScaleType.FIT_CENTER); attacher.setMatrixListener(matrix -> { RectF displayRect = attacher.getDisplayRect(); updateControlViewRect(width, height, displayRect); }); attacher.setGestureListener(gestureListener); attacher.update(); gestureAttacher = attacher; return gestureAttacher; } private void updateControlViewRect(float vw, float vh, @NonNull RectF rect) { if (!gestureEnable) { return; } float scaleW = rect.width() / vw; float scaleH = rect.height() / vh; float dx = rect.centerX() - vw / 2; float dy = rect.centerY() - vh / 2; for (View view : controlViews) { view.setTranslationX(dx); view.setTranslationY(dy); view.setScaleX(scaleW); view.setScaleY(scaleH); } } }
import { useEffect } from 'react'; import {Routes,Route} from 'react-router-dom' import {useDispatch} from 'react-redux'; import Home from './routes/home/home-component'; import Navigation from './routes/navigation/navigation.component'; import Authentication from './routes/authentication/authentication.component'; import Shop from './routes/shop/shop-component'; import CheckOut from './routes/checkout/checkout-component'; import { setCurrentUser } from './store/user/user.action'; import { createUserDocumentFromAuth, onAuthStateChangedListener } from './utilities/firebase/firebase.utils'; const App = ()=> { const dispatch = useDispatch(); useEffect(() => { const unsubscribe = onAuthStateChangedListener((user) => { if (user) { createUserDocumentFromAuth(user); } dispatch(setCurrentUser(user)); }); return unsubscribe; }, []); return ( <Routes> <Route path="/" element={<Navigation/>}> <Route index element={<Home/>}/> <Route path="shop/*" element={<Shop/>}/> <Route path="auth" element={<Authentication/>}/> <Route path="/checkout" element={<CheckOut/>}/> </Route> </Routes> ) } export default App;
package tests.modelTest; import src.model.SoldBooks; import org.junit.jupiter.api.Test; import src.model.TheDate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class SoldBooksTest { @Test public void testSoldBooks() { String ISBN = "1234567890"; String titleOfBook = "Test Book"; int quantity = 5; double price = 50.0; SoldBooks soldBooks = new SoldBooks(ISBN, titleOfBook, quantity, price); // Verify the getters return the expected values assertEquals(ISBN, soldBooks.getISBN()); assertEquals(titleOfBook, soldBooks.getTitleOfBook()); assertEquals(quantity, soldBooks.getQuantity()); assertEquals(price, soldBooks.getPrice()); // Verify the date object is not null assertNotNull(soldBooks.getDate()); // Verify toString method // String expectedString = "SoldBooks [ISBN=" + ISBN + ", titleOfBook=" + titleOfBook + // ", quantity=" + quantity + ", sellprice=" + price + ", sellDate=" + // soldBooks.getDate() + "]"; // assertEquals(expectedString, soldBooks.toString()); } @Test public void testSetters() { SoldBooks soldBooks = new SoldBooks("123", "Book1", 10, 100.0); soldBooks.setBarcode("456"); soldBooks.setName("Book2"); soldBooks.setQuantity(20); soldBooks.setPrice(200.0); assertEquals("456", soldBooks.getISBN()); assertEquals("Book2", soldBooks.getTitleOfBook()); assertEquals(20, soldBooks.getQuantity()); assertEquals(200.0, soldBooks.getPrice()); } @Test public void testSetDate() { SoldBooks soldBooks = new SoldBooks("1234567890", "Test Book", 5, 50.0); TheDate date = new TheDate(1, 1, 2023); soldBooks.setDate(date); assertEquals(date, soldBooks.getDate()); } @Test public void testToString() { String ISBN = "1234567890"; String titleOfBook = "Test Book"; int quantity = 5; double price = 50.0; TheDate date = new TheDate(1, 1, 2023); SoldBooks soldBooks = new SoldBooks(ISBN, titleOfBook, quantity, price); soldBooks.setDate(date); String expectedToString = "SoldBooks [ISBN=" + ISBN + ", titleOfBook=" + titleOfBook + ", quantity=" + quantity + ", sellprice=" + price + ", sellDate=" + date + "]"; assertEquals(expectedToString, soldBooks.toString()); } }
import AppKit /* Inspired by https://rderik.com/blog/managing-uti-and-url-schemes-via-launch-services-api-from-swift/ https://github.com/Lord-Kamina/SwiftDefaultApps https://www.droidwin.com/cannot-change-default-browser-for-webloc-files-in-ventura-fix/ */ @main public struct Main { public static func main() { /* UTI to open webloc files. You can use the `mdls` command to find an UTI for a file $ mdls -name kMDItemContentType -name kMDItemContentTypeTree -name kMDItemKind ~/Desktop/amazon.webloc kMDItemContentType = "com.apple.web-internet-location" kMDItemContentTypeTree = ( "com.apple.web-internet-location", "com.apple.internet-location", "public.stored-url", "public.data", "public.item" ) kMDItemKind = "Web internet location" */ let uti = "com.apple.web-internet-location" /* Bundle ID of the handler app. You can use the `default` command to find an app's bundle ID $ defaults read /Applications/Firefox.app/Contents/Info.plist CFBundleIdentifier Firefox : org.mozilla.firefox Safari : com.apple.Safari Chrome : com.google.Chrome Brave : com.brave.Browser */ let handler = "org.mozilla.firefox" guard let result = LSCopyDefaultRoleHandlerForContentType(uti as CFString, .all) else { print("handler not found for UTI: \(uti)") return } let currentHandler = result.takeRetainedValue() as String print("handler for \(uti) is \(currentHandler)") if (currentHandler != handler) { let result = LSSetDefaultRoleHandlerForContentType(uti as CFString, .viewer, handler as CFString) guard result != 0 else { print("Couldn't set handler with bundle id: \(handler) for UTI: \(uti)") return } print("Successfully set handler with bundle id: \(handler) for UTI: \(uti)") } } }
<!--<app-login (userConnectedEmitter)="userConnected($event)" (userDeconnectedEmitter)="userDeconnected($event)" > </app-login>--> <!-- tout cela est affiché ssi l'utilisateur est connecté --> <div *ngIf="monService.isConnected"> <!-- affiche l'ensemble des playlists disponibles (début) --> Les playlists : <ul> <li *ngFor="let playlist of listDePlaylist"> <!-- à chaque playlist est associé un formulaire tel que si on clique dessus, alors on affiche le contenu de la playlist --> <form (ngSubmit)="showPlaylistContent(playlist)"> <button>{{ playlist.name }}</button> </form> <!--on associe un second bouton qui correspond à la suppression de la playlist elle-même --> <form (ngSubmit)="deletePlaylist(playlist.id)"> <button>supprimer (non fonctionnel)</button> </form> </li> </ul> <!-- affiche l'ensemble des playlists disponibles (FIN) --> <!-- bouton qui permet d'appeler le formulaire qui permet de créer une nouvelle playlist --> <form (ngSubmit)="formNewPlaylistOn()"> <button>créer une nouvelle playlist</button> </form> <!-- si l'utilisateur a activé le formulaire de nouvelle playlist, alors c'est ici qu'il peut lui donner un nom--> <div *ngIf="newPlaylistOn"> <form (ngSubmit)="addNewNamePlaylist()" #varForm2="ngForm"> Nom de la playlist : <input type="text" required maxlength="20" minlength="3" pattern="[a-zA-Z0-9]+" name="playlist" [(ngModel)]="nomPlaylist" #nomPlaylistControler="ngModel" /> <button type="submit" [disabled]="varForm2.invalid">Créer</button> </form> </div> </div> <!--on affiche le contenu de la playlist choisie par le user si ce dernier a demandé l'affichage d'une playlist--> <div *ngIf="displayPlaylistOn"> Les musiques de la playlist <!--"{{ playlistChosen.name }}"--> sont : <ul> <li *ngFor="let track of playlistContent"> {{ track.name }} </li> </ul> </div>
import PropTypes from "prop-types"; import {Link} from "react-router-dom"; function UserItem ({user}) { return( <div className="card shadow-md compact card-side bg-neutral"> <div className="flex-row items-center space-x-4 card-body"> <div> <div className="avatar"> <div className="rounded-full shadow-2xl w-14 h-14"> <img src={user.avatar_url} alt="UserIMG"/> </div> </div> </div> <div> <h2 className="card-title"> {user.login} </h2> <Link className="text-base-content text-opacity-40" to={`/user/${user.login}`}> Check Profile </Link> </div> </div> </div> ) } UserItem.propTypes = { user: PropTypes.object.isRequired } export default UserItem
import React, {useState} from 'react' import styled from 'styled-components' import {FilmType, SimilarFilmType} from '../../../api/filmAPI' import {ImdbCard} from '../../ImdbCard/ImdbCard' import {useDispatch, useSelector} from "react-redux"; import {AppRootStateType} from "../../../app/store"; import {setFilm, setFilmId} from "../FilmPage/film-reducer"; import {Redirect} from "react-router-dom"; import {PATH} from "../../../app/main/routes/Pages"; import {Link} from "react-scroll/modules"; import {backgroundCover} from "../../../common/stylesVariables"; type SimilarFilmPropsType = { similarFilm: SimilarFilmType } const SimilarFilmWrapper = styled.div` min-width: 260px; min-height: 360px; margin-right: 30px; margin-top: 10px; ` const SimilarFilmInner = styled.div<{ image: string }>` width: 100%; min-height: 100%; position: relative; background-color: black; background-image: url(${props => props.image}); ${backgroundCover}; border-radius: 20px; ` const Description = styled.div` width: 100%; height: 100%; position: absolute; top: 0; left: 0; background-color: rgba(20, 19, 19, 0.85); z-index: 999; display: flex; flex-direction: column; justify-content: space-between; padding: 20% 30px; color: #FFFFFF; border-radius: 20px; ` const DescriptionTitle = styled.h3` font-size: 24px; font-weight: 800; line-height: 29px; text-align: left; margin-bottom: 8px; overflow-wrap: anywhere; cursor: pointer; ` const GenresSpan = styled.span` font-size: 14px; font-weight: 500; line-height: 17px; margin-bottom: 20px; &.top { margin-bottom: 8px; } ` const Paragraph = styled.p` font-size: 14px; font-weight: 400; line-height: 18px; margin-bottom: 23px; overflow-wrap: anywhere; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; ` export const SimilarFilm: React.FC<SimilarFilmPropsType> = ({similarFilm}) => { const dispatch = useDispatch() const [toggleDescription, setToggleDescription] = useState<boolean>(false) const film = useSelector<AppRootStateType, FilmType>(state => state.similarFilms[similarFilm.id]) const [redirect, setRedirect] = useState<boolean>(false) const showDescription = () => { setToggleDescription(true) } const hideDescription = () => { setToggleDescription(false) } const chooseFilm = () => { dispatch(setFilmId({id: film.id})) dispatch(setFilm({film})) setRedirect(true) } if (redirect) { return <Redirect to={PATH.FILM}/> } return ( <SimilarFilmWrapper> <SimilarFilmInner onMouseEnter={showDescription} onMouseLeave={hideDescription} image={similarFilm.image}> {toggleDescription && <Description> <Link to={'film'} spy={true} smooth={true} duration={2000}> <DescriptionTitle onClick={chooseFilm}>{film.title}</DescriptionTitle> </Link> <GenresSpan className={'top'}>{film.type}</GenresSpan> <GenresSpan>{film.genres}</GenresSpan> <Paragraph>{film.plot}</Paragraph> <ImdbCard rating={film.imDbRating}/> </Description>} </SimilarFilmInner> </SimilarFilmWrapper> ) }
package pages; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class BlogPage extends BasePage{ WebDriver driver; Logger logger = Logger.getLogger(BlogPage.class); public BlogPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } //Locate elements @FindBy(xpath = "//div[@class='et_pb_text_inner']//h1") WebElement blogTitleHeader; @FindBy(xpath = "//div[@class='et_pb_text_inner']//p") WebElement blogContent; @FindBy(xpath = "//input[@id='et_pb_signup_email']") WebElement emailTxt; @FindBy(xpath = "//a[@class='et_pb_newsletter_button et_pb_button']") WebElement subscribeBtn; //Methods public String getTitleHeader() { logger.info("Getting the title header."); return getText(blogTitleHeader); } public String getBlogContent() { logger.info("Getting the blog content."); return getText(blogContent); } public void enterEmail(String email) { logger.info("Entering email."); enterText(emailTxt, email); } public void clickSubscribeBtn() { logger.info("Clicking subscribe button."); click(subscribeBtn); } public String getEmailTxtValue() { logger.info("Getting email text value."); return emailTxt.getAttribute("value"); } public WebElement emailInputTextField() { return driver.findElement(By.xpath("//input[@id='et_pb_signup_email']")); } }
<?php namespace Database\Factories; use App\Models\Exam; use Illuminate\Database\Eloquent\Factories\Factory; class ExamFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Exam::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name'=>$this->faker->word(), 'semester'=>$this->faker->numberBetween($min = 1, $max = 8) ]; } }
package com.goodworkalan.paste.connector; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.goodworkalan.dovetail.Path; import com.goodworkalan.ilk.association.IlkAssociation; import com.goodworkalan.ilk.inject.InjectorBuilder; import com.goodworkalan.paste.cassette.BindKey; import com.goodworkalan.paste.cassette.Cassette; import com.goodworkalan.paste.cassette.Connection; import com.goodworkalan.paste.cassette.ConnectionSet; import com.goodworkalan.winnow.RuleMapBuilder; /** * Used by {@link Router} instances to define path to controller mappings and * controller to renderer mappings. * * @author Alan Gutierrez */ public class Connector { /** The connection data structure to populate. */ private final Cassette cassette; /** * Create a default connector. * * @param cassette * The connection data structure to populate. */ public Connector(Cassette cassette) { cassette.reactionsByType = new IlkAssociation<Class<?>>(true); cassette.reactionsByAnnotation = new HashMap<Class<? extends Annotation>, List<Class<?>>>(); cassette.routes = new HashMap<Class<?>, Path>(); cassette.connections = new ArrayList<ConnectionSet<List<Connection>>>(); cassette.renderers = new RuleMapBuilder<BindKey, List<InjectorBuilder>>(); cassette.interceptors = new IlkAssociation<Class<?>>(true); this.cassette = cassette; } /** * Syntactical sugar for importing existing routers, applies the router to * this connector and returns this connector. * * @param router * The router to apply to this connector. * @return This connector to continue specifying routes. */ public Connector module(Router router) { router.connect(this); return this; } /** * Specify a controller for an event that is not directly associated with an * HTTP request. This is used by timers to implement delayed jobs or * background tasks. Reaction controllers are built using dependency * injection, so that application scoped resources are available during the * reaction. * * @return A react statement to specify an event reactor. */ public ReactStatement react() { return new ReactStatement(this, cassette.reactionsByType, cassette.reactionsByAnnotation); } /** * Specify intercepting controllers that bind to controller types and are * invoked prior to the invocation bound controller to intercept the request * processing based on controller type. * * @return An intercept statement to specify controller interceptors. */ public InterceptStatement intercept() { return new InterceptStatement(this, cassette.interceptors); } /** * Create a new group of connections that will map paths to controller * classes. When processing a request, each group of connections is * evaluated in the order in which they were defined. Each group of * connections has the opportunity to match the path and apply a controller * to the request. If the controller intercepts the request, either by * explicitly calling intercept, throwing an exception, or writing output, * connection group evaluation processing, no further connection groups are * evaluated, and view evaluation begins. * * @return A domain-specific language element used to define a group */ public ConnectStatement connect() { ConnectionSet<List<Connection>> group = new ConnectionSet<List<Connection>>(new ArrayList<Connection>()); cassette.connections.add(group); return new ConnectStatement(this, cassette.routes, group); } /** * Return an element in the domain-specific language that will map * controllers and exceptions to renderers, based on their type and on * additional request properties. * * @return A domain-specific language used to define the renderer. */ public RenderStatement render() { return new RenderStatement(this, cassette.renderers); } /** End a connection statement. */ public void end() { } }
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:stacked/stacked.dart'; import 'package:sugar_mill_app/views/cane_screens/add_cane_view/add_cane_model.dart'; import '../../../widgets/cdrop_down_widget.dart'; import '../../../widgets/ctext_button.dart'; import '../../../widgets/full_screen_loader.dart'; class AddCaneScreen extends StatelessWidget { final String caneId; const AddCaneScreen({super.key, required this.caneId}); @override Widget build(BuildContext context) { return ViewModelBuilder<CaneViewModel>.reactive( viewModelBuilder: () => CaneViewModel(), onViewModelReady: (model) => model.initialise(context, caneId), builder: (context, model, child) => Scaffold( appBar: AppBar( title: model.isEdit == true ? Text(model.canedata.name.toString()) : const Text('Cane Registration'), ), body: fullScreenLoader( child: SingleChildScrollView( child: Form( key: model.formKey, child: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( //for plant child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.season, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Season *', ), hint: const Text('Select Season'), items: model.seasonlist.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedSeason(value), validator: model.validateSeason, ), ), ), const SizedBox( width: 20.0, ), Expanded( //for plant child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.plantName, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Plant *', ), hint: const Text('Select Plant'), items: model.plantlist.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedPlant(value), validator: model.validatePlant, ), ), ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Autocomplete<String>( key: Key(model.canedata.village ?? "03"), initialValue: TextEditingValue( text: model.canedata.village ?? "", ), optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text.isEmpty) { return const Iterable<String>.empty(); } return model.villageList .map((route) => route.name ?? "") .toList() .where((route) => route .toLowerCase() .contains(textEditingValue.text .toLowerCase())); }, onSelected: (String routeName) { // Find the corresponding route object final routeData = model.villageList .firstWhere( (route) => route.name == routeName); model.setSelectedVillage(context, routeData.name); // Pass the route }, fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextFormField( // key: Key(model.farmerData.village ?? ""), // initialValue: model.farmerData.village, controller: textEditingController, focusNode: focusNode, decoration: const InputDecoration( labelText: 'Village *', ), onChanged: (String value) {}, validator: model.validateVillage, ); }, optionsViewBuilder: (BuildContext contpext, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Align( alignment: Alignment.topLeft, child: Material( elevation: 4.0, child: Container( constraints: const BoxConstraints( maxHeight: 200), child: ListView.builder( shrinkWrap: true, itemCount: options.length, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); return GestureDetector( onTap: () { onSelected(option); }, child: ListTile( title: Text(option), ), ); }, ), ), ), ); }, optionsMaxHeight: 200, ), ), const SizedBox( width: 15, ), Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.plantationStatus, decoration: const InputDecoration( labelText: 'Plantation Status *', ), hint: const Text('Select Is Plantation Status'), items: model.plantationStatus.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedplantation(value), validator: model.validatePlantationStatus, ), )), ], ), Row(children: [ Expanded( child: Autocomplete<String>( key: Key(model.canedata.vendorCode ?? "05"), initialValue: TextEditingValue( text: model.canedata.vendorCode ?? "", ), optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text.isEmpty) { return const Iterable<String>.empty(); } return model.farmerList .where((grower) => (grower.supplierName ?? "") .toLowerCase() .contains(textEditingValue.text .toLowerCase())) .map((grower) => grower.existingSupplierCode ?? "") .toList(); }, onSelected: model.setSelectedgrowercode, fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextFormField( controller: textEditingController, focusNode: focusNode, decoration: const InputDecoration( labelText: 'Grower Code * ', ), onChanged: (String value) {}, validator: model.validateGrowerCode, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Align( alignment: Alignment.topLeft, child: Material( elevation: 4.0, child: Container( constraints: const BoxConstraints( maxHeight: 200), child: ListView.builder( shrinkWrap: true, itemCount: options.length, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); final routeData = model.farmerList .firstWhere((route) => route .existingSupplierCode == option); return GestureDetector( onTap: () { onSelected(option); }, child: ListTile( title: Text(option), subtitle: Text( routeData.supplierName!), ), ); }, ), ), ), ); }, optionsMaxHeight: 200, ), ), const SizedBox( width: 20.0, ), Expanded( //for plant child: CdropDown( dropdownButton: DropdownButtonFormField<String>( value: model.canedata.developmentPlot, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Development Plot', ), hint: const Text('Select Plot'), items: model.yesno.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedDevelopmentplot(value), ), ), ), ]), TextFormField( readOnly: true, key: Key(model.canedata.growerName ?? "07"), initialValue: model.canedata.growerName, decoration: const InputDecoration(labelText: 'Grower Name'), validator: (value) => value!.isEmpty ? 'Please enter a Grower Name' : null, onChanged: model.setSelectedgrowername, ), //mobile number Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: TextFormField( keyboardType: const TextInputType.numberWithOptions( signed: false), controller: model.formNumberController, decoration: const InputDecoration( labelText: 'Form Number *'), validator: (value) => value!.isEmpty ? 'Please enter a form Number' : null, onChanged: model.setFormNumber, ), ), // const SizedBox( // width: 20.0, // ), // Expanded( // //for plant // child: CdropDown( // dropdownButton: // DropdownButtonFormField<String>( // isExpanded: true, // value: model.canedata.isKisanCard, // // Replace null with the selected value if needed // decoration: const InputDecoration( // labelText: 'Is Kisan Card *', // ), // hint: const Text('Select Is Kisan Card'), // items: model.yesno.map((val) { // return DropdownMenuItem<String>( // value: val, // child: AutoSizeText(val), // ); // }).toList(), // onChanged: (value) => // model.setSelectedkisan(value), // validator: model.validateKisanCard, // ), // ), // ), ], ), model.isEdit ? const Chip( label: Text( "Route Details", style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, ), ), ) : Container(), Row( children: [ Expanded( child: Autocomplete<String>( key: Key(model.canedata.route ?? "02"), initialValue: TextEditingValue( text: model.selectedCaneRoute ?? "", ), optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text.isEmpty) { return const Iterable<String>.empty(); } return model.routeList .map((route) => route.route!) .toList() .where((route) => route .toLowerCase() .contains(textEditingValue.text .toLowerCase())); }, onSelected: (String routeName) { // Find the corresponding route object final routeData = model.routeList .firstWhere((route) => route.route == routeName); model.setselectedRoute( routeData); // Pass the route }, fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextFormField( controller: textEditingController, focusNode: focusNode, decoration: const InputDecoration( labelText: 'Route *', ), onChanged: (String value) {}, validator: model.validateRoute, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Align( alignment: Alignment.topLeft, child: Material( elevation: 4.0, child: Container( constraints: const BoxConstraints( maxHeight: 200, ), child: ListView.builder( shrinkWrap: true, itemCount: options.length, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); // Find the corresponding route object final routeData = model.routeList .firstWhere((route) => route.route == option); return GestureDetector( onTap: () { onSelected(routeData.route ?? ""); // Send the name as the selected route }, child: ListTile( title: Text(option), // Display the corresponding name value subtitle: Text(routeData.name!), ), ); }, ), ), ), ); }, optionsMaxHeight: 200, ), ), const SizedBox( width: 15, ), Expanded( child: TextFormField( key: Key(model.canedata.routeKm.toString()), readOnly: true, decoration: const InputDecoration(labelText: 'KM'), initialValue: model.canedata.routeKm?.toStringAsFixed(0) ?? "", onChanged: (newValue) { // Handle the newValue here, you can update the routeKm value // using the setroutekm function with the new value. double? parsedValue = double.tryParse(newValue) ?? 0; model.setroutekm(parsedValue); }, )), ], ), Row( children: [ Visibility( visible: model.canedata.route != null, child: Expanded( child: TextFormField( key: Key(model.canedata.circleOffice ?? "circleoffice"), readOnly: true, initialValue: model.canedata.circleOffice, decoration: const InputDecoration( labelText: 'Circle Office', ), onChanged: model.setSelectedcircleoffice, ), ), ), const SizedBox( width: 15, ), Visibility( visible: model.isEdit, child: Expanded( child: TextFormField( readOnly: true, initialValue: model.canedata.taluka, decoration: const InputDecoration( labelText: 'Taluka'), ), ), ), // Expanded( // child: TextFormField( // readOnly: true, // initialValue: model.canedata.state, // decoration: const InputDecoration( // labelText: 'State', // ), // ), // ), ], ), const SizedBox( height: 15, ), Visibility( visible: model.isEdit, child: const Divider( thickness: 1, ), ), Row( children: [ Expanded( child: TextFormField( keyboardType: const TextInputType.numberWithOptions( signed: false), controller: model.surveyNumberController, decoration: const InputDecoration( labelText: 'Survey Number *', ), validator: (value) => value!.isEmpty ? 'Please enter a Survey Number' : null, onChanged: model.setsurveyNumber, ), ), const SizedBox( width: 15, ), Expanded( child: Autocomplete<String>( key: Key(model.canedata.cropVariety ?? "cropvariety"), initialValue: TextEditingValue( text: model.canedata.cropVariety ?? "", ), optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text.isEmpty) { return const Iterable<String>.empty(); } return model.canevarietyList .map((route) => route) .toList() .where((route) => route .toLowerCase() .contains(textEditingValue.text .toLowerCase())); }, onSelected: (value) => model.setselectedcropVariety(value), fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextFormField( // key: Key(model.farmerData.village ?? ""), // initialValue: model.farmerData.village, keyboardType: const TextInputType.numberWithOptions( signed: false), controller: textEditingController, focusNode: focusNode, decoration: const InputDecoration( labelText: 'Crop Variety *', ), onChanged: (String value) {}, validator: model.validateVillage, ); }, optionsViewBuilder: (BuildContext contpext, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Align( alignment: Alignment.topLeft, child: Material( elevation: 4.0, child: Container( constraints: const BoxConstraints( maxHeight: 200), child: ListView.builder( shrinkWrap: true, itemCount: options.length, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); return GestureDetector( onTap: () { onSelected(option); }, child: ListTile( title: AutoSizeText(option), ), ); }, ), ), ), ); }, optionsMaxHeight: 200, ), ), // Expanded( // child: CdropDown( // dropdownButton: // DropdownButtonFormField<String>( // isExpanded: true, // value: model.canedata.cropVariety, // // Replace null with the selected value if needed // decoration: const InputDecoration( // labelText: 'Crop Variety', // ), // hint: const Text('Select Crop Variety'), // items: model.canevarietyList.map((val) { // return DropdownMenuItem<String>( // value: val, // child: Text(val), // ); // }).toList(), // onChanged: (value) => // model.setselectedcropVariety(value), // validator: model.validateCropVariety, // menuMaxHeight: 200, // ), // ), // ), ], ), Row( children: [ Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.plantationSystem, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Plantation System *', ), hint: const Text('Select Plantation System'), items: model.plantationsystemList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model .setselectedPlantationSystem(value), validator: model.validatePlantationSystem, ), ), ), const SizedBox( width: 15, ), Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.irrigationSource, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Irrigation Source *', ), hint: const Text( 'Select Is Irrigation Source'), items: model.irrigationSourceList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model .setSelectedirrigationsource(value), validator: model.validateirrigationSource, ), ), ), ], ), Row( children: [ Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.soilType, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Soil Type *', ), hint: const Text('Select Is Soil Type'), items: model.soilTypeList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedSoilType(value), validator: model.validateSoilType, ), ), ), const SizedBox( width: 15, ), Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.roadSide, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Road Side *', ), hint: const Text('Select Is Road Side'), items: model.yesnoroadside.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedRoadSIde(value), validator: model.validateRoadSide, ), ), ), ], ), Row( children: [ Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.cropType, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Crop Type *', ), hint: const Text('Select Crop Type'), items: model.croptypeList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setSelectedcroptype(value), validator: model.validateCropType, ), ), ), const SizedBox( width: 15, ), Expanded( child: TextFormField( keyboardType: TextInputType.number, controller: model.areainAcrsController, decoration: const InputDecoration( labelText: 'Area In Acrs *', ), validator: model.validateAreaInAcrs, onChanged: model.setSelectedareainacrs, ), ), ], ), Row( children: [ Expanded( child: TextFormField( controller: model.plantationdateController, keyboardType: TextInputType.datetime, decoration: InputDecoration( labelText: 'Plantation Date *', hintText: 'DD-MM-YYYY', errorText: model.errorMessage.isNotEmpty ? model.errorMessage : null, ), validator: model.validateplantationdate, onChanged: model.onplantationdateChanged, // Format the date before displaying it in the TextFormField ), ), const SizedBox(width: 15), Expanded( child: TextFormField( controller: model.baselDateController, keyboardType: TextInputType.datetime, decoration: InputDecoration( labelText: 'Basel Date', hintText: 'DD-MM-YYYY', errorText: model.errorMessageforbasel.isNotEmpty ? model.errorMessageforbasel : null, ), onChanged: model.onBaseldateChanged, ), ), ], ), //Text Row( children: [ Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.irrigationMethod, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Irrigation Method *', ), hint: const Text('Select Irrigation Method'), items: model.irrigationmethodList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model .setSelectedirrigationmethod(value), validator: model.validateirrigationMethod, ), ), ), const SizedBox(width: 15), Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( isExpanded: true, value: model.canedata.seedMaterial, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Seed Material *', ), hint: const Text('Select Seed Material'), items: model.seedmaterialList.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText(val), ); }).toList(), onChanged: (value) => model.setselectedSeedMaterial(value), validator: model.validateSeedMaterial, ), ), ), ], ), Row( children: [ Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( value: model.canedata.isMachine, // Replace null with the selected value if needed decoration: const InputDecoration( labelText: 'Is Machine', ), isExpanded: true, hint: const AutoSizeText('Select Is Machine'), items: model.yesnomachine.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText( val, overflow: TextOverflow.ellipsis, ), ); }).toList(), onChanged: (value) => model.setSelectedisMachine(value), ), ), ), const SizedBox(width: 15), Expanded( child: CdropDown( dropdownButton: DropdownButtonFormField<String>( value: model.canedata.seedType, // Replace null with the selected value if needed isExpanded: true, decoration: const InputDecoration( labelText: 'Seed Type', ), hint: const AutoSizeText('Select Seed Type'), items: model.seedType.map((val) { return DropdownMenuItem<String>( value: val, child: AutoSizeText( val, overflow: TextOverflow.ellipsis, ), ); }).toList(), onChanged: (value) => model.setSelectedseedType(value), ), ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CtextButton( text: 'Cancel', onPressed: () => Navigator.of(context).pop(), buttonColor: Colors.red, ), CtextButton( onPressed: () => model.onSavePressed(context), text: 'Save', buttonColor: Colors.green, ), ], ), ], ), ), ), ), loader: model.isBusy, context: context, ), )); } }
import java.util.*; public class SudokuSolver { private static final int BOARD_SIZE = 9; private char[][] board; public SudokuSolver(char[][] initialBoard) { this.board = new char[BOARD_SIZE][BOARD_SIZE]; for (int i = 0; i < BOARD_SIZE; i++) { System.arraycopy(initialBoard[i], 0, this.board[i], 0, BOARD_SIZE); } } public boolean solve() { return solveSudoku(); } private boolean solveSudoku() { for (int row = 0; row < BOARD_SIZE; row++) { for (int col = 0; col < BOARD_SIZE; col++) { if (board[row][col] == '.') { for (char c = '1'; c <= '9'; c++) { if (isValid(row, col, c)) { board[row][col] = c; if (solveSudoku()) { return true; } else { board[row][col] = '.'; } } } return false; } } } return true; } private boolean isValid(int row, int col, char c) { for (int i = 0; i < BOARD_SIZE; i++) { if (board[i][col] == c || board[row][i] == c || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) { return false; } } return true; } public void printSolution() { for (int i = 0; i < BOARD_SIZE; i++) { if (i % 3 == 0 && i != 0) { System.out.println("---------------------"); } for (int j = 0; j < BOARD_SIZE; j++) { if (j % 3 == 0 && j != 0) { System.out.print("| "); } System.out.print(board[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { char[][] initialBoard = { {'9', '5', '7', '.', '1', '3', '.', '8', '4'}, {'4', '8', '3', '.', '5', '7', '1', '.', '6'}, {'.', '1', '2', '.', '4', '9', '5', '3', '7'}, {'1', '7', '.', '3', '.', '4', '9', '.', '2'}, {'5', '.', '4', '9', '7', '.', '3', '6', '.'}, {'3', '.', '9', '5', '.', '8', '7', '.', '1'}, {'8', '4', '5', '7', '9', '.', '6', '1', '3'}, {'.', '9', '1', '.', '3', '6', '.', '7', '5'}, {'7', '.', '6', '1', '8', '5', '4', '.', '9'} }; SudokuSolver solver = new SudokuSolver(initialBoard); if (solver.solve()) { System.out.println("Sudoku puzzle solved:"); solver.printSolution(); } else { System.out.println("No solution exists for the given Sudoku puzzle."); } } }
//reclamo.js import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import { Button, Table } from 'react-bootstrap'; //la siguiente linea generaba un warning de falta de uso, se comento para eliminar si no genera problemas //import { useNavigate } from 'react-router-dom'; const ReclamoDueño = () => { const [reclamos, setReclamos] = useState([]); useEffect(() => { async function fetchReclamos() { try { const token = localStorage.getItem('token'); // Obtener todas las unidades const unidadesResponse = await fetch(`/api/unidades`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, }); if (!unidadesResponse.ok) { throw new Error('Error al obtener los edificios'); } const unidadesData = await unidadesResponse.json(); //devolver solo las unidades de las cuales el usuario sea dueño const unidadesDeUsuario = unidadesData.filter(unidad => unidad.idPropietario == localStorage.getItem('id')); console.log(unidadesDeUsuario); // obtener todos los reclamos const response = await fetch('/api/reclamos', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` } }); if (!response.ok) { throw new Error('Error al mostrar reclamos'); } const reclamosData = await response.json(); //obtener un arreglo con los idEdificio de las unidades de las cuales el usuario es dueño const idEdificiosDeUsuario = unidadesDeUsuario.map(unidad => unidad.idEdificio); //filtrar los reclamos para mostrar solo aquellos pertenecientes al o los edificios en los que el usuario es propietarios de al menos una unidad const reclamosFiltrados = reclamosData.filter(reclamo => idEdificiosDeUsuario.includes(reclamo.idEdificio)); setReclamos(reclamosFiltrados); } catch (error) { console.error('Error fetching reclamos:', error); // Manejar el error de alguna manera (mostrar un mensaje al usuario, por ejemplo) } } fetchReclamos(); }, []); // Se ejecuta solo al montar el componente const decodeBase64Image = (base64) => { return `data:image/png;base64,${base64}`; }; return ( <div className="container"> <div className="content"> <div className="title"> <h1>Menu de Reclamos - Dueños</h1> </div> <div className="description"> <p> Por favor seleccione una de las opciones para continuar (tal vez aquí abajo tendríamos que mostrar una lista con las unidades del chabón, los estados los manejamos nosotros) </p> </div> <div className="button-wrapper"> <Link to="/agregar-reclamo-dueño"> <Button color="primary" size="lg" style={{ width: '250px', fontSize: '20px', margin: '10px' }}> Agregar Reclamo </Button> </Link> <Link to="/imagen-reclamo-dueño"> <Button color="primary" size="lg" style={{ width: '250px', fontSize: '20px', margin: '10px' }} > Agregar Imagen </Button> </Link> </div> <div className="table-wrapper"> <Table striped bordered hover> <thead> <tr> <th>id</th> <th>Estado</th> <th>Ubicación</th> <th>ID Edificio</th> <th>ID Unidad</th> <th>Tipo de Reclamo</th> <th>Descripción</th> <th>ID Usuario</th> <th>Notas</th> <th>Imagen</th> </tr> </thead> <tbody> {reclamos.map(reclamo => ( <tr key={reclamo.id}> <td>{reclamo.id}</td> <td>{reclamo.estado}</td> <td>{reclamo.ubicacion}</td> <td>{reclamo.idEdificio}</td> <td>{reclamo.idUnidad == 0 ? "Parte Comun" : reclamo.idUnidad}</td> <td>{reclamo.tipoReclamo}</td> <td>{reclamo.descripcion}</td> <td>{reclamo.idUsuario}</td> <td>{reclamo.notas}</td> <td> {reclamo.imagenBase64 && ( <img src={decodeBase64Image(reclamo.imagenBase64)} alt="Imagen Reclamo" style={{ maxWidth: '100px', maxHeight: '100px' }} /> )} </td> </tr> ))} </tbody> </Table> </div> </div> </div> ); }; export default ReclamoDueño;
import { StyleSheet, ImageBackground, SafeAreaView } from "react-native"; import StartGameScreen from "./screens/StartGameScreen"; import GameOverScreen from "./screens/GameOverScreen"; import { LinearGradient } from "expo-linear-gradient"; import { useEffect, useState } from "react"; import GameScreen from "./screens/GameScreen"; import Colors from "./constants/colors"; import { useFonts } from "expo-font"; import { StatusBar } from "expo-status-bar"; import * as SplashScreen from "expo-splash-screen"; SplashScreen.preventAutoHideAsync() .then((result) => {}) .catch(console.warn); export default function App() { const [userNumber, setUserNumber] = useState(); const [gameIsOver, setGameOver] = useState(false); const [guessRounds, setGuessRounds] = useState(0); const [fontsLoaded] = useFonts({ "open-sans": require("./assets/fonts/OpenSans-Regular.ttf"), "open-sans-bold": require("./assets/fonts/OpenSans-Bold.ttf"), }); // Watch for fonts to be loaded, then hide the splash screen useEffect(() => { async function hideSplashScreen() { await SplashScreen.hideAsync(); } if (fontsLoaded) { hideSplashScreen(); } }, [fontsLoaded]); // Initally return null instead of <AppLoading /> if (!fontsLoaded) { // return <AppLoading />; return null; } function pickedNumberHandler(pickNumber) { setUserNumber(pickNumber); setGameOver(false); } function gameOverHandler(numOfRounds) { setGameOver(true); setGuessRounds(numOfRounds); } function startNewGameHandler() { setUserNumber(null); setGameOver(true); setGuessRounds(0); } let screen = <StartGameScreen onConfirmNumber={pickedNumberHandler} />; if (userNumber) { screen = ( <GameScreen userNumber={userNumber} onGameOver={gameOverHandler} /> ); } if (gameIsOver && userNumber) { screen = ( <GameOverScreen userNumber={userNumber} roundsNumber={guessRounds} onStartNewGame={startNewGameHandler} /> ); } return ( <> <StatusBar /> <LinearGradient colors={[Colors.primary700, Colors.accent500]} style={styles.rootScreen} > <ImageBackground source={require("./assets/images/background.png")} resizeMode="cover" style={styles.rootScreen} imageStyle={styles.backgroundImage} > <SafeAreaView style={styles.rootScreen}>{screen}</SafeAreaView> </ImageBackground> </LinearGradient> <StatusBar style="light" /> </> ); } const styles = StyleSheet.create({ rootScreen: { flex: 1, }, backgroundImage: { opacity: 0.15, }, });
<script setup lang="ts"> import { ref, watch } from 'vue'; const nombre = ref('nombre'); const apellido = ref('apellido'); const mensajeInvalido = ref(''); const mensajeedad = ref(''); const mensajetelefono = ref(''); const edad = ref(0); const genero = ref(''); const telefono = ref(''); function mensaje() { if (nombre.value === apellido.value) { mensajeInvalido.value = 'Los nombres no pueden ser iguales.'; } else { mensajeInvalido.value = ''; } if (edad.value >= 0 && edad.value <= 60) { mensajeedad.value = '' } else { mensajeedad.value = 'Edad invalidad 0 a 60 años'; } if (telefono.value.length >= 10) { mensajetelefono.value = 'inserte solo 10 numeros'; } else { mensajetelefono.value = ''; } } watch([nombre, apellido, edad, telefono], () => { mensaje(); }); </script> <template> <div class="form"> <h3>Nombre</h3> <input type="text" v-model="nombre"> <h3>Apellido</h3> <input type="text" v-model="apellido"> <p v-if="mensajeInvalido !== ''" class="error-message">{{ mensajeInvalido }}</p> <h3>Género</h3> <select v-model="genero"> <option value="">Selecciona una opción</option> <option value="Masculino">Masculino</option> <option value="Femenino">Femenino</option> <option value="Otro">Otro</option> </select> <h3>Edad</h3> <input type="number" v-model="edad"> <p v-if="mensajeedad !== ''" class="error-message">{{ mensajeedad }}</p> <h3>Número de teléfono</h3> <input type="tel" pattern="[0-9]{10}" v-model="telefono"> <p v-if="mensajetelefono !== ''" class="error-message">{{ mensajetelefono }}</p> </div> <div> <h1> INFORMACION</h1> <h5> Nombre : {{ nombre }} </h5> <h5> Apellido : {{ apellido }}</h5> <h5> Edad : {{ edad }}</h5> <h5> Genero : {{ genero }}</h5> <h5> Numero de telefono : {{ telefono }}</h5> </div> </template> <style scoped> .form { max-width: 400px; margin: 0 auto; } h3 { font-size: 18px; margin-bottom: 8px; } input, select { width: 100%; padding: 10px; margin-bottom: 16px; border: 1px solid #360055; border-radius: 8px; font-size: 16px; outline: none; } .input-error { border-color: #FF3333; } .error-message { color: #FF3333; font-size: 16px; margin-top: 8px; padding: 8px; background-color: #FFD6D6; border: 1px solid #E57373; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } /* Add any additional styling based on your preference */ </style>
// // Api.swift // APILearning // // Created by Luiz Sena on 16/08/22. // import Foundation //Using completion handler class API { static func getUsers() { let url = URL(string: "http://adaspace.local/users")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in // print("response: \(String(describing: response)), data: \(String(describing: data)), error: \(String(describing: error))") guard let responseData = data else {return} do { let users = try JSONDecoder().decode([Users].self, from: responseData) print(users[1]) } catch let error { print("error: \(error)") } // if let responseString = String(data: responseData, encoding: .utf8) { // // print(responseString) // } } task.resume() } static func getUsers(id:String) async -> User { let url: URL = URL(string: "http://adaspace.local/users/\(id)")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "GET" do { let (data, _) = try await URLSession.shared.data(for: urlRequest) let userDecoded = try JSONDecoder().decode(User.self, from: data) return userDecoded } catch{ print(error) } return User(email: "", id: "", name: "") } static func getAllPosts() async -> [Post] { let url: URL = URL(string: "http://adaspace.local/posts")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "GET" do { let (data, _) = try await URLSession.shared.data(for: urlRequest) let allPostsDecoded = try JSONDecoder().decode([Post].self, from: data) return allPostsDecoded } catch { print(error) } return [] } static func postLogin() async -> [Post] { let url: URL = URL(string: "http://adaspace.local/posts")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" do { let (data, _) = try await URLSession.shared.data(for: urlRequest) let allPostsDecoded = try JSONDecoder().decode([Post].self, from: data) return allPostsDecoded } catch { print(error) } return [] } static func loginUser(email:String, password:String) async -> String { guard let url = URL(string:"http://adaspace.local/users/login")else{ return"" } var urlRequest = URLRequest(url:url) urlRequest.httpMethod = "POST" // urlRequest.addValue("application/json", forHTTPHeaderField: "Accept") urlRequest.allHTTPHeaderFields=[ "Content-Type": "application/json" ] let authData = (email + ":" + password).data(using: .utf8)!.base64EncodedData() let authString = String(data: authData, encoding: .utf8)! print(String(data: authData, encoding: .utf8)!) urlRequest.addValue("Basic \(authString)",forHTTPHeaderField: "Authorization") let dict: String = "" do { let dictData = try JSONSerialization.data(withJSONObject: dict, options: .fragmentsAllowed) urlRequest.httpBody = dictData let (data, response) = try await URLSession.shared.data(for: urlRequest) print(String(data: data, encoding: .utf8)!) let decoded = try JSONDecoder().decode(Token.self, from: data) if let responseHeader = response as? HTTPURLResponse { if responseHeader.statusCode == 200 { print(String(data: data, encoding: .utf8)!) return String(decoded.token) } } print(decoded.token) } catch { print(error) } return "" } }
import { useState } from "react"; import styled from "styled-components"; import { VideoData } from "./SoriAward"; import gold from "../../../assets/gold.png"; import silver from "../../../assets/silver.png"; import bronze from "../../../assets/bronze.png"; import smiling from "../../../assets/smiling.png"; import { s3URL } from "../../../utils/s3"; import { useNavigate, useParams } from "react-router-dom"; const Container = styled.div` position: relative; display: flex; justify-content: center; align-items: center; perspective: 90%; transform-style: preserve-3d; width: 100%; height: 18rem; flex-grow: 1; .nav { color: rgba(255 ,255, 255, 0.7); font-size: 3rem; position: absolute; display: flex; justify-content: center; align-items: center; z-index: 2; cursor: pointer; user-select: none; background: unset; border: unset; transition: all 200ms ease; &.left { left: 0; transform: translateX(-25%) translateY(0); filter: drop-shadow(3px 3px 4px rgba(0, 0, 0, 0.1)); &:hover { color: #fbfbfb; } } &.right { filter: drop-shadow(3px 3px 4px rgba(0, 0, 0, 0.1)); right: 0; transform: translateX(25%) translateY(-0%); &:hover { color: #fbfbfb; } } } ` const Card = styled.div<{ $active: boolean, $offset: number, $direction: number, $absOffset: number, $isOver: boolean }>` width: 90%; height: 90%; position: absolute; transform: ${(props) => ` rotateY(calc(${props.$offset} * 50deg)) scaleY(calc(1 + ${props.$absOffset} * -0.4)) translateZ(calc(${props.$absOffset} * -20rem)) `}; filter: ${(props) => `blur(calc(${props.$absOffset} * 0.7rem))`}; transition: all 0.3s ease-out; opacity: ${(props) => props.$isOver ? "0" : "1"}; display: ${(props) => props.$isOver ? "none" : "flex"}; flex-direction: column; align-items: center; .img-box { width: 75%; height: 80%; box-shadow: ${(props) => props.$active && '0px 0px 10px 10px rgba(191, 255, 10, 0.5)'}; border-radius: 5px; position: relative; .img { width: 100%; height: 100%; } .medal { position: absolute; left: 2%; top: 4%; display: ${(props) => props.$active ? "block" : "none"}; } .like-box { display: ${(props) => props.$active ? "flex" : "none"}; gap: .5rem; align-items: center; justify-content: center; background: rgba(0, 0, 0, 0.7); border: 0.5px solid #BFFF0A; border-radius: 10px; padding: .2rem .75rem; position: absolute; right: 2%; bottom: 4%; .smile { height: 90%; } .like { color: #BFFF0A; font-size: 1.6rem; font-family: 'GmarketSansBold'; } } } .title { display: ${(props) => props.$active ? "-webkit-box" : "none"}; color: white; font-size: 1.5rem; height: 20%; margin-top: 1.5rem; overflow: hidden; text-overflow: ellipsis; white-space: normal; line-height: 1.2; word-wrap: break-word; -webkit-line-clamp: 2 ; -webkit-box-orient: vertical; } ` const Carousel: React.FC<{ hotContents: VideoData[]}> = ({ hotContents }) => { const navigate = useNavigate(); const params = useParams(); const count = hotContents.length; const MAX_VISIBILITY = hotContents.length; const [active, setActive] = useState(0); return ( <Container className="carousel"> {active > 0 && ( <button className="nav left text-white" onClick={() => setActive((active) => active - 1)} > { '<' } </button> )} {hotContents.map((child, i) => ( <Card onClick={() => navigate(`/dubbing/${params.sourceCode}/${child.dubCode}`)} $active={i === active ? true : false} $offset={(active - i) / 3} $direction={Math.sign(active - 1)} $absOffset={Math.abs(active - i) / 3} $isOver={Math.abs(active - i) >= MAX_VISIBILITY} key={child.dubCode} className="card-container" > <div className="img-box"> <img className="medal" src={ i === 0 && gold || i === 1 && silver || i === 2 && bronze || '' } alt="medal" /> <img className="img" src={s3URL + child.thumbnailPath} alt="" /> <div className="like-box"> <img className="smile" src={smiling} alt="like" /> <p className="like">+ {child.likeCount}</p> </div> </div> <p className="title">{child.dubName}</p> </Card> ))} {active < count - 1 && ( <button className="nav right text-white" onClick={() => setActive((active) => active + 1)} > { '>' } </button> )} </Container> ) } export default Carousel;
package com.dnd.gooding.domain.file.domain; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.UUID; import org.springframework.web.multipart.MultipartFile; import lombok.Builder; import lombok.Getter; @Getter public class FileCreate { private String extension; private String fileUrl; private String originName; private String newName; private String fileDir; private Long fileSize; @Builder public FileCreate(String extension, String fileUrl, String originName, String newName, Long fileSize) { this.extension = extension; this.fileUrl = fileUrl; this.originName = originName; this.newName = newName; this.fileSize = fileSize; } public FileCreate(String environment, String basicDir) { if ("local".equals(environment)) { this.fileDir = System.getProperty("user.dir") + basicDir; } else if ("development".equals(environment)) { this.fileDir = basicDir; } } public FileCreate create(String fileUrl) { return FileCreate.builder() .extension(extension) .fileUrl(fileUrl) .originName(originName) .newName(newName) .fileSize(fileSize) .build(); } public void update(String extension) { this.extension = extension; } public void update(String originName, String newName, Long fileSize) { this.originName = originName; this.newName = newName; this.fileSize = fileSize; } public Optional<File> convert(MultipartFile multipartFile) throws IOException { if (multipartFile.isEmpty()) { return Optional.empty(); } String originalFilename = multipartFile.getOriginalFilename(); String newFileName = createStoreFileName(originalFilename); File file = new File(fileDir + newFileName); multipartFile.transferTo(file); update(originalFilename, newFileName, file.length()); return Optional.of(file); } private String createStoreFileName(String originalFilename) { String extension = extractExtension(originalFilename); String uuid = UUID.randomUUID().toString(); update(extension); return uuid + "." + extension; } private String extractExtension(String originName) { int position = originName.lastIndexOf("."); return originName.substring(position + 1); } }
// // ViewController.swift // Weather-test-app // // Created by Serhii Navka on 05.08.2022. // import UIKit import Core import Combine class HomeViewController: UITableViewController { var viewModel: HomeViewModel! var searchResultsController: SearchResultsController! private var searchController: UISearchController! private var cancelBag: Set<AnyCancellable> = .init() override func viewDidLoad() { super.viewDidLoad() title = "Weather" searchResultsController.delegate = self searchController = UISearchController(searchResultsController: searchResultsController) navigationItem.searchController = searchController setupBindings() } } // MARK: - Actions extension HomeViewController { @objc private func toggleMeasure(_ sender: UIBarButtonItem) { viewModel.toggleMeasureType() } } // MARK: - Private extension HomeViewController { private func setupBindings() { searchController.searchBar.searchTextField .textPublisher .map { $0 == nil ? "" : $0! } .receive(subscriber: viewModel.querySubscriber) viewModel.reload.sink { [weak self] in self?.tableView.reloadData() }.store(in: &cancelBag) viewModel.measureTitle.sink { [weak self] in self?.setupMeasureBarButton(title: $0) }.store(in: &cancelBag) } private func setupMeasureBarButton(title: String) { navigationItem.rightBarButtonItem = UIBarButtonItem( title: title, style: .plain, target: self, action: #selector(toggleMeasure) ) } } // MARK: - UITableViewDataSource && UITAbleViewDelegate extension HomeViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 92.0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.cities.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: String(describing: HomeCityCell.self), for: indexPath ) as! HomeCityCell cell.viewModel = viewModel.viewModel(at: indexPath.row) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let city = viewModel.cities[indexPath.row] viewModel.showDetailedWeather(for: city) } } // MARK: - SearchResultsControllerDelegate extension HomeViewController: SearchResultsControllerDelegate { func searchResultsShouldHide(_ controller: SearchResultsController) { searchController.isActive = false } }
import { useState, useEffect } from 'react'; import { ethers } from 'ethers'; const useWallet = () => { const [account, setAccount] = useState(''); const [state, setState] = useState(''); const [error, setError] = useState(''); useEffect(() => { const checkWallet = async () => { setState('loading'); try { console.log('checking wallet'); // First make sure we have access to window.ethereum const { ethereum } = window; if (!ethereum) { console.log('Make sure you have metamask!'); setError('Make sure you have metamask!'); return; } else { console.log('We have the ethereum object', ethereum); } // Check if we're authorized to access the user's wallet const accounts = await ethereum.request({ method: 'eth_accounts' }); if (accounts.length) { const account = accounts[0]; console.log('Found an authorized account:', account); setAccount(account); } else { console.log('No authorized account found'); setError('No authorized account found'); } } catch (error) { console.log(error); setError(error.message); } setState(''); } checkWallet(); }, []); const connect = async () => { setState('loading'); try { console.log('checking wallet'); // First make sure we have access to window.ethereum const { ethereum } = window; if (!ethereum) { console.log('Make sure you have metamask!'); setError('Make sure you have metamask!'); return; } const accounts = await ethereum.request({ method: 'eth_requestAccounts', }); console.log('Connected', accounts[0]); setAccount(accounts[0]); } catch (error) { console.log(error); setError(error.message); } setState(''); }; return { account, walletState: state, walletError: error, connectWallet: connect, } }; export default useWallet;
import { motion } from "framer-motion"; import { useEffect } from "react"; import { useState } from "react"; import { styles } from "../styles"; import { ComputersCanvas } from "./canvas"; const Hero = () => { const [typedText, setTypedText] = useState(""); const typingOptions = [ "Web Application", "Collaboration Tools", "Online Marketplaces", "E-commerce Platforms", "Content Management Systems", "Learning Management Systems", "Real-time Chat Applications", "Booking and Reservation Systems", ]; useEffect(() => { let currentIndex = 0; let currentText = ""; let interval; const type = () => { if (currentIndex === typingOptions.length) { currentIndex = 0; } const targetText = typingOptions[currentIndex]; const targetLength = targetText.length; if (currentText.length < targetLength) { currentText = targetText.substring(0, currentText.length + 1); setTypedText(currentText); } else { clearInterval(interval); setTimeout(() => { interval = setInterval(erase, 50); }, 2000); } }; const erase = () => { if (currentText.length === 0) { currentIndex++; clearInterval(interval); interval = setInterval(type, 200); } else { currentText = currentText.substring(0, currentText.length - 1); setTypedText(currentText); } }; interval = setInterval(type, 200); return () => clearInterval(interval); }, []); return ( <section className="relative w-full h-screen mx-auto"> <div className={`${styles.paddingX} absolute inset-0 top-[120px] max-w-7xl mx-auto flex flex-row items-start gap-5`} > <div className="flex flex-col justify-center items-center mt-5"> <div className="w-5 h-5 rounded-full bg-[#915eff]" /> <div className="w-1 sm:h-80 h-40 violet-gradient" /> </div> <div> <h1 className={`${styles.heroHeadText} text-white`}> Hi, I'm <span className="text-[#915eff]">Shishir</span> </h1> <p className="{`${styles.heroSubText} mt-2 text-white-100`} font-bold text-4xl"> I develop{" "} <span className="typing-animation text-[#915eff] text-4xl font-bold">{typedText}</span> </p> </div> </div> <ComputersCanvas /> <div className="absolute xs:bottom-10 bottom-32 w-full flex justify-center items-center"> <a href="#about"> <div className="w-[35px] h-[64px] rounded-3xl border-4 border-secondary flex justify-center items-start p-2"> <motion.div animate={{ y: [0, 24, 0] }} transition={{ duration: 1.2, repeat: Infinity, repeatType: "loop", }} className="w-3 h-3 rounded-full bg-secondary mb-1" ></motion.div> </div> </a> </div> </section> ); }; export default Hero;
import React, {Component} from 'react'; import {View, Text,StyleSheet, TouchableOpacity, ActivityIndicator, Image} from "react-native"; import AsyncStorage from '@react-native-community/async-storage'; import axios from "axios"; import animacaoTorneira from "../animacoes/animacaoTorneira.json"; import Lottie from "lottie-react-native"; import ImgConfig from "../imagens/config.png"; export default class Torneira extends Component{ static navigationOptions = { headerTitle: "Torneira" } constructor(props){ super(props); this.state = { loop: false, agua: false, ip: "", carregando: true, carregandoLigar: false, carregandoDesligar: false, erro: "" } } async componentDidMount(){ let ip = await AsyncStorage.getItem("ip"); if(ip) this.setState({ip}); this.setStatus(); if(this.state.agua) this.animacao.play(0, 20); this.telaEmExibicao = this.props.navigation.addListener('didFocus', async () => { this.setState({carregandoDesligar: false, carregandoLigar: false, carregando: false}); let ip = await AsyncStorage.getItem("ip"); if(ip) this.setState({ip}); console.log(this.state.ip); }); } componentWillUnmount() { this.telaEmExibicao.remove(); } setStatus = () => { axios.get("http://"+this.state.ip).then(response => { if(response.data.indexOf("Torneira Ligada") > -1){ this.setState({agua: true}); this.animacao.play(0, 20); }else(response.data.indexOf("Torneira Parada") > -1) this.setState({agua: false}); this.setState({carregando: false}); this.setState({erro: ""}); }).catch((erro)=>{ this.setState({carregando: false}); if(erro.toString().indexOf("play") < 0){ this.setState({erro: "Não foi possivel se conectar ao aparelho =(", carregando: false}); this.animacao.play(36, 60); this.setState({agua: false}); }else{ this.animacao.play(0, 20); } }); } ligar = () => { if(!this.state.agua && !this.state.carregandoLigar && !this.state.carregandoDesligar && !this.state.carregando){ this.setState({carregandoLigar: true}); this.setState({loop: false}); axios.get("http://"+this.state.ip+"?ligarTorneira").then(() => { this.animacao.play(0, 20); this.setState({carregandoLigar: false, carregando: false}); this.setState({agua: true}); this.setState({erro: ""}); }).catch(()=>{ this.setState({erro: "Não foi possivel se conectar ao aparelho =("}); this.setState({carregandoLigar: false, carregando: false}); this.animacao.play(49, 50); }); } } desligar = () => { if(this.state.agua && !this.state.carregandoLigar && !this.state.carregandoDesligar && !this.state.carregando){ this.setState({carregandoDesligar: true}) this.setState({loop: false}); axios.get("http://"+this.state.ip+"?pararTorneira").then(() => { this.animacao.play(36, 60); this.setState({carregandoDesligar: false}); this.setState({erro: ""}); }).catch(()=>{ this.setState({erro: "Não foi possivel se conectar ao aparelho =(", carregandoDesligar: false}); this.animacao.play(49, 50); }); this.setState({agua: false}); } } render(){ return( <View style={estilos.container}> { !this.state.carregando ? <Lottie source={animacaoTorneira} ref={(animation) => { this.animacao = animation }} style={estilos.animacao} onAnimationFinish={() => { if(this.state.agua){ this.animacao.play(21, 35); this.setState({loop: true}) } }} loop={this.state.loop}/> : <ActivityIndicator size="large" color="#e61919"/> } <Text style={estilos.erro}>{this.state.erro}</Text> <TouchableOpacity style={[estilos.button, {backgroundColor: "green"}]} onPress={this.ligar}> {this.state.carregandoLigar ? <ActivityIndicator size="large" color="white"/> : <Text style={estilos.rotulo}>Ligar</Text>} </TouchableOpacity> <TouchableOpacity style={estilos.button} onPress={this.desligar}> {this.state.carregandoDesligar ? <ActivityIndicator size="large" color="white"/> : <Text style={estilos.rotulo}>Desligar</Text>} </TouchableOpacity> <TouchableOpacity style={[estilos.button, {width: 60, height: 60, backgroundColor: "#4682B4", marginLeft: 140}]} onPress={() => { this.props.navigation.navigate("MudarIP", {tela: "Torneira"}); this.setState({carregandoDesligar: false}); }}> <Image source={ImgConfig} style={[estilos.icones, {width: 45, marginRight: 8}]}/> </TouchableOpacity> </View> ); } } const estilos = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center" }, button: { backgroundColor: "red", padding: 10, alignItems: "center", justifyContent: "center", borderRadius: 4, width: 200, height: 70, marginBottom: 20, flexDirection: "row" }, rotulo: { color: "white", fontSize: 27, fontFamily: 'BigStem-Regular', }, icones: { resizeMode: "stretch", width: 50, height: 50, marginLeft: 10 }, animacao: { width: 200, height: 200, marginBottom: 0, }, erro: { color: "red", fontSize: 16, fontWeight: "bold", marginBottom: 7 } });
package pt.isec.amov.ui.screens import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import pt.isec.amov.R import pt.isec.amov.ui.composables.NormalBtn import pt.isec.amov.ui.viewmodels.ActionsViewModel import pt.isec.amov.ui.viewmodels.Screens @Composable fun Menu( title: String, navHostController: NavHostController?, vm : ActionsViewModel ) { Box( modifier = Modifier .fillMaxSize() .padding(16.dp), contentAlignment = Alignment.Center ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp) ) { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "logo", contentScale = ContentScale.Fit, modifier = Modifier .fillMaxWidth() .height(200.dp) ) Spacer(modifier = Modifier.height(90.dp)) if(vm.user.value != null){ NormalBtn( onClick = { navHostController?.navigate(Screens.LOCATION.route) }, text = vm.user.value!!.email ) }else{ NormalBtn( onClick = { navHostController?.navigate(Screens.LOGIN.route) }, text = stringResource(R.string.login) ) Spacer(modifier = Modifier.height(16.dp)) NormalBtn( onClick = { navHostController?.navigate(Screens.REGISTER.route) }, text = stringResource(R.string.Register) ) } Spacer(modifier = Modifier.height(16.dp)) NormalBtn( onClick = { navHostController?.navigate(Screens.CREDITS.route) }, text = stringResource(R.string.Credits) ) } } }
import { describe, expect, it } from 'vitest'; import { Appointment } from '../entities/appointment'; import { InMemoryAppointmentsRepository } from '../repositories/in-memory/in-memory-appointments-repository'; import { getFutureDate } from '../tests/utils/get-future-date'; import { CreateAppointment } from './create-appointment'; describe('create appointment', () => { it('should create an appointment', () => { const appointmentsRepository = new InMemoryAppointmentsRepository(); const createAppointment = new CreateAppointment(appointmentsRepository); const startsAt = getFutureDate('2022-10-28'); const endsAt = getFutureDate('2022-10-29'); expect(createAppointment.execute({ costumer: 'John Doe', startsAt, endsAt, })).resolves.toBeInstanceOf(Appointment) }) it('should not create an appointment with overlapping dates', async () => { const appointmentsRepository = new InMemoryAppointmentsRepository(); const createAppointment = new CreateAppointment(appointmentsRepository); const startsAt = getFutureDate('2022-10-28'); const endsAt = getFutureDate('2022-11-05'); await createAppointment.execute({ costumer: 'John Doe', startsAt, endsAt, }) expect(createAppointment.execute({ costumer: 'John Doe', startsAt: getFutureDate('2022-10-30'), // overlapping date endsAt: getFutureDate('2022-11-05'), // overlapping date })).rejects.toBeInstanceOf(Error) // should throw an error }) })
import { Body, Controller, Delete, ForbiddenException, Get, Headers, Param, Patch, Put, UseGuards } from '@nestjs/common'; import FindOneParams from '../../utils/findOneParams'; import AgentService from './agent.service'; import Agent from './entities/agent.entity'; import { ApiBearerAuth, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'; import JwtAuthenticationGuard from '../../authentication/guards/jwt-authentication.guard'; import AreaService from '../../areas/area.service'; import UpdateAreaDTO from '../../areas/dto/updateArea.dto'; import UpdateAgentAreaDTO from './dto/updateAgentArea.dto'; import BoostaGenericHeader from '../../utils/generic.headers'; import { ConfigService } from '@nestjs/config'; @Controller('agents') // @ApiBearerAuth() @ApiTags('Agents') export default class AgentController { constructor( private readonly agentService: AgentService, private readonly areaService: AreaService, private readonly configService: ConfigService, ) { } @Get() @ApiBearerAuth() @UseGuards(JwtAuthenticationGuard) async getAllAgents(): Promise<Agent[]> { return await this.agentService.getAllAgents(); } @Get('/areas/:id') @ApiParam({ type: "string", name: "id", description: "The area ID" }) // @UseGuards(JwtAuthenticationGuard) async getAllAgentsInAnArea(@Param() { id }: FindOneParams): Promise<Agent[]> { const area = await this.areaService.getAreaById(id); return await this.agentService.getAllAgentsInAnArea(area); } @Get('areas/with-admin-access/:id') @ApiParam({ name: 'id', description: 'Area ID', }) @ApiOperation({ description: 'Returns all agents in this area.', }) async getAnAgentsInAnArea(@Param() { id }: FindOneParams) { // async getAllAgentsInAnAreaWithAdminAccess(@Param() { id }: FindOneParams, @Headers() headers: BoostaGenericHeader) { // const adminSignUpToken: string = headers.adminsignuptoken; // if (adminSignUpToken != this.configService.get('ADMIN_SIGN_UP_TOKEN')) // throw new ForbiddenException( // 'You are not allowed to make this request.', // ); const area = await this.areaService.getAreaById(id); return this.agentService.getAnAgentsInAnArea((area)) } @Get('users/:id') @ApiBearerAuth() @UseGuards(JwtAuthenticationGuard) @ApiBearerAuth() @ApiParam({ name: 'id', description: 'The Agent User ID. Note: User ID must be the one gotten from the auth service', }) @ApiOperation({ description: 'Returns the agent data.', }) async getAgent(@Param() { id }: FindOneParams) { return await this.agentService.getAgentByUserAuthServiceUserID(id); } @Get('users/with-admin-access/:id') @ApiParam({ name: 'id', description: 'User ID', }) @ApiOperation({ description: 'Returns the agent data.', }) async getAgentWithAdminAccess(@Param() { id }: FindOneParams) { // async getAgentWithAdminAccess(@Param() { id }: FindOneParams, @Headers() headers: BoostaGenericHeader) { // const adminSignUpToken: string = headers.adminsignuptoken; // if (adminSignUpToken != this.configService.get('ADMIN_SIGN_UP_TOKEN')) // throw new ForbiddenException( // 'You are now allowed to make this request.', // ); return this.agentService.getAgentByUserAuthServiceUserID((id)) } @Get(':id') @ApiParam({ type: "string", name: "id", description: "The Agent ID" }) @ApiBearerAuth() @UseGuards(JwtAuthenticationGuard) async getAgentById(@Param() { id }: FindOneParams) { return this.agentService.getAgentById(id); } @Put(':id/update-agent') @ApiBearerAuth() @ApiParam({ type: "string", name: "id", description: "The Agent ID" }) async updateAgentArea(@Param() { id }: FindOneParams, @Body() areaData: UpdateAgentAreaDTO) { const area = await this.areaService.getAreaById(areaData.areaID); return this.agentService.updateAgent(id, area); } @Delete(':id') @ApiParam({ type: "string", name: "id", description: "The Agent ID" }) @ApiBearerAuth() @UseGuards(JwtAuthenticationGuard) async deleteAgent(@Param() { id }: FindOneParams) { await this.agentService.deleteAgent(id); } }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "general.h" #include "instructions.h" #include "symbols.h" int ROM_IRQ_ADDR[] = {0xC803, 0xC074 }; int PRODOS_IRQ_ADDR = 0xBFEB; char *mem_str[3] = { "RAM", "ROM", "none" }; /* LSR, ROL, ROR, ? */ char *read_instructions[] = { "adc", "and", "bit", "cmp", "cpx", "cpy", "eor", "jmp", "jsr", "ora", "lda", "ldx", "ldy", "sbc", NULL }; char *write_instructions[] = { "dec", "inc", "lsr", "rol", "ror", "sta", "stx", "sty", "stz", "trb", "tsb", NULL }; struct _instr_cycles { char *instruction; int cost[NUM_ADDR_MODES]; int cost_if_taken; }; /* Values are for the 65C02. * Ref1: https://www.masswerk.at/6502/6502_instruction_set.html * Ref2: http://6502.org/tutorials/65c02opcodes.html */ instr_cycles instr_cost[] = { /* {name, {imm, imp, acc, zero, zeroind,zeroxy, abs, absxy, indx, indy}} */ /* Math */ {"adc", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"and", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"asl", {0, 0, 2, 5, 0, 6, 6, 6, 0, 0}, 0}, {"eor", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"bit", {2, 0, 0, 3, 0, 4, 4, 4, 0, 0}, 0}, {"lsr", {0, 0, 2, 5, 0, 6, 6, 6, 0, 0}, 0}, {"ora", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"rol", {0, 0, 2, 5, 0, 6, 6, 6, 0, 0}, 0}, {"ror", {0, 0, 2, 5, 0, 6, 6, 6, 0, 0}, 0}, {"sbc", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"trb", {0, 0, 0, 5, 0, 0, 6, 0, 0, 0}, 0}, {"tsb", {0, 0, 0, 5, 0, 0, 6, 0, 0, 0}, 0}, /* Flow */ {"bcc", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bcs", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"beq", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bmi", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bne", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bpl", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bvc", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bvs", {0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, 1}, {"bra", {0, 0, 0, 0, 0, 0, 3, 0, 0, 0}, 0}, {"brk", {0, 7, 0, 0, 0, 0, 4, 0, 0, 0}, 0}, {"jmp", {0, 0, 0, 0, 0, 0, 3, 6, 5, 5}, 0}, {"jsr", {0, 0, 0, 0, 0, 0, 6, 0, 0, 0}, 0}, {"nop", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"rti", {0, 6, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"rts", {0, 6, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* Flags */ /* {name, {imm, imp, acc, zero, zeroind,zeroxy, abs, absxy, indx, indy}} */ {"clc", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"cld", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"cli", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"clv", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"sec", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"sed", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"sei", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* Compare */ {"cmp", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"cpx", {2, 0, 0, 3, 0, 0, 4, 0, 0, 0}, 0}, {"cpy", {2, 0, 0, 3, 0, 0, 4, 0, 0, 0}, 0}, /* Decrement */ {"dec", {0, 0, 2, 5, 0, 6, 6, 7, 0, 0}, 0}, {"dex", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"dey", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* Increment */ {"inc", {0, 0, 2, 5, 0, 6, 6, 7, 0, 0}, 0}, {"inx", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"iny", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* Loads and stores */ /* {name, {imm, imp, acc, zero, zeroind,zeroxy, abs, absxy, indx, indy}} */ {"lda", {2, 0, 0, 3, 5, 4, 4, 4, 6, 5}, 0}, {"ldx", {2, 0, 0, 3, 0, 4, 4, 4, 0, 0}, 0}, {"ldy", {2, 0, 0, 3, 0, 4, 4, 4, 0, 0}, 0}, {"sta", {0, 0, 0, 3, 5, 4, 4, 5, 6, 6}, 0}, {"stx", {0, 0, 0, 3, 0, 4, 4, 0, 0, 0}, 0}, {"sty", {0, 0, 0, 3, 0, 4, 4, 0, 0, 0}, 0}, {"stz", {0, 0, 0, 3, 0, 4, 4, 5, 0, 0}, 0}, {"tax", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"tay", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"tsx", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"txa", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"txs", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"tya", {0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* Stack */ {"pha", {0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"php", {0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"phx", {0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"phy", {0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"pla", {0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"plp", {0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"plx", {0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, {"ply", {0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, 0}, /* {name, {imm, imp, acc, zero, zeroind,zeroxy, abs, absxy, indx, indy}} */ {NULL, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0} }; /* Current memory banking */ int read_from = RAM; int write_to = NONE; int lc_bank = 1; extern int start_addr; static int _main_addr; static int handle_rom_irq_addr = 0x0; static int handle_ram_irq_addr = 0x0; extern int verbose; /* Statistics structure */ struct _function_calls { /* The address */ int addr; /* The source location */ const char *file; int line; /* The associated debug symbol */ dbg_symbol *func_symbol; /* Number of times the function's been called */ unsigned long call_count; /* Number of instructions and cycles inside this function, total */ unsigned long self_instruction_count; unsigned long self_cycle_count; /* Number of instructions and cycles inside this function, current call */ unsigned long cur_call_self_instruction_count; unsigned long cur_call_self_cycle_count; /* Number of instructions and cycles inside this function, * plus the ones it calls */ unsigned long incl_instruction_count; unsigned long incl_cycle_count; /* List of functions called by this one */ function_calls **callees; /* Number of functions called by this one */ int n_callees; }; /* The current call tree */ static function_calls **func_tree = NULL; /* The current call tree during an IRQ */ static function_calls **irq_tree = NULL; /* Pointer to which call tree to use */ static function_calls **tree_functions = NULL; /* The current tree depth */ static int tree_depth = 0; /* Storage for the tree depth before entering * IRQ handlers */ static int tree_depth_before_intr[2]; /* MLI hack (rti'ng from anywhere) */ static int mli_call_depth = -1; /* Interrupt handler counter (0xC803 will call * ProDOS's 0xBFEB), so two handlers will run */ static int in_interrupt = 0; /* Remember if we just rti'd out of IRQ */ static int just_out_of_irq = 0; /* Array of functions we track */ static function_calls **functions = NULL; /* The first call (at start address) */ static function_calls *root_call = NULL; /* Helper for mapping addresses and symbols */ int is_addr_in_cc65_user_bank (int op_addr) { return (read_from == RAM && (op_addr < 0xD000 || op_addr > 0xDFFF)) || (read_from == RAM && op_addr >= 0xD000 && op_addr < 0xDFFF && lc_bank == 2); } /* Figure out the addressing mode for the instruction */ int instruction_get_addressing_mode(int cpu, const char *arg) { int len; int shift = 0; /* no arg */ if (!arg || arg[0] == '\0') return ADDR_MODE_IMPLIED; len = strlen(arg); /* A */ if (len == 1) return ADDR_MODE_ACC; /* #$ff */ if (arg[0] == '#') return ADDR_MODE_IMMEDIATE; /* $ff */ if (len == 3 && arg[0] == '$') return ADDR_MODE_ZERO; /* <$90 or similar, unsure of page, let's use absolute */ if (arg[0] == '<' || arg[0] == '>') return ADDR_MODE_ABS; /* MAME symbol like RDRAM or 80STOREON :( */ if ((arg[0] >= 'A' && arg[0] <= 'Z') || (arg[0] >= 'a' && arg[0] <= 'z') || (arg[0] >= '0' && arg[0] <= '9')) return ADDR_MODE_ABS; if (strstr(arg, ",s") - arg + 2 == strlen(arg)) { return ADDR_MODE_ABSXY; /* FIXME that's not true */ } if (len >= 5) { indexed_modes: /* $ff, x */ if (arg[0] == '$' && arg[3] == ',') return ADDR_MODE_ZEROXY; /* ($ff), y */ if (arg[0] == '(' && arg[shift+4] == ')' && len > 7 && (arg[shift+7] == 'x' || arg[shift+7] == 'y')) return ADDR_MODE_ZEROXY; /* ($ff) */ if (arg[0] == '(' && arg[shift+4] == ')') return ADDR_MODE_ZEROIND; /* $ffff */ if (len == shift+5 && arg[0] == '$') return ADDR_MODE_ABS; /* $ffff, x */ if (len >= 6 && arg[0] == '$' && arg[shift+5] == ',') return ADDR_MODE_ABSXY; /* ($ffff, x) */ if (len >= shift+6 && arg[0] == '(' && arg[shift+6] == ',' && arg[shift+8] == 'x') return ADDR_MODE_INDX; /* ($ff, x) */ if (arg[0] == '(' && arg[shift+4] == ',' && arg[shift+6] == 'x') return ADDR_MODE_INDX; /* ($ffff), y */ if (len >= shift+7 && arg[0] == '(' && arg[shift+6] == ')') return ADDR_MODE_INDY; /* ($ff), y */ if (arg[0] == '(' && arg[shift+4] == ',' && arg[shift+7] == 'x') return ADDR_MODE_INDX; } if (len >= 7 && shift == 0) { shift = 2; goto indexed_modes; } fprintf(stderr, "Warning: unknown addressing mode for %s\n", arg); return ADDR_MODE_ABS; } extern int cur_65816_bank; /* Check instruction for memory banking change */ int analyze_instruction(int cpu, int op_addr, const char *instr, int param_addr, char *comment) { static int bit_count = 0; static int last_bit = 0; int parsed = 0, bank_switch = 0; if (cpu == CPU_65816) { if (cur_65816_bank == 0xFF) { read_from = ROM; } else { read_from = RAM; } return 0; } comment[0] = '\0'; if (!strcmp(instr, "bit") || !strncmp(instr,"ld", 2) || !strncmp(instr,"st", 2) || !strcmp(instr, "inc")) { if (is_instruction_write(instr)) { /* only one write required (?) */ bit_count++; last_bit = param_addr; } switch(param_addr) { case 0xC080: case 0xC084: read_from = RAM; write_to = NONE; lc_bank = 2; parsed = 1; bank_switch = 1; break; case 0xC081: case 0xC085: if (param_addr == last_bit) { bit_count++; } else { bit_count = 0; } read_from = ROM; write_to = (bit_count == 2) ? RAM : NONE; lc_bank = 2; parsed = 1; bank_switch = 1; break; case 0xC082: case 0xC086: read_from = ROM; write_to = NONE; lc_bank = 2; parsed = 1; bank_switch = 1; break; case 0xC083: case 0xC087: if (param_addr == last_bit) { bit_count++; } else { bit_count = 0; } read_from = RAM; write_to = (bit_count == 2) ? RAM : NONE; lc_bank = 2; parsed = 1; bank_switch = 1; break; case 0xC088: case 0xC08C: read_from = RAM; write_to = NONE; lc_bank = 1; parsed = 1; bank_switch = 1; break; case 0xC089: case 0xC08D: if (param_addr == last_bit) { bit_count++; } else { bit_count = 0; } read_from = ROM; write_to = (bit_count == 2) ? RAM : NONE; lc_bank = 1; parsed = 1; bank_switch = 1; break; case 0xC08A: case 0xC08E: read_from = ROM; write_to = NONE; lc_bank = 1; parsed = 1; bank_switch = 1; break; case 0xC08B: case 0xC08F: if (param_addr == last_bit) { bit_count++; } else { bit_count = 0; } read_from = RAM; write_to = (bit_count == 2) ? RAM : NONE; lc_bank = 1; parsed = 1; bank_switch = 1; break; default: break; } last_bit = param_addr; bit_count++; } else { bit_count = 0; last_bit = 0; } /* Update comment for the caller */ if (bank_switch) { snprintf(comment, BUF_SIZE, "BANK SWITCH: read from %s, write to %s, LC bank %d", mem_str[read_from], mem_str[write_to], lc_bank); } return parsed; } /* Returns 1 if the instruction is a "write" instruction */ int is_instruction_write(const char *instr) { int i; for (i = 0; write_instructions[i] != NULL; i++) { if (!strcmp(write_instructions[i], instr)) { return 1; } } return 0; } /* Alloc a stat struct */ static function_calls *function_calls_new(int addr) { function_calls *counter = malloc(sizeof(function_calls)); memset(counter, 0, sizeof(function_calls)); counter->addr = addr; return counter; } /* Stat struct getter. Will return the existing one, or * create and register a new one as needed. */ static function_calls *get_function_calls_for_addr(int addr) { function_calls *counter; dbg_slocdef *sloc_info = NULL; /* We want to register the first one away from * the array, so as to dump it first and once * in the * callgrind file */ if (addr == start_addr) { if (!root_call) root_call = function_calls_new(start_addr); return root_call; } counter = functions[addr]; /* Initialize the struct */ if (counter == NULL) { counter = function_calls_new(addr); functions[addr] = counter; sloc_info = sloc_get_for_addr(addr); if (sloc_info) { counter->file = sloc_get_filename(sloc_info); counter->line = sloc_get_line(sloc_info); } } return counter; } /* Get cycles number for instruction / addressing mode * TODO Hugely inefficient, add a instruction str <=> number mapping */ int get_cycles_for_instr(int cpu, const char *instr, int a_mode, int *extra_cost_if_taken) { for (int i = 0; instr_cost[i].instruction != NULL; i++) { if (!strcmp(instr, instr_cost[i].instruction)) { if (instr_cost[i].cost[a_mode] == 0) { fprintf(stderr, "Warning, addressing mode %d invalid for %s\n", a_mode, instr); return instr_cost[i].cost[ADDR_MODE_ABS]; } *extra_cost_if_taken = instr_cost[i].cost_if_taken; return instr_cost[i].cost[a_mode]; } } if (cpu == CPU_6502) { fprintf(stderr, "Error, cycle count not found for %s\n", instr); return -1; } else { /* FIXME add 65816 instructions */ return 0; } } /* Count current instruction */ static void count_instruction(const char *instr, int cycle_count) { tree_functions[tree_depth - 1]->cur_call_self_instruction_count++; tree_functions[tree_depth - 1]->cur_call_self_cycle_count += cycle_count; } /* Find a function in an array */ static function_calls *find_func_in_list(function_calls *func, function_calls **list, int list_len) { int i; for (i = 0; i < list_len; i++) { function_calls *cur = list[i]; if (cur->addr == func->addr) { return cur; } } return NULL; } /* Add a callee to a function */ static void add_callee(function_calls *caller, function_calls *callee) { function_calls *existing_callee = find_func_in_list(callee, caller->callees, caller->n_callees); if (!existing_callee) { /* First time caller calls callee. Init a new struct */ existing_callee = function_calls_new(callee->addr); existing_callee->func_symbol = callee->func_symbol; existing_callee->file = callee->file; existing_callee->line = callee->line; /* Register new callee in caller's struct */ caller->n_callees++; caller->callees = realloc(caller->callees, caller->n_callees * sizeof(function_calls *)); caller->callees[caller->n_callees - 1] = existing_callee; } /* Increment the call count */ existing_callee->call_count++; // if (verbose) // fprintf(stderr, "; updated callee %04X %s count %ld to parent addr %04X, func %s\n", // existing_callee->addr, symbol_get_name(existing_callee->func_symbol), // existing_callee->call_count, // caller->addr, symbol_get_name(caller->func_symbol)); } static void tabulate_stack(void) { fprintf(stderr, ";"); for (int i = 0; i < tree_depth; i++) fprintf(stderr, " "); } /* Transfer the instruction count to the top of the tree */ static void update_caller_incl_cost(int instr_count, int cycle_count) { int i = tree_depth; for (i = tree_depth; i > 0; i--) { function_calls *caller = tree_functions[i - 1]; function_calls *ref_callee = find_func_in_list(tree_functions[i], caller->callees, caller->n_callees); // if (verbose) // fprintf(stderr, "; adding %d incl count to %s called by %s\n", // count, symbol_get_name(callee->func_symbol), symbol_get_name(caller->func_symbol)); ref_callee->incl_instruction_count += instr_count; ref_callee->incl_cycle_count += cycle_count; } /* and the root */ tree_functions[0]->incl_instruction_count += instr_count; tree_functions[0]->incl_cycle_count += cycle_count; } /* Register a new call in the tree */ static void start_call_info(int cpu, int addr, int mem, int lc, int line_num) { function_calls *my_info; if (tree_depth < 0) { fprintf(stderr, "Error, tree depth is negative (%d)\n", tree_depth); exit(1); } /* Get the stats structure */ my_info = get_function_calls_for_addr(addr); /* FIXME shouldn't the stats structs be indexed by addr / mem / lc... */ my_info->func_symbol = symbol_get_by_addr(cpu, addr, mem, lc); if (my_info->func_symbol == NULL) { fprintf(stderr, "No symbol found for 0x%04X, %d, %d\n", addr, mem, lc); exit(1); } /* Log */ if (verbose) { tabulate_stack(); fprintf(stderr, "depth %d, $%04X (%s/LC%d), %s calls %s (asm line %d)\n", tree_depth, addr, mem == RAM ? "RAM":"ROM", lc, tree_depth > 0 ? symbol_get_name(tree_functions[tree_depth - 1]->func_symbol) : "*start*", symbol_get_name(my_info->func_symbol), line_num); } /* Register in the call tree */ tree_functions[tree_depth] = my_info; /* Reset current self instruction count for this new call */ tree_functions[tree_depth]->cur_call_self_instruction_count = 0; tree_functions[tree_depth]->cur_call_self_cycle_count = 0; /* add myself to parent's callees */ if (tree_depth > 0) { function_calls *parent_info = tree_functions[tree_depth - 1]; add_callee(parent_info, my_info); } /* increment depth */ tree_depth++; } static void end_call_info(int op_addr, int line_num, const char *from) { function_calls *my_info; if (tree_depth == 0) { fprintf(stderr, "Can not go up call tree from depth 0\n"); exit(1); } /* Go back up */ tree_depth--; /* Get stats */ my_info = tree_functions[tree_depth]; /* Log */ if (verbose) { tabulate_stack(); fprintf(stderr, "depth %d, %s returning (%s, asm line %d)\n", tree_depth, symbol_get_name(my_info->func_symbol), from, line_num); } /* We done ? */ if (tree_depth > 0) { /* update self counts */ tree_functions[tree_depth]->self_instruction_count += tree_functions[tree_depth]->cur_call_self_instruction_count; tree_functions[tree_depth]->self_cycle_count += tree_functions[tree_depth]->cur_call_self_cycle_count; /* push it up to callers */ update_caller_incl_cost( tree_functions[tree_depth]->cur_call_self_instruction_count, tree_functions[tree_depth]->cur_call_self_cycle_count); } } int update_call_counters(int cpu, int op_addr, const char *instr, int param_addr, int cycle_count, int line_num) { int dest = RAM, lc = 0; if (cpu == CPU_6502) { /* Set memory and LC bank according to the address */ if (param_addr < 0xD000 || param_addr > 0xDFFF) { dest = RAM; lc = 1; } else { dest = is_instruction_write(instr) ? write_to : read_from; lc = lc_bank; } } /* Count the instruction */ count_instruction(instr, cycle_count); /* Are we entering an IRQ handler ? */ if (op_addr == ROM_IRQ_ADDR[cpu] || op_addr == PRODOS_IRQ_ADDR || op_addr == handle_rom_irq_addr || op_addr == handle_ram_irq_addr) { if (verbose) fprintf(stderr, "; interrupt at depth %d\n", tree_depth); if (in_interrupt == 0) { /* Record existing depth */ tree_depth_before_intr[in_interrupt] = tree_depth; /* Update stats structs pointer */ tree_functions = irq_tree; /* Reset tree depth */ tree_depth = 1; } /* Increment the IRQ stack count */ in_interrupt++; /* And record entering */ start_call_info(cpu, op_addr, RAM, lc, line_num); } else if (!strcmp(instr, "rti")) { /* Are we exiting an IRQ handler ? */ if (in_interrupt) { if (verbose) fprintf(stderr, "; rti from interrupt at depth %d\n", tree_depth); /* Record end of call */ end_call_info(op_addr, line_num, "irq"); /* Decrease IRQ stack */ in_interrupt--; if (!in_interrupt) { /* Reset tree to standard runtime */ tree_functions = func_tree; tree_depth = tree_depth_before_intr[in_interrupt]; /* Remember if we just rti'd out of IRQ, as if * we go back to a jsr that was recorded but not * executed, we don't want to re-register it. If * so we'll skip the next instruction. */ just_out_of_irq = 1; } } else if (op_addr == PRODOS_MLI_RETURN_ADDR) { /* Hack: ProDOS MLI calls return with an rti, * handle it as an rts, and go back up to caller's depth. */ if (mli_call_depth == -1) { fprintf(stderr, "Untracked end of MLI call at depth %d\n", tree_depth); exit(1); } else { if (verbose) { tabulate_stack(); fprintf(stderr, "(End of MLI call at depth %d)\n", tree_depth); } /* don't register an rts if we just went out of irq, * we registered it before, same as jsr's */ if (!just_out_of_irq) { while (tree_depth > mli_call_depth) end_call_info(op_addr, line_num, "mli rts"); } if (verbose) { tabulate_stack(); fprintf(stderr, "(Returned from MLI call at depth %d)\n", tree_depth); } /* Unset flag */ just_out_of_irq = 0; /* Unset MLI call flag */ mli_call_depth = -1; } } /* cc65 runtime jmp's into _main, record it as if it * was a jsr */ } else if (param_addr == _main_addr && !strcmp(instr, "jmp")) { goto jsr; /* Are we entering a function ? */ } else if (!strcmp(instr, "jsr") || !strcmp(instr, "jsl")) { jsr: /* don't register a jsr if we just went out of * irq, we registered it right before entering IRQ */ if (!just_out_of_irq) { start_call_info(cpu, param_addr, dest, lc, line_num); /* Ugly hack (both because of MAME's symbol and because of the hardcoding). * ProDOS MLI uses rti to return faster to where it was called from. */ if (!strncmp(symbol_get_name(tree_functions[tree_depth - 1]->func_symbol), "RAM.LC1.ProDOS 8: ", 18)) { if (mli_call_depth != -1) { fprintf(stderr, "Error: unhandled recursive MLI call at line %d\n", line_num); exit(1); } mli_call_depth = tree_depth - 1; if (verbose) { tabulate_stack(); fprintf(stderr, "Recording MLI call at depth %d\n", mli_call_depth); } } } /* Unset flag */ just_out_of_irq = 0; /* Are we returning from a function? */ } else if ((!strcmp(instr, "rts") || !strcmp(instr, "rtl")) && tree_depth > 0) { /* don't register an rts if we just went out of irq, * we registered it before, same as jsr's */ if (!just_out_of_irq) end_call_info(op_addr, line_num, instr); /* Unset flag */ just_out_of_irq = 0; } else { /* At least one instruction since getting * out of IRQ, unset flag */ just_out_of_irq = 0; } return 0; } /* Dump data in Callgrind format: callee information * this will be included for all functions. * Ref: https://valgrind.org/docs/manual/cl-format.html */ static void dump_callee(function_calls *cur) { dbg_symbol *sym = cur->func_symbol; /* Dump callee information (call count and * inclusive instruction count) */ printf("cfi=%s%s\n" "cfn=%s\n" "calls=%ld\n" "%d %lu %lu\n", cur->file ? cur->file : "unknown.", cur->file ? "": symbol_get_name(sym), symbol_get_name(sym), cur->call_count, cur->line, cur->incl_instruction_count, cur->incl_cycle_count ); } /* Dump data in Callgrind format: function information * this will be included for all functions. * Ref: https://valgrind.org/docs/manual/cl-format.html */ static void dump_function(function_calls *cur) { dbg_symbol *sym = cur->func_symbol; int i; /* Dump the function definition and self * instruction count */ printf("fl=%s%s\n" "fn=%s\n" "%d %lu %lu\n", cur->file ? cur->file : "unknown.", cur->file ? "": symbol_get_name(sym), symbol_get_name(sym), cur->line, cur->self_instruction_count, cur->self_cycle_count ); /* Dump information for every function it calls */ for (i = 0; i < cur->n_callees; i++) { dump_callee(cur->callees[i]); } /* Separate for clarity. */ printf("\n"); } /* Everything is done, dump the callgrind * file. */ void finalize_call_counters(void) { int i; /* finish all calls to count their self count */ while (tree_depth > 0) end_call_info(0x0000, 0, "end of program"); /* File header */ printf("# callgrind format\n" "events: Instructions Cycles\n\n"); /* Dump start function first */ dump_function(root_call); /* And then all the rest. */ for (i = 0; i < STORAGE_SIZE; i++) { if (functions[i]) { dump_function(functions[i]); } } } void start_tracing(int cpu) { /* make ourselves a root in the IRQ call tree */ tree_functions = irq_tree; start_call_info(cpu, start_addr, RAM, 1, 0); /* Hack - reset depth for the runtime root */ tree_depth = 0; /* make ourselves a root in the runtime call tree */ tree_functions = func_tree; start_call_info(cpu, start_addr, RAM, 1, 0); } /* Setup structures and data */ void allocate_trace_counters(void) { if (functions != NULL) { /* Already done */ return; } functions = malloc(sizeof(function_calls *) * 2 * STORAGE_SIZE); func_tree = malloc(sizeof(function_calls *) * 2 * STORAGE_SIZE); irq_tree = malloc(sizeof(function_calls *) * 2 * STORAGE_SIZE); memset(functions, 0, sizeof(function_calls *) * 2 * STORAGE_SIZE); memset(func_tree, 0, sizeof(function_calls *) * 2 * STORAGE_SIZE); memset(irq_tree, 0, sizeof(function_calls *) * 2 * STORAGE_SIZE); /* Let the depth where it is, so every call will * be attached to the start_addr function */ /* register _main's address for later - crt0 will * jmp to it and we'll still want to record it. */ _main_addr = symbol_get_addr(symbol_get_by_name("_main")); handle_rom_irq_addr = symbol_get_addr(symbol_get_by_name("handle_rom_irq")); handle_ram_irq_addr = symbol_get_addr(symbol_get_by_name("handle_ram_irq")); }
/* eslint-disable no-restricted-imports */ import { createStitches } from "@stitches/core"; import type * as Stitches from "@stitches/core"; export type { VariantProps, PropertyValue, ScaleValue } from "@stitches/core"; import { colors } from "./colors"; import { space, spaceAliases, SpaceToken } from "./space"; export { withStyle } from "./withStyle"; export type { CSSProps, PolymorphicProps, BasicStyledComponentProps, StyledComponentProps, StyledComponentPropsWithPolymorphism, } from "./withStyle"; export const { css, globalCss, keyframes, theme, createTheme, getCssText, config, } = createStitches({ prefix: "cards", utils: { px: (value: SpaceToken) => ({ paddingLeft: value, paddingRight: value, }), py: (value: SpaceToken) => ({ paddingTop: value, paddingBottom: value, }), mx: (value: SpaceToken | "auto") => ({ marginLeft: value, marginRight: value, }), my: (value: SpaceToken | "auto") => ({ marginTop: value, marginBottom: value, }), gradientRight: (value: string) => ({ backgroundImage: `linear-gradient(to right, ${value})`, }), gradientBottom: (value: string) => ({ backgroundImage: `linear-gradient(to bottom, ${value})`, }), gradientBottomRight: (value: string) => ({ backgroundImage: `linear-gradient(to bottom right, ${value})`, }), backgroundSoftFadeEdges: (value: string) => ({ WebkitMaskImage: `linear-gradient(to right, transparent 0%, black ${value}, black calc(100% - ${value}), transparent 100%)`, }), }, theme: { // Typography fonts: { serif: `EB Garamond, Newsreader, ui-serif, Georgia, Cambria, "Times New Roman", Times, serif`, mono: `ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`, }, fontSizes: { 1: "16px", 2: "20px", 3: "24px", 4: "30px", 5: "36px", 6: "48px", 7: "64px", 8: "80px", 9: "96px", }, lineHeights: { single: "1", tight: "1.2", normal: "1.3", relaxed: "1.5", double: "2", }, fontWeights: { normal: 400, medium: 500, semibold: 600, }, letterSpacings: { tighter: "-0.02em", tight: "-0.01em", normal: "0em", wide: "0.025em", wider: "0.05em", widest: "0.1em", }, // Borders radii: { none: "0px", xs: "2px", sm: "4px", md: "6px", lg: "12px", xl: "16px", round: "50%", pill: "9999px", }, borderWidths: { 0: "0px", 1: "1px", 2: "2px", 4: "4px", 8: "8px", }, borderStyles: { none: "none", solid: "solid", dashed: "dashed", dotted: "dotted", hidden: "hidden", }, // Color colors: { // Semantic tokens primary1: "#FFF9F0", primary2: "#FFEED4", primary3: "#FADAA8", primary4: "#F4C47B", primary5: "#F99D10", primary6: "#C17410", primary7: "#784511", primary8: "#50280B", primary9: "#371B06", primary10: "#120902", primary11: "#050201", gradientPrimary: "linear-gradient(180deg, #FADAA8 21.28%, #F99D10 92.02%)", // Alias tokens minContrast: colors.mono.white, maxContrast: colors.mono.black, // Backgrounds bgPrimary: "$primary10", bgSecondary: "$primary9", bgTertiary: "$primary8", // Text contentMuted: "$primary6", contentNormal: "$primary3", contentStrong: "$primary1", // Border borderMuted: "$neutral9", borderNormal: "$neutral8", borderStrong: "$neutral6", }, // Effects shadows: { none: "none", sm: "0px 0px 8px rgba(193, 116, 16, 0.6), 0px 0px 4px rgba(250, 218, 168, 0.3)", md: "0px 0px 15px rgba(193, 116, 16, 0.7), 0px 0px 3px 1px rgba(250, 218, 168, 0.39)", lg: "0px 0px 24px rgba(193, 116, 16, 0.8), 0px 0px 4px 1px rgba(250, 218, 168, 0.59)", }, // Transitions & Animations transitions: { dur: "150ms", dur75: "75ms", dur100: "100ms", dur150: "150ms", dur200: "200ms", dur300: "300ms", dur500: "500ms", dur700: "700ms", dur1000: "1000ms", fn: "cubic-bezier(0.4, 0, 0.2, 1)", fnLinear: "linear", fnIn: "cubic-bezier(0.4, 0, 1, 1)", fnOut: "cubic-bezier(0, 0, 0.2, 1)", fnInOut: "cubic-bezier(0.4, 0, 0.2, 1)", }, // Spacing & Sizing space: { 0: space[0], 1: space[1], 2: space[2], 4: space[4], 6: space[6], 8: space[8], 10: space[10], 12: space[12], 14: space[14], 16: space[16], 20: space[20], 24: space[24], 28: space[28], 32: space[32], 36: space[36], 40: space[40], 44: space[44], 48: space[48], 56: space[56], 64: space[64], 80: space[80], 96: space[96], 112: space[112], 128: space[128], 144: space[144], 160: space[160], 176: space[176], 192: space[192], 208: space[208], 224: space[224], 240: space[240], 256: space[256], 288: space[288], 320: space[320], 384: space[384], // Alias Tokens gutter: spaceAliases.gutter, sm1: spaceAliases.sm1, sm2: spaceAliases.sm2, sm3: spaceAliases.sm3, sm4: spaceAliases.sm4, sm5: spaceAliases.sm5, md1: spaceAliases.md1, md2: spaceAliases.md2, md3: spaceAliases.md3, md4: spaceAliases.md4, md5: spaceAliases.md5, lg1: spaceAliases.lg1, lg2: spaceAliases.lg2, lg3: spaceAliases.lg3, lg4: spaceAliases.lg4, lg5: spaceAliases.lg5, }, // Layout zIndices: { auto: "auto", 0: "0", 10: "10", 20: "20", 30: "30", 40: "40", 50: "50", }, }, }); const _css = css(); /** * A utility for creating a one-off css class name. Useful for inline styling but use *sparingly*. * @param c A CSS object. * @returns A CSS class object. * @example <div className={inlineCss({ color: "pink" })} /> */ export const inlineCss = (c: CSS): string => _css({ css: c }); /** * Use for typing a CSS object which includes our theme and utils. * @example const styles: CSS = { color: "$primary" } */ export type CSS = Stitches.CSS<typeof config>; type ThemeColors = typeof theme.colors; /** * Utility to modify a theme value to have an alpha channel. A bit hacky. * @param colorToken The theme color to change the alpha channel of. * @param alphaValue The alpha channel value (should be between 0 and 1). * @returns A new value (not variable) with the alpha channel applied * @example * alpha("primary9", .5) // "hsl(245 50% 75% / 0.5)" */ export const alpha = ( colorToken: ThemeColors[keyof ThemeColors], alphaValue: number ) => colorToken.value.replace(")", ` / ${alphaValue})`); /** Utility for making a rule !important. */ export const important = (rule: any) => `${rule} !important`;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using OfficeMenStore.Application.Interfaces; using OfficeMenStore.Application.Models.User; namespace OfficeMenStore.Api.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly IUserService _userService; public UsersController(IUserService userService) { _userService = userService; } private string setImageName(string currentName) { return String.Format("{0}://{1}{2}/images/Users/{3}", Request.Scheme, Request.Host, Request.PathBase, currentName); } [HttpPost("Login")] [AllowAnonymous] public async Task<IActionResult> LoginAsync([FromBody] LoginRequest request) { var result = await _userService.LoginAsync(request); return Ok(result); } [HttpGet("{id}")] public async Task<IActionResult> GetUserById([FromRoute] Guid id) { var result = await _userService.GetUserByIdAsync(id); if (result.StatusCode == 200) { result.Data.Avatar = setImageName(result.Data.Avatar); return Ok(result.Data); } return BadRequest(result.Message); } [HttpPost("GetAllUser")] [AllowAnonymous] public async Task<IActionResult> GetAllUserAsync([FromBody] GetAllUserRequest requestDto) { var result = await _userService.GetAllUserAsync(requestDto); if (result.StatusCode == 200) { result.Data.ForEach(s => s.Avatar = setImageName(s.Avatar)); return Ok(result); } return BadRequest(result); } [HttpPost("Register")] [AllowAnonymous] public async Task<IActionResult> RegisterAsync([FromBody] RegisterRequest request) { var result = await _userService.RegisterAsync(request); return Ok(result); } } }
import React, { useState, useEffect } from 'react'; import { Calendar, momentLocalizer } from 'react-big-calendar'; import moment from 'moment'; import 'react-big-calendar/lib/css/react-big-calendar.css'; const localizer = momentLocalizer(moment); const Cal_no_input = () => { const [events, setEvents] = useState([]); const [selectedEvent, setSelectedEvent] = useState(null); useEffect(() => { const storedEvents = JSON.parse(localStorage.getItem('events')) || []; setEvents(storedEvents); }, []); const handleSelect = ({ start, end }) => { const newEvent = { title: '', description: '', coordinator: '', lab: '', feedbackLink: '', registrationLink: '', start, end, }; const updatedEvents = [...events, newEvent]; setEvents(updatedEvents); localStorage.setItem('events', JSON.stringify(updatedEvents)); }; const handleEventSelect = (event) => { setSelectedEvent(event); }; const handleClose = () => { setSelectedEvent(null); }; return ( <div> <div style={{ height: 500 }}> <Calendar localizer={localizer} events={events} startAccessor="start" endAccessor="end" style={{ margin: '50px' }} onSelectSlot={handleSelect} onSelectEvent={handleEventSelect} /> </div> {selectedEvent && ( <div style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: 'white', padding: '20px', zIndex: 9999, boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.5)', }} > <h2>{selectedEvent.title}</h2> <p><strong>Description:</strong> {selectedEvent.description}</p> <p><strong>Coordinator:</strong> {selectedEvent.coordinator}</p> <p><strong>Lab:</strong> {selectedEvent.lab}</p> <p><strong>Feedback Link:</strong> <a href={selectedEvent.feedbackLink} target="_blank" rel="noopener noreferrer">{selectedEvent.feedbackLink}</a></p> <p><strong>Registration Link:</strong> <a href={selectedEvent.registrationLink} target="_blank" rel="noopener noreferrer">{selectedEvent.registrationLink}</a></p> <p><strong>Start:</strong> {moment(selectedEvent.start).format('YYYY-MM-DD HH:mm')}</p> <p><strong>End:</strong> {moment(selectedEvent.end).format('YYYY-MM-DD HH:mm')}</p> <button onClick={handleClose}>Close</button> </div> )} {selectedEvent && ( <div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.5)', zIndex: 9998, }} onClick={handleClose} /> )} </div> ); }; export default Cal_no_input;
### Containerized Installation for Inference on Linux GPU Servers 1. Ensure docker installed and ready (requires sudo), can skip if system is already capable of running nvidia containers. Example here is for Ubuntu, see [NVIDIA Containers](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker) for more examples. ```bash distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ && curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \ && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | \ sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \ sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit-base sudo apt install nvidia-container-runtime sudo nvidia-ctk runtime configure --runtime=docker sudo systemctl restart docker ``` 2. Build the container image: ```bash docker build -t h2ogpt . ``` 3. Run the container (you can also use `finetune.py` and all of its parameters as shown above for training): For the fine-tuned h2oGPT with 20 billion parameters: ```bash docker run --runtime=nvidia --shm-size=64g -p 7860:7860 \ -v ${HOME}/.cache:/root/.cache --rm h2ogpt -it generate.py \ --base_model=h2oai/h2ogpt-oasst1-512-20b ``` if have a private HF token, can instead run: ```bash docker run --runtime=nvidia --shm-size=64g --entrypoint=bash -p 7860:7860 \ -e HUGGINGFACE_API_TOKEN=<HUGGINGFACE_API_TOKEN> \ -v ${HOME}/.cache:/root/.cache --rm h2ogpt -it \ -c 'huggingface-cli login --token $HUGGINGFACE_API_TOKEN && python3.10 generate.py --base_model=h2oai/h2ogpt-oasst1-512-20b --use_auth_token=True' ``` For your own fine-tuned model starting from the gpt-neox-20b foundation model for example: ```bash docker run --runtime=nvidia --shm-size=64g -p 7860:7860 \ -v ${HOME}/.cache:/root/.cache --rm h2ogpt -it generate.py \ --base_model=EleutherAI/gpt-neox-20b \ --lora_weights=h2ogpt_lora_weights --prompt_type=human_bot ``` 4. Open `https://localhost:7860` in the browser ### Run h2oGPT using Docker __Optional: Running with a custom entrypoint__ To run with a custom entrypoint, modify the local [`run-gpt.sh`](https://github.com/h2oai/h2ogpt/blob/76947c009a82d7a4a871548e68a60ce0a28b75d1/run-gpt.sh) & mount it. ```bash docker run \ --runtime=nvidia --shm-size=64g \ -e HF_MODEL=h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-7b \ -p 8888:8888 -p 7860:7860 \ --rm --init \ -v `pwd`/h2ogpt_env:/h2ogpt_env \ -v `pwd`/run-gpt.sh:/run-gpt.sh \ gcr.io/vorvan/h2oai/h2ogpt-runtime:61d6aea6fff3b1190aa42eee7fa10d6c ``` ### Docker Compose Setup & Inference 1. (optional) Change desired model and weights under `environment` in the `docker-compose.yml` 2. Build and run the container ```bash docker-compose up -d --build ``` 3. Open `https://localhost:7860` in the browser 4. See logs: ```bash docker-compose logs -f ``` 5. Clean everything up: ```bash docker-compose down --volumes --rmi all ```
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: 'contacts', pathMatch: 'full' }, { path: 'contacts', loadChildren: './pages/contact-list/contact-list.module#ContactListPageModule' }, { path: 'contacts/:id', loadChildren: './pages/contact-detail/contact-detail.module#ContactDetailPageModule' }, { path: 'albums/:id', loadChildren: './pages/contact-photos/contact-photos.module#ContactPhotosPageModule' }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule { }
package T2.service; import T2.dto.UserAndOrderDto; import T2.dto.UserDto; import T2.entities.Order; import T2.entities.User; import T2.exception.AlreadyExistsException; import T2.exception.IncorrectDataException; import T2.exception.NotFoundUserException; import T2.mapper.OrderMapper; import T2.mapper.UserMapper; import T2.repository.OrderRepository; import T2.repository.UserRepository; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service @Transactional @RequiredArgsConstructor public class UserService implements UserDetails, UserSummary, EditUsers { UserRepository userRepository; OrderRepository orderRepository; UserMapper userMapper; OrderMapper orderMapper; @Autowired public UserService(UserRepository userRepository, OrderRepository orderRepository, UserMapper userMapper, OrderMapper orderMapper) { this.userRepository = userRepository; this.orderRepository = orderRepository; this.userMapper = userMapper; this.orderMapper = orderMapper; } @Override public void createUser(UserDto userDto) { validInput(userDto); try { getUser(userDto.getName()); throw new AlreadyExistsException("User already exists: " + userDto.getName()); } catch (NotFoundUserException e) { User user = new User(); user.setName(userDto.getName()); user.setEmail(userDto.getEmail()); userRepository.save(user); } } @Override public void updateUser(UserDto userDto) { validInput(userDto); User user = getUser(userDto.getName()); user.setEmail(userDto.getEmail()); userRepository.save(user); } @Override public void deleteUser(String name) { getUser(name); userRepository.deleteByName(name); } @Override public UserAndOrderDto getUserAndOrders(String name) { User user = getUser(name); UserAndOrderDto userAndOrderDto = new UserAndOrderDto(); userAndOrderDto.setUser(userMapper.userDto(user)); List<Order> orders = orderRepository.findByUserName(user.getName()); if (!orders.isEmpty()) { orders.forEach(order -> userAndOrderDto.addOrder(orderMapper.orderDto(order))); } return userAndOrderDto; } @Override public ArrayList<UserDto> getAllUsersSummary() { ArrayList<UserDto> result = new ArrayList<>(); Iterable<User> users = userRepository.findAll(); users.forEach(user -> result.add(userMapper.userDto(user))); return result; } @Override public UserDto getUserSummary(String name) { User user = getUser(name); return userMapper.userDto(user); } @Override public User getUserSummaryJsonView(String name) { return getUser(name); } private User getUser(String name) { Optional<User> user = userRepository.findByName(name); if (user.isEmpty()) { throw new NotFoundUserException("User " + name + " not found"); } return user.get(); } private void validInput(UserDto userDto) { String email = userDto.getEmail(); Pattern pattern = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"); Matcher mat = pattern.matcher(email); if (userDto.getName().isEmpty() || !mat.matches()) { throw new IncorrectDataException("Not a valid email: " + email); } else if (userDto.getName().isEmpty() || userDto.getName() == "") { throw new IncorrectDataException("Not a valid name: " + userDto.getName()); } } }
print(".vav | BEGIN") VIDEO_FILE_TO_CAST = "E:\\temp\\Movies\\Sherlock.Holmes.A.Game.Of.Shadows.2011.1080P.Brrip.X264.Yify-1.m4v" print(".") print("Publishing content:", VIDEO_FILE_TO_CAST) print(".") import asyncio import json import websockets from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, RTCConfiguration, RTCIceCandidate from aiortc.contrib.media import MediaPlayer import logging logging.basicConfig(level=logging.INFO) pcs = set() class VideoFrameTrack(VideoStreamTrack): frame_count=-1 def __init__(self, video_path): print(".vav | VideoFrameTrack::__init__ : video_path: ", video_path) super().__init__() self.player = MediaPlayer(video_path) async def recv(self): frame = await self.player.video.recv() #logic to print indications for the first few frames global frame_count self.frame_count +=1 if(self.frame_count < 10 ) : # print only few frames print(".") return frame #logic to include custom stun server(s) from aiortc import RTCIceServer # Define your STUN server URL configuration = RTCConfiguration(iceServers=[ RTCIceServer("stun:localhost:3478") # Assuming your STUN server is on localhost ]) async def offer_handler(websocket, path): print(".vav | offer_handler() begin.") async for message in websocket: params = json.loads(message) print(".vav | offer_handler() message in websocket:", params) print(".") print(".") if params['type'] == 'offer': print("**********************************************************************************") offer = RTCSessionDescription(sdp=params['sdp'], type=params['type']) pc = RTCPeerConnection(configuration) pcs.add(pc) @pc.on("icecandidate") async def on_icecandidate(candidate): print(".vav | offer_handler()::on_icecandidate") if candidate: await websocket.send(json.dumps({ "type": "candidate", "candidate": candidate.candidate, "sdpMid": candidate.sdpMid, "sdpMLineIndex": candidate.sdpMLineIndex })) video_track = VideoFrameTrack(VIDEO_FILE_TO_CAST) pc.addTrack(video_track) await pc.setRemoteDescription(offer) answer = await pc.createAnswer() await pc.setLocalDescription(answer) await websocket.send(json.dumps({ "sdp": pc.localDescription.sdp, "type": pc.localDescription.type })) elif params['type'] == 'candidate': print("-----------------------------------------------------------------------------------") candidate = RTCIceCandidate( sdp=params['candidate'], sdpMid=params['sdpMid'], sdpMLineIndex=params['sdpMLineIndex'] ) if 'pc' in locals(): await pc.addIceCandidate(candidate) else: logging.warning("Attempted to add ICE candidate without an active peer connection.") print(".vav | offer_handler() end.") print(".vav | before websockets.serve() or creation of the socket.") start_server = websockets.serve(offer_handler, "localhost", 8080) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() print(".vav | END")
import ClayButton from '@clayui/button'; import ClayIcon from '@clayui/icon'; import getCN from 'classnames'; import Input from './Input'; import Loading from 'shared/components/Loading'; import Overlay from './Overlay'; import Promise from 'metal-promise'; import React, {useEffect, useImperativeHandle, useRef, useState} from 'react'; import {ARROW_DOWN, ARROW_UP, ENTER} from '../util/key-constants'; import {DocumentNode} from 'graphql'; import {identity, noop} from 'lodash'; import {useDebounce} from 'shared/hooks'; import {useQuery} from '@apollo/react-hooks'; import {useRequest} from 'shared/hooks'; const DEBOUNCE_DELAY = 250; const SELECT_KEYS = [ARROW_DOWN, ARROW_UP, ENTER]; type GraphqlQuery = { mapResultsToProps: (data: any) => TMappedData; variables: object; query: DocumentNode; }; type TMappedData = { data: string[]; total: number; }; interface IItemProps extends React.HTMLAttributes<HTMLLIElement> { active?: boolean; disabled?: boolean; item: any; itemRenderer: (item: any) => React.ReactNode; onSelect: (item: any) => void; } export const Item: React.FC<IItemProps> = ({ active, className, disabled, item, itemRenderer, onSelect }) => ( <li className={className}> <ClayButton className={getCN('button-root dropdown-item text-truncate', { active })} disabled={disabled} displayType='unstyled' onClick={() => onSelect(item)} > {itemRenderer(item)} </ClayButton> </li> ); interface IBaseSelectProps extends React.HTMLAttributes<HTMLInputElement> { alwaysFetchOnFocus?: boolean; className?: string; containerClass?: string; dataSourceFn?: (value: string | number) => Promise<any>; disabled?: boolean; emptyInputOnInactive?: boolean; inputName?: string; focusOnInit?: boolean; forwardedRef?: React.Ref<any>; graphqlQuery?: GraphqlQuery; id?: string; inputSize?: string; inputValue?: string | React.ReactText; inset?: boolean; itemRenderer?: (item: any) => React.ReactNode; menuTitle?: string; onFocus?: () => void; onInputValueChange?: (value: string | number) => void; onSelect?: (item: any) => void; selectedItem?: any; } const BaseSelect: React.FC<IBaseSelectProps> = ({ alwaysFetchOnFocus = false, className, containerClass, dataSourceFn, disabled = false, emptyInputOnInactive = false, focusOnInit = false, forwardedRef, graphqlQuery, id, inputName, inputSize, inputValue = '', inset = false, itemRenderer, menuTitle, onBlur, onFocus, onInputValueChange = noop, onSelect = noop, placeholder = '', selectedItem, ...otherProps }) => { useImperativeHandle(forwardedRef, () => ({ focus: () => { handleFocus(); _inputRef.current.focus(); } })); const [active, setActive] = useState<boolean>(false); const [focusIndex, setFocusIndex] = useState<number>(0); const _inputRef = useRef<any>(); let response; if (graphqlQuery) { const { mapResultsToProps = value => value, query, variables } = graphqlQuery; const debouncedInputValue = useDebounce(inputValue, DEBOUNCE_DELAY); response = useQuery(query, { fetchPolicy: 'network-only', skip: !active, variables: { ...variables, keywords: debouncedInputValue } }); response = { ...response, ...mapResultsToProps(response.data) }; } else { response = useRequest({ dataSourceFn: ({value}) => dataSourceFn(value), debounceDelay: DEBOUNCE_DELAY, initialState: { data: [], error: false, loading: false }, resetStateIfSkipingRequest: true, skipRequest: !active, variables: {value: inputValue} }); } const {data: items = [], loading, refetch} = response; useEffect(() => { if (focusOnInit) { _inputRef.current.focus(); } }, []); const handleBlur = (event: React.FocusEvent<HTMLInputElement>) => { onBlur && onBlur(event); }; const handleFocus = () => { if (!active) { if (!items?.length || alwaysFetchOnFocus) { refetch(); } onFocus && onFocus(); setActive(true); handleSetFocusIndex(0); } }; const handleKeyDown = (event: React.KeyboardEvent) => { const {keyCode} = event; if (!SELECT_KEYS.includes(keyCode)) { return; } event.preventDefault(); switch (keyCode) { case ARROW_DOWN: handleSetFocusIndex(focusIndex + 1); break; case ARROW_UP: handleSetFocusIndex(focusIndex - 1); break; case ENTER: handleSelect(items[focusIndex]); break; default: break; } }; const handleOutsideClick = () => { _inputRef.current.blur(); setActive(false); }; const handleSelect = item => { handleOutsideClick(); onSelect(item); }; const handleSetFocusIndex = (val: number): void => { const count = items?.length; setFocusIndex((val + count) % count || 0); }; return ( <Overlay {...otherProps} active={active} alignment='bottomLeft' containerClass={getCN('base-select-container', containerClass)} onOutsideClick={handleOutsideClick} usePortal={false} > <Input.Group className={getCN( 'base-select-input-root select-input-root', className, {inset} )} onClick={disabled ? null : handleFocus} > <Input.GroupItem> <Input autoComplete='off' disabled={disabled} id={id} inset='after' name={inputName} onBlur={handleBlur} onChange={( event: React.ChangeEvent<HTMLInputElement> ) => { onInputValueChange(event.target.value); }} onFocus={handleFocus} onKeyDown={handleKeyDown} placeholder={placeholder} ref={_inputRef} size={inputSize} value={ active || !emptyInputOnInactive ? inputValue : '' } /> <Input.Inset position='after'> {loading ? ( <Loading /> ) : ( <ClayIcon className='icon-root' symbol='caret-bottom' /> )} </Input.Inset> </Input.GroupItem> {!active && selectedItem && itemRenderer && ( <div className='selected-item-container'> {itemRenderer(selectedItem)} </div> )} </Input.Group> {!!items?.length && ( <div className='dropdown-root'> <ul className='base-select-menu dropdown-menu show'> {!!menuTitle && ( <li className='dropdown-header'>{menuTitle}</li> )} {items.map((item, i) => ( <Item active={i === focusIndex} disabled={loading} item={item} itemRenderer={itemRenderer || identity} key={i} onSelect={handleSelect} /> ))} </ul> </div> )} </Overlay> ); }; export default React.forwardRef<HTMLInputElement, IBaseSelectProps>( (props, ref) => <BaseSelect {...props} forwardedRef={ref} /> );
import { useState, useEffect } from "react" export default function TextForm(props, { pageTitle = "TextHub - word counter | character counter | lowercase to uppercase | text read aloud" }) { const [text, setText] = useState(""); const [readText, setReadText] = useState("Read Aloud"); useEffect(() => { document.title = pageTitle; }, [pageTitle]); const handleUpClick = () => { setText(text.toUpperCase()); props.showAlert("Converted to UpperCase", "success"); } const handleLoClick = () => { setText(text.toLowerCase()); props.showAlert("Converted to LowerCase", "success"); } const handleOnChange = (e) => { setText(e.target.value); } const handleClearClick = (e) => { setText(""); props.showAlert("Text successfully cleared", "success"); } const handleRemoveSpace = () => { let newText = text.split(/[ ]+/); setText(newText.join(" ")); props.showAlert("Extra spaces successfully deleted", "success"); } const handleCapitalizeClick = (e) => { const capitalizedText = text.charAt(0).toUpperCase() + text.slice(1).toLowerCase(); setText(capitalizedText); props.showAlert("Text successfully capitalized ", "success"); } const handleInvertClick = (e) => { let length = text.length; let newText = ""; for (let i = 0; i < length; i++) { if (text[i].toLowerCase() === text[i]) { newText += text[i].toUpperCase(); } else { newText += text[i].toLowerCase(); } } setText(newText); props.showAlert("Case Inverted", "success"); } const handleCopy = (e) => { navigator.clipboard.writeText(text); props.showAlert("Copied to clipboard", "success"); } const handleReadAloud = (e) => { let msg = new SpeechSynthesisUtterance(); msg.text = text; window.speechSynthesis.speak(msg); if (readText === "Read Aloud") { setReadText("Stop"); } else { setReadText("Read Aloud"); window.speechSynthesis.cancel(); } } return ( <> <div className="container" style={{ color: props.mode === "dark" ? "white" : "#042723" }}> <h2>{props.heading}</h2> <div className="mb-1"> <textarea placeholder="Enter text here..." value={text} style={{ backgroundColor: props.mode === "dark" ? "#13466e" : "white", color: props.mode === "dark" ? "white" : "#042723", resize: "none" }} className="form-control" id="myBox" onChange={handleOnChange} rows="6" > </textarea> </div> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleUpClick}>Convert to Uppercase</button> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleLoClick}>Convert to Lowercase</button> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleInvertClick}>Swap Case</button> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleCapitalizeClick}>Capitalized Case</button> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleRemoveSpace}>Remove Extra Spaces</button> <button disabled={ text.length === 0 } className="btn btn-primary mx-1 my-2" onClick={handleCopy}>Copy to Clipboard</button> <button disabled={ text.length === 0 } className="btn btn-warning mx-1 my-2" onClick={handleReadAloud}>{readText}</button> <button disabled={ text.length === 0 } className="btn btn-danger mx-1 my-2" onClick={handleClearClick}>Clear text</button> </div> <div className="container my-3" style={{ color: props.mode === "dark" ? "white" : "#042723" }}> <h3>Your text Summary</h3> <p>{text.split(/\s+/).filter((char) => char !== "").length} words and {text.length} characters</p> <p>{0.008 * text.split(/\s+/).filter((char) => char !== "").length} Minutes read</p> <h3>Preview</h3> <p>{text.length > 0 ? text : "Nothing to preview"}</p> </div> </> ) }
package com.dlowji.simple.command.api.aggregates; import com.dlowji.simple.command.api.commands.CreateEmployeeCommand; import com.dlowji.simple.command.api.events.employee.EmployeeCreatedEvent; import org.axonframework.commandhandling.CommandHandler; import org.axonframework.eventsourcing.EventSourcingHandler; import org.axonframework.modelling.command.AggregateIdentifier; import org.axonframework.modelling.command.AggregateLifecycle; import org.axonframework.spring.stereotype.Aggregate; import org.springframework.beans.BeanUtils; import java.math.BigDecimal; import java.time.LocalDate; @Aggregate public class EmployeeAggregate { @AggregateIdentifier private String employeeId; private String fullName; private String email; private boolean gender; private BigDecimal salary; private LocalDate dob; private String phone; private String address; private String roleId; public EmployeeAggregate() { } @CommandHandler public EmployeeAggregate(CreateEmployeeCommand createEmployeeCommand) { EmployeeCreatedEvent employeeCreatedEvent = new EmployeeCreatedEvent(); BeanUtils.copyProperties(createEmployeeCommand, employeeCreatedEvent); AggregateLifecycle.apply(employeeCreatedEvent); } @EventSourcingHandler public void on(EmployeeCreatedEvent employeeCreatedEvent) { this.employeeId = employeeCreatedEvent.getEmployeeId(); this.fullName = employeeCreatedEvent.getFullName(); this.email = employeeCreatedEvent.getEmail(); this.gender = employeeCreatedEvent.isGender(); this.salary = employeeCreatedEvent.getSalary(); this.dob = employeeCreatedEvent.getDob(); this.phone = employeeCreatedEvent.getPhone(); this.address = employeeCreatedEvent.getAddress(); this.roleId = employeeCreatedEvent.getRoleId(); } }
# SSD1306 OLED Display Linux Device Driver This repository contains the Linux device driver for the SSD1306 OLED display. The SSD1306 is a monochrome OLED display, popular for its simplicity and ease of use in various embedded systems and IoT projects. This driver enables interaction with the display at the kernel level, providing a foundation for higher-level applications to utilize its features via a user-space interface. ![alt text](img/ssd1306-img.png) ## Features - **Set Rotate:** Set the display rotation. - **Horizontal Flip:** Flip the display horizontally. - **Invert Display:** Inverts the display colors, turning black pixels to white and vice versa, to enhance visibility or for visual effects. - **Clear Screen:** Clear the display screen. - **Draw Pixel:** Draw a pixel at a specified location. - **Draw Area:** Draw a rectangular area with custom data. ## Prerequisites Before installing and using this driver, ensure your system meets the following requirements: - Linux kernel version 4.x or higher. - I2C support enabled in the kernel. - Access to the I2C bus where the SSD1306 display is connected. ## Installation 1. Clone this repository to your local machine. 2. Navigate to the directory containing the driver source code. 3. Compile the driver using the appropriate kernel build system. 4. Insert the compiled module into the kernel: `sudo insmod ssd1306.ko` 5. Verify the driver is loaded correctly using `dmesg | grep SSD1306`. ## Integrating with Yocto Projects To integrate the SSD1306 OLED I2C driver into your Yocto project, follow these steps: 1. **Prepare Your Yocto Layer**: If you don't already have a custom Yocto layer where you can place external recipes, create one using the `bitbake-layers create-layer` command. Let's assume this layer is named `meta-custom`. 2. **Add the SSD1306 Driver Recipe**: Copy the `ssd1306-driver.bb` recipe from this repository into your layer's recipe directory. For example, you might place it in `meta-custom/recipes-ssd1306/ssd1306-driver/`. 3. **Add Your Layer to the Build**: If your new layer (`meta-custom`) isn't already included in your build configuration, add it to your `bblayers.conf` file located in the `conf` directory of your Yocto build environment. 4. **Build the Driver**: You can now include the SSD1306 driver in your Yocto build. Add `ssd1306-driver` to your image recipe, or build it directly using BitBake: ## Device Tree Configuration The driver is configured to work with a specific I2C bus and address via the device tree. A sample device tree snippet is provided in `ssd1306.dtsi`. Customize this according to your hardware setup. ```dts // ssd1306.dtsi &i2c2 { clock-frequency = <400000>; // Set I2C2 bus speed to 400kHz ssd1306_display: ssd1306@3C { compatible = "vendor,ssd1306"; reg = <0x3C>; oled-lines = <64>; oled-columns = <128>; status = "okay"; }; }; ``` ## Usage The driver exposes a character device interface for user-space applications to interact with the display. Example operations include setting the display orientation, drawing pixels, and clearing the screen. For detailed usage instructions and examples, refer to the user-space application documentation available in [SSD1306-Tool](https://github.com/bdcabreran/ssd1306-tool/tree/master) repository ### Writing to the Device Write operations to the device can be performed using the standard `write()` system call. Commands are structured as data packets, each consisting of a command identifier followed by the necessary parameters. ### Supported Commands - **Set Rotate:** Set the display rotation. - **Horizontal Flip:** Flip the display horizontally. - **Display Flip:** Flip the display vertically. - **Clear Screen:** Clear the display screen. - **Draw Pixel:** Draw a pixel at a specified location. - **Draw Area:** Draw a rectangular area with custom data. ## User-Level Application For higher-level control and to demonstrate the driver's capabilities, a separate user-level application is available. This application provides a convenient interface for interacting with the display, showcasing its functionalities through various demos and usage examples. The application can be found in a separate repository: [SSD1306-Tool](https://github.com/bdcabreran/ssd1306-tool/tree/master) ## License This project is licensed under the [MIT License](LICENSE.md) - see the LICENSE file for details. ## Author **Bayron Cabrera** - **GitHub:** https://github.com/bdcabreran - **LinkedIn:** https://www.linkedin.com/in/bayron-cabrera-517821124/ - **Email:** bayron.nanez@gmail.com ---
import numpy as np import nnfs from nnfs.datasets import spiral_data from tensorflow import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Activation from kerastuner.tuners import RandomSearch import time nnfs.init() LOG_DIR = f"{int(time.time())}" class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLu: def forward(self, inputs): self.output = np.maximum(0, inputs) class Activation_Softmax: def forward(self, inputs): exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) probabilities = exp_values / np.sum(exp_values, axis=1, keepdims=True) self.output = probabilities class Loss: def calculate(self, output, y): sample_losses = self.forward(output, y) data_loss = np.mean(sample_losses) return data_loss class Loss_CategoricalCrossentropy(Loss): def forward(self, y_pred, y_true): samples = len(y_pred) y_pred_clipped = np.clip(y_pred, 1e-7, 1-1e-7) if len(y_true.shape) == 1: correct_confidences = y_pred_clipped[range(samples), y_true] elif len(y_true.shape) == 2: correct_confidences = np.sum(y_pred_clipped*y_true, axis=1) negative_log_likelihoods = -np.log(correct_confidences) return negative_log_likelihoods X, y = spiral_data(samples=100, classes=3) dense1 = Layer_Dense(2, 3) activation1 = Activation_ReLu() dense2 = Layer_Dense(3, 3) activation2 = Activation_Softmax() dense1.forward(X) activation1.forward(dense1.output) dense2.forward(activation1.output) activation2.forward(dense2.output) print(activation2.output[:5]) loss_function = Loss_CategoricalCrossentropy() loss = loss_function.calculate(activation2.output, y) print('Loss: ', loss) tuner = RandomSearch( Layer_Dense, objective='val_accuracy', max_trials=1, # how many model variations to test? executions_per_trial=1, # how many trials per variation? (same model could perform differently) directory=LOG_DIR ) tuner.search(x=X, y=y, #verbose=2, # just slapping this here bc jupyter notebook. The console out was getting messy. epochs=1, batch_size=64, #callbacks=[tensorboard], # if you have callbacks like tensorboard, they go here. validation_data=(X, y)) print(tuner.get_best_hyperparameters()[0].values) print(tuner.results_summary())
const express = require('express'); const morgan = require('morgan'); const rateLimit = require('express-rate-limit'); const helmet = require('helmet'); const mongoSanitize = require('express-mongo-sanitize'); const xss = require('xss-clean'); const hpp = require('hpp'); const cors = require('cors'); const AppError = require('./utils/appError'); const globalErrorHandler = require('./controllers/errorController'); const userRouter = require('./routes/userRoutes'); const scannerRouter = require('./routes/scannerRoutes'); const programRouter = require('./routes/programRoute'); const submissionRouter = require('./routes/submissionRoutes'); const app = express(); const { createProxyMiddleware } = require('http-proxy-middleware'); // 1) GLOBAL MIDDLEWARES // Set security HTTP headers app.use(cors({ origin: 'http://127.0.0.1:3000', })) app.use(helmet()); // app.use(cors()); // Development logging if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } // // Limit requests from same API // const limiter = rateLimit({ // max: 100, // windowMs: 60 * 60 * 1000, // message: 'Too many requests from this IP, please try again in an hour!' // }); // app.use('/api', limiter); // Body parser, reading data from body into req.body app.use(express.json({ limit: '10kb' })); // Data sanitization against NoSQL query injection app.use(mongoSanitize()); // Data sanitization against XSS app.use(xss()); // Prevent parameter pollution app.use( hpp({ whitelist: [] }) ); // Serving static files app.use(express.static(`${__dirname}/public`)); // Test middleware app.use((req, res, next) => { req.requestTime = new Date().toISOString(); // console.log(req.headers); next(); }); // 3) ROUTES app.use('/api/v1/users', userRouter); app.use('/api/v1/programs', programRouter); app.use('/api/v1/submissions', submissionRouter); app.use('/api/v1/Scanner', scannerRouter); app.all('*', (req, res, next) => { next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404)); }); app.use(globalErrorHandler); module.exports = app;
<template> <div ref="dropdownRef" class="container"> <input v-model="text" type="text" @focusin="setFilterItems" /> <transition-group name="list" tag="ul"> <li v-for="(item, index) in filterItems" :key="item" :class="{ active: index == selected }" @click="setText(item)" > {{ item }} </li> </transition-group> </div> </template> <script setup lang="ts"> import { ref, watch } from "vue"; import useClickOutside from "./useClickOutside"; const props = defineProps<{ value: string; items: string[]; }>(); const filterItems = ref<string[]>([]); const text = ref(""); const selected = ref(-1); const setFilterItems = () => { filterItems.value = props.items; }; const setText = (item: string) => { text.value = item; }; watch(text, (text) => { if (text) { filterItems.value = props.items.filter((item) => item.toLowerCase().startsWith(text.toLowerCase()) ); } else { filterItems.value = props.items; } }); const dropdownRef = ref<null | HTMLElement>(null); const isClickOutside = useClickOutside(dropdownRef); watch(isClickOutside, () => { if (isClickOutside.value) { filterItems.value = []; } }); </script> <style scoped> .container { width: fit-content; } input { border-radius: 10px; padding: 5px; border: 1px solid #ccc; } ul { list-style: none; padding: 0; margin: 0; border-radius: 5px; margin-top: 10px; } li { cursor: pointer; padding: 3px; margin: 5px; background: #eee; border-radius: 5px; transition: all 0.3s; } li:hover { background: #ccc; scale: 1.02; } .list-move, /* apply transition to moving elements */ .list-enter-active, .list-leave-active { transition: all 0.5s ease; } .list-enter-from, .list-leave-to { opacity: 0; transform: translateY(30px); } /* ensure leaving items are taken out of layout flow so that moving animations can be calculated correctly. */ .list-leave-active { position: absolute; } </style>
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Sonic Visualiser An audio file viewer and annotation editor. Centre for Digital Music, Queen Mary, University of London. This file copyright 2006-2007 Chris Cannam and QMUL. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See the file COPYING included with this distribution for more information. */ #ifndef _RANGE_SUMMARISABLE_TIME_VALUE_MODEL_H_ #define _RANGE_SUMMARISABLE_TIME_VALUE_MODEL_H_ #include <QObject> #include "DenseTimeValueModel.h" #include "base/ZoomConstraint.h" #include <stdint.h> /** * Base class for models containing dense two-dimensional data (value * against time) that may be meaningfully represented in a zoomed view * using min/max range summaries. Audio waveform data is an obvious * example: think "peaks and minima" for "ranges". */ class RangeSummarisableTimeValueModel : public DenseTimeValueModel { Q_OBJECT public: RangeSummarisableTimeValueModel() { } class Range { public: Range() : m_new(true), m_min(0.f), m_max(0.f), m_absmean(0.f) { } Range(const Range &r) : m_new(true), m_min(r.m_min), m_max(r.m_max), m_absmean(r.m_absmean) { } Range(float min, float max, float absmean) : m_new(true), m_min(min), m_max(max), m_absmean(absmean) { } float min() const { return m_min; } float max() const { return m_max; } float absmean() const { return m_absmean; } void setMin(float min) { m_min = min; m_new = false; } void setMax(float max) { m_max = max; m_new = false; } void setAbsmean(float absmean) { m_absmean = absmean; } void sample(float s) { if (m_new) { m_min = s; m_max = s; m_new = false; } else { if (s < m_min) m_min = s; if (s > m_max) m_max = s; } } private: bool m_new; float m_min; float m_max; float m_absmean; }; typedef std::vector<Range> RangeBlock; /** * Return ranges from the given start frame, corresponding to the * given number of underlying sample frames, summarised at the * given block size. duration / blockSize ranges should ideally * be returned. * * If the given block size is not supported by this model * (according to its zoom constraint), also modify the blockSize * parameter so as to return the block size that was actually * obtained. */ virtual void getSummaries(int channel, sv_frame_t start, sv_frame_t count, RangeBlock &ranges, int &blockSize) const = 0; /** * Return the range from the given start frame, corresponding to * the given number of underlying sample frames, summarised at a * block size equal to the distance between start and end frames. */ virtual Range getSummary(int channel, sv_frame_t start, sv_frame_t count) const = 0; virtual int getSummaryBlockSize(int desired) const = 0; QString getTypeName() const { return tr("Range-Summarisable Time-Value"); } std::string getType() const { return "RangeSummarisableTimeValueModel"; } }; #endif
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Menú lateral responsive - MagtimusPro</title> <link rel="stylesheet" href="css/estilos.css"> <script src="https://kit.fontawesome.com/41bcea2ae3.js" crossorigin="anonymous"></script> </head> <body id="body"> <header> <div class="icon__menu"> <i class="fas fa-bars" id="btn_open"></i> </div> </header> <div class="menu__side" id="menu_side"> <div class="name__page"> <i class="fab fa-person"></i> <h4>Mario</h4> </div> <div class="options__menu"> <a href="index.html" class="selected"> <div class="option"> <i class="fas fa-home" title="Inicio"></i> <h4>Inicio</h4> </div> </a> <a href="Reglas básicas de derivación.html"> <div class="option"> <i class="far fa-file" title="Portafolio"></i> <h4>Reglas básicas de derivación</h4> </div> </a> <a href="Reglas básicas de derivación1.HTML"> <div class="option"> <i class="far fa-file" title="Cursos"></i> <h4>Reglas básicas de derivación_2.0</h4> </div> </a> <a href="Logaritmica y Natural.html"> <div class="option"> <i class="far fa-file" title="Blog"></i> <h4>Logarítmica y natural</h4> </div> </a> <a href="PREGUNTAS/index.html"> <div class="option"> <i class="far fa-address-card" title="Nosotros"></i> <h4>Juego de PREGUNTAS</h4> </div> </a> </div> </div> <main> <h1>Uso de las reglas de derivación</h1><br> <p>Las reglas de derivación son un conjunto de herramientas y técnicas que se utilizan para calcular las derivadas de funciones. La derivación es una operación fundamental en cálculo diferencial y es ampliamente utilizada en diversas áreas de las matemáticas, la física, la economía y otras disciplinas científicas.<br><br> <h2>Las reglas de derivación permiten determinar la tasa de cambio instantánea de una función en un punto dado. Estas reglas incluyen:<br><br> </h2> • Regla de la potencia: permite derivar funciones que involucran potencias de x.<br> • Regla de la constante: establece que la derivada de una constante es cero.<br> • Regla de la suma y la resta: permite derivar la suma y la resta de funciones.<br> • Regla del producto: establece cómo derivar el producto de dos funciones.<br> • Regla del cociente: permite derivar el cociente de dos funciones.<br><br> Cont..<br> • Regla de la cadena: permite derivar funciones compuestas.<br> • Regla de la derivada de una función compuesta inversa.<br> • Regla de la derivada de las funciones trigonométricas.<br> • Regla de la derivada de las funciones exponenciales y logarítmicas.<br> • Regla de la derivada de las funciones hiperbólicas.<br><br> Estas reglas son fundamentales para calcular derivadas de manera eficiente y se combinan y aplican según las características de la función que se desea derivar. Con el uso adecuado de estas reglas, se pueden resolver problemas de optimización, modelar fenómenos físicos, analizar el comportamiento de funciones y mucho más.<br><br> <h2>Reglas básicas de derivación</h2><br><br> <h3>Cadena</h3><br> 𝑆𝑖 𝑓 𝑥 = 𝑥 𝑛<br> 𝑑𝑦<br> 𝑑𝑥<br> = 𝑛 𝑥 𝑛−1. 𝑥´<br> <h3>Exponencial</h3><br><br> 𝑆𝑖 𝑓 𝑥 = 𝑎𝑥<br> 𝑑𝑦<br> 𝑑𝑥<br> = 𝑎𝑥. ln(𝑎)<br> <h3> Función Exponencial</h3><br><br> 𝑆𝑖 𝑓 𝑥 = 𝑎𝑢𝑥<br> 𝑑𝑦/𝑑𝑥 = 𝑎𝑈𝑥. ln(𝑎) . (𝑢𝑥) ´<br><br> <h2> básicas de derivación</h2><br><br> <h3>Logarítmica</h3><br> 𝑆𝑖 𝑓 = 𝐿𝑜𝑔𝑎(𝑢𝑥)<br> 𝑑𝑦/𝑑𝑥 = 1/𝑢𝑥. ln 𝑎 . (𝑢𝑥)′<br><br> <h3> natural</h3><br><br> 𝑆𝑖 𝑓 = 𝑙𝑛 (𝑢𝑥)<br> 𝑑𝑦/𝑑𝑥 = (𝑢𝑥)′/𝑢𝑥<br> <img src="Imagen de WhatsApp 2023-07-16 a las 10.04.59.jpg" alt=""> </p> </main> <script src="js/script.js"></script> </body> </html>
function[] = alpha_voltagetrace(alpha, Pmax_e, tau1i) % ALPHA_VOLTAGETRACE: Generates figures comparing spiking behavior of FFEI % triad synapse circuit models with different alpha (FFE, 1, 1.25, 2, 5) % General simulation parameters F = 50; % input modulation frequency (Hz) % tmax = 0.2; % length of simulation (s) tmax = 0.5; dt = 0.0001/5; % time step length (s) tvec = 0:dt:tmax; % time vector (s) Nt = length(tvec); % provide a custom input: 50 Hz uniform spiking signal spktrain = zeros(1,Nt); spktrain(round(1/(4*F)/dt):round(1/F/dt):end) = 1; % Run triad synapse simulations using run_triad_model.m % input: Poisson spike train input over time % Ps_E, Ps_I: excitatory (or inhibitory) conductance post-synapse due to % input % Vm_noreset: membrane potential of output neuron over time (no spiking) % I_syn_noreset: synaptic current produced by input % I_leak_noreset: leak current for output neuron input = generate_input(F, 1, 0, 'manual_signal', spktrain, 'tmax', tmax, 'dt', dt); output = run_triad_model(input, 0, 'Pmax_e', Pmax_e, 'tau1i', tau1i, 'alpha', alpha); Vm_noreset = output.Vm; Ps_E = output.Ps_E; Ps_I = output.Ps_I; input = output.input_spktrain; I_syn_noreset = output.I_syn; I_leak_noreset = output.I_leak; % Plot model behavior without Vm resets figure; subplot(4,1,1) plot(tvec, input, 'k') hold on; %plot(tvec, rate/PR, 'k:') ylabel('Spike present') xlabel('Time (s)') box off; title(['alpha = ' num2str(alpha)]) subplot(4,1,2) plot(tvec, Ps_E, 'r') hold on; plot(tvec, Ps_I, 'b') ylabel('Synaptic conductance (S)') xlabel('Time (s)') legend('G_e', 'G_i') box off; subplot(4,1,3) hold on; %plot(tvec, Im_syn_noreset + Im_leak_noreset, 'k') plot(tvec, I_syn_noreset, 'k') plot(tvec, -I_leak_noreset, 'g') %plot([0 tvec(end)], [0 0], 'k:') ylabel('Current (A)') ylim([-2e-8 5e-8]) xlabel('Time (s)') legend('I_s_y_n', '-I_l_e_a_k') box off; subplot(4,1,4) plot(tvec, Vm_noreset, 'k') ylabel('Voltage (V)') ylim([-0.09 -0.02]) xlabel('Time (s)') box off; end
library(sf) library(tidyverse) calveg_database_files <- list.files(here::here("..","CalVeg"), "S_USA.EVMid") nvcs_data <- data.frame() for(file in calveg_database_files) { calveg <- st_read(here::here("..","CalVeg",file)) calveg_natural <- as.data.frame(calveg) %>% select("NVCS_CLASS","NVCS_SUBCLASS", "NVCS_FORMATION", "NVCS_DIVISION", "NVCS_MACROGROUP", "ECOREGION_DIVISION", "SHAPE_Area") %>% drop_na(NVCS_MACROGROUP) %>% group_by(NVCS_MACROGROUP) %>% summarize(NVCS_CLASS=as.character(Mode(NVCS_CLASS)), NVCS_SUBCLASS=as.character(Mode(NVCS_SUBCLASS)), NVCS_FORMATION=as.character(Mode(NVCS_FORMATION)), NVCS_DIVISION=as.character(Mode(NVCS_DIVISION)), ECOREGION_DIVISION=as.character(Mode(ECOREGION_DIVISION)), area_total = sum(SHAPE_Area)*1e10/(30^2), area_median = median(SHAPE_Area)*1e10/(30^2)) if(nrow(nvcs_data) == 0) { nvcs_data <- calveg_natural } else { nvcs_data <- rbind(nvcs_data, calveg_natural) } } write_csv(nvcs_data, here::here("calveg_all_formations.csv")) nvcs_unique <- nvcs_data %>% select(-ECOREGION_DIVISION) %>% select(-area_median) %>% group_by(NVCS_MACROGROUP) %>% summarize(NVCS_CLASS=as.character(Mode(NVCS_CLASS)), NVCS_SUBCLASS=as.character(Mode(NVCS_CLASS)), NVCS_FORMATION=as.character(Mode(NVCS_FORMATION)), NVCS_DIVISION=as.character(Mode(NVCS_DIVISION)), area_total = sum(area_total)*1e10/(30^2)) write_csv(nvcs_unique, here::here("calveg_all_formations_unique.csv")) # deal with 'all data' example all_data_vafb <- raster("D:/SERDP/GEE_Classifier/Phenology/vandenberg/vandenberg_all_data_2020_phenoseries.tif")
mysql> \. c:/150a/apatrick_assignment06.sql -------------- /* Assignment06.sql Andrew Patrick CS 150A, Fall 2021 */ USE restaurant -------------- Query OK, 0 rows affected (0.00 sec) -------------- /* Question 01 : Run Describe on orders. Add default of today's date to order_date. Run Describe on orders to verify. */ DESCRIBE orders -------------- +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | order_number | decimal(5,0) | NO | PRI | NULL | | | order_date | date | NO | | NULL | | | cust_id | decimal(5,0) | NO | MUL | NULL | | | staff_id | decimal(5,0) | NO | MUL | NULL | | +--------------+--------------+------+-----+---------+-------+ 4 rows in set (0.04 sec) -------------- ALTER TABLE orders MODIFY order_date DATE NOT NULL DEFAULT (CURRENT_DATE()) -------------- Query OK, 0 rows affected (0.60 sec) Records: 0 Duplicates: 0 Warnings: 0 -------------- DESCRIBE orders -------------- +--------------+--------------+------+-----+-----------+-------------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+-----------+-------------------+ | order_number | decimal(5,0) | NO | PRI | NULL | | | order_date | date | NO | | curdate() | DEFAULT_GENERATED | | cust_id | decimal(5,0) | NO | MUL | NULL | | | staff_id | decimal(5,0) | NO | MUL | NULL | | +--------------+--------------+------+-----+-----------+-------------------+ 4 rows in set (0.00 sec) -------------- /* Question 02 : Run Describe on customers. Add customers_phone with NULL allowed and 11 digits. Run Describe on customers to verify. */ DESCRIBE customers -------------- +--------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+---------------+------+-----+---------+-------+ | customer_id | decimal(5,0) | NO | PRI | NULL | | | first_name | varchar(25) | NO | | NULL | | | last_name | varchar(35) | NO | | NULL | | | address | varchar(50) | NO | | NULL | | | city | varchar(30) | NO | | NULL | | | state | varchar(20) | NO | | NULL | | | zip | decimal(10,0) | NO | | NULL | | | phone_number | varchar(25) | NO | | NULL | | +--------------+---------------+------+-----+---------+-------+ 8 rows in set (0.00 sec) -------------- ALTER TABLE customers ADD customers_phone VARCHAR(11) -------------- Query OK, 0 rows affected (0.69 sec) Records: 0 Duplicates: 0 Warnings: 0 -------------- DESCRIBE customers -------------- +-----------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------------+------+-----+---------+-------+ | customer_id | decimal(5,0) | NO | PRI | NULL | | | first_name | varchar(25) | NO | | NULL | | | last_name | varchar(35) | NO | | NULL | | | address | varchar(50) | NO | | NULL | | | city | varchar(30) | NO | | NULL | | | state | varchar(20) | NO | | NULL | | | zip | decimal(10,0) | NO | | NULL | | | phone_number | varchar(25) | NO | | NULL | | | customers_phone | varchar(11) | YES | | NULL | | +-----------------+---------------+------+-----+---------+-------+ 9 rows in set (0.01 sec) -------------- /* Question 03 : Run Describe on customers. Drop customers_phone. Run Describe on customers to verify. */ DESCRIBE customers -------------- +-----------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------------+------+-----+---------+-------+ | customer_id | decimal(5,0) | NO | PRI | NULL | | | first_name | varchar(25) | NO | | NULL | | | last_name | varchar(35) | NO | | NULL | | | address | varchar(50) | NO | | NULL | | | city | varchar(30) | NO | | NULL | | | state | varchar(20) | NO | | NULL | | | zip | decimal(10,0) | NO | | NULL | | | phone_number | varchar(25) | NO | | NULL | | | customers_phone | varchar(11) | YES | | NULL | | +-----------------+---------------+------+-----+---------+-------+ 9 rows in set (0.00 sec) -------------- ALTER TABLE customers DROP customers_phone -------------- Query OK, 0 rows affected (1.63 sec) Records: 0 Duplicates: 0 Warnings: 0 -------------- DESCRIBE customers -------------- +--------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+---------------+------+-----+---------+-------+ | customer_id | decimal(5,0) | NO | PRI | NULL | | | first_name | varchar(25) | NO | | NULL | | | last_name | varchar(35) | NO | | NULL | | | address | varchar(50) | NO | | NULL | | | city | varchar(30) | NO | | NULL | | | state | varchar(20) | NO | | NULL | | | zip | decimal(10,0) | NO | | NULL | | | phone_number | varchar(25) | NO | | NULL | | +--------------+---------------+------+-----+---------+-------+ 8 rows in set (0.00 sec) -------------- /* Question 04 : Write the INSERT to add the specified row into the customers table. */ INSERT INTO customers VALUES (60, 'brian', 'rogers', '820 Bounty Drive', 'Palo Alto', 'CA', 94342, '01654564898''') -------------- Query OK, 1 row affected (0.18 sec) -------------- /* Question 05 : Create 3 o_ tables using specified syntax. */ -- drop tables if exist DROP TABLE IF EXISTS o_departments -------------- Query OK, 0 rows affected, 1 warning (0.04 sec) -------------- DROP TABLE IF EXISTS o_staff -------------- Query OK, 0 rows affected, 1 warning (0.02 sec) -------------- DROP TABLE IF EXISTS o_jobs -------------- Query OK, 0 rows affected, 1 warning (0.02 sec) -------------- -- create tables with specified syntax -------------- Query OK, 0 rows affected (0.00 sec) -------------- CREATE TABLE o_jobs AS (SELECT * FROM jobs) -------------- Query OK, 13 rows affected (0.89 sec) Records: 13 Duplicates: 0 Warnings: 0 -------------- CREATE TABLE o_staff AS (SELECT staff_id, first_name, last_name, email, hire_date, job_id FROM staff) -------------- Query OK, 30 rows affected (0.89 sec) Records: 30 Duplicates: 0 Warnings: 0 -------------- CREATE TABLE o_departments AS (SELECT * FROM departments) -------------- Query OK, 6 rows affected (0.81 sec) Records: 6 Duplicates: 0 Warnings: 0 -------------- /* Question 06 : Write the INSERT to add the Human Resources job to the o_jobs table. */ INSERT INTO o_jobs VALUES ('HR_MAN', 'Human Resources Manager', 4500, 5500) -------------- Query OK, 1 row affected (0.15 sec) -------------- /* Question 07 : Rename o_jobs to o_job_description. */ RENAME TABLE o_jobs TO o_job_description -------------- Query OK, 0 rows affected (0.38 sec) -------------- /* Question 08 : Create a copy of the staff table and call it your_initials_emp, then add a column. */ DROP TABLE IF EXISTS amp_emp -------------- Query OK, 0 rows affected, 1 warning (0.02 sec) -------------- CREATE TABLE amp_emp AS (SELECT * FROM staff) -------------- Query OK, 30 rows affected (0.78 sec) Records: 30 Duplicates: 0 Warnings: 0 -------------- -- Add department_name column, match data type to departments table ALTER TABLE amp_emp ADD department_name VARCHAR(30) -------------- Query OK, 0 rows affected (0.29 sec) Records: 0 Duplicates: 0 Warnings: 0 -------------- /* Question 09 : Drop the o_staff table. */ DROP TABLE IF EXISTS o_staff -------------- Query OK, 0 rows affected (0.56 sec) mysql> notee
package com.kingjinho.portfolio.com.kingjinho.mobile import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.kingjinho.mobile.curvedSection.CurvedSection import com.kingjinho.mobile.drawer.ScreenHomeRental import com.kingjinho.portfolio.game.hopscotch.HopScotchGameScreen import com.kingjinho.portfolio.game.snake.SnakeGameScreen import com.kingjinho.portfolio.game.touchtouch.initial.TouchTouchGameScreen import com.kingjinho.portfolio.game.touchtouch.initial.TouchTouchGameViewModel @Composable fun PortfolioApp() { val navController = rememberNavController() NavHost(navController = navController, startDestination = Screen.Home.route) { composable("home") { HomeScreen( onButtonClick = { navController.navigate(it.route) } ) } composable("curvedSection") { CurvedSection() } composable(Screen.CustomDrawer.route) { ScreenHomeRental() } composable(Screen.HopScotchGame.route) { HopScotchGameScreen { navController.popBackStack() } } composable(Screen.TouchTouchGame.route) { TouchTouchGameScreen( viewModel = TouchTouchGameViewModel() ) } composable(Screen.SnakeGame.route) { SnakeGameScreen() } } } private val screens = listOf( Screen.CustomDrawer, Screen.CurvedSection, Screen.HopScotchGame, Screen.TouchTouchGame, Screen.SnakeGame ) @Composable fun HomeScreen(onButtonClick: (Screen) -> Unit = {}) { val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxSize() .padding(horizontal = 24.dp) .verticalScroll(scrollState), verticalArrangement = Arrangement.Center ) { screens.forEach { NavigationButton( modifier = Modifier.padding(bottom = 16.dp), item = it, onButtonClick = onButtonClick ) } } } @Composable fun NavigationButton( modifier: Modifier = Modifier, onButtonClick: (Screen) -> Unit = {}, item: Screen ) { Button( onClick = { onButtonClick(item) }, modifier = modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium ) { Text(text = stringResource(item.titleRes)) } }
import React, { useState } from 'react' import { Link } from 'react-router-dom' import PropTypes from 'prop-types' import { useJournalContext } from '../../hooks/useJournalContext' import { useThemeContext } from '../../hooks/useThemeContext' export const ParentComment = ({ username, comment, commentedAt, likes, commentId }) => { const { theme } = useThemeContext(); const { fetchReplies } = useJournalContext(); const [isOpenReplies, setIsOpenReplies] = useState(false); const [repliespage, setRepliespage] = useState(1); const [replies, setReplies] = useState([]); const [reply, setReply] = useState(''); const getReplies = async () => { const result = await fetchReplies({ commentId, repliespage }) setRepliespage(page => page + 1); setReplies([...replies, ...result]); } const openReplies = async () => { if (repliespage === 1) { await getReplies(); } setIsOpenReplies(prevReplies => !prevReplies) } return ( <> <div className="parent-comment"> <ChildComment key={commentId} username={username} comment={comment} commentedAt={commentedAt} likes={likes} openReplies={openReplies} /> {isOpenReplies && <div className="replies" style={{ display: isOpenReplies ? "flex" : "none" }}> <div className="add-comment"> <input name="reply" id="add-comment" placeholder='Reply Here' value={reply} onChange={(e) => setReply(e.target.value)}></input> <button id='add-comment-button' > Add {/* <i className="fa fa-angle-right"></i> */} </button> </div> { replies[0] && replies.map(reply => <blockquote key={reply._id}> <ChildComment username={reply.username} comment={reply.comment} commentedAt={reply.commentedAt} likes={reply.likes} isChild={true} /> </blockquote> ) || <div style={{ textAlign: 'center' }}>No Replies</div> } <div className="load-more"> <span> <i className="fa fa-angle-down " ><span className={`dark-text-${theme}`}>Load More</span></i> </span> </div> </div> } </div> </> ) } ParentComment.propTypes = { username: PropTypes.string.isRequired, comment: PropTypes.string.isRequired, commentedAt: PropTypes.instanceOf(Date).isRequired, likes: PropTypes.number.isRequired, replies: PropTypes.instanceOf(Array) } export const ChildComment = ({ username, comment, commentedAt, likes, isChild, openReplies }) => { const like = () => { } return ( <> <div className="comment "> <div className="comment-name"> <Link to={`/user/${username}`} className="username">{username}</Link> <div className="journal-date light-text">{commentedAt.toString().slice(4, 16)}</div> </div> <div className="comment-desc">{comment}</div> <div className="comment-details"> <i className="fa fa-heart" onClick={like} style={{ color: likes.isLiked ? "#ff2424" : "#000" }}><span >{likes.count} </span> </i> {!isChild && <i className="fa fa-comment" onClick={openReplies}><span>Replies</span></i> } </div> </div> </> ) } ChildComment.propTypes = { username: PropTypes.string.isRequired, comment: PropTypes.string.isRequired, commentedAt: PropTypes.instanceOf(Date).isRequired, likes: PropTypes.number.isRequired, openReplies: PropTypes.func }
/** * 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 org.apache.hadoop.mapred; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.JobTracker.IllegalStateException; import org.apache.hadoop.util.StringUtils; /** * A {@link TaskScheduler} that implements the requirements in HADOOP-3421 * and provides a HOD-less way to share large clusters. This scheduler * provides the following features: * * support for queues, where a job is submitted to a queue. * * Queues are guaranteed a fraction of the capacity of the grid (their * 'guaranteed capacity') in the sense that a certain capacity of resources * will be at their disposal. All jobs submitted to the queues of an Org * will have access to the capacity guaranteed to the Org. * * Free resources can be allocated to any queue beyond its guaranteed * capacity. These excess allocated resources can be reclaimed and made * available to another queue in order to meet its capacity guarantee. * * The scheduler guarantees that excess resources taken from a queue will * be restored to it within N minutes of its need for them. * * Queues optionally support job priorities (disabled by default). * * Within a queue, jobs with higher priority will have access to the * queue's resources before jobs with lower priority. However, once a job * is running, it will not be preempted for a higher priority job. * * In order to prevent one or more users from monopolizing its resources, * each queue enforces a limit on the percentage of resources allocated to a * user at any given time, if there is competition for them. * */ class CapacityTaskScheduler extends TaskScheduler { /** * For keeping track of reclaimed capacity. * Whenever slots need to be reclaimed, we create one of these objects. * As the queue gets slots, the amount to reclaim gets decremented. if * we haven't reclaimed enough within a certain time, we need to kill * tasks. This object 'expires' either if all resources are reclaimed * before the deadline, or the deadline passes . */ private static class ReclaimedResource { // how much resource to reclaim public int originalAmount; // how much is to be reclaimed currently public int currentAmount; // the time, in millisecs, when this object expires. // This time is equal to the time when the object was created, plus // the reclaim-time SLA for the queue. public long whenToExpire; // we also keep track of when to kill tasks, in millisecs. This is a // fraction of 'whenToExpire', but we store it here so we don't // recompute it every time. public long whenToKill; public ReclaimedResource(int amount, long expiryTime, long whenToKill) { this.originalAmount = amount; this.currentAmount = amount; this.whenToExpire = expiryTime; this.whenToKill = whenToKill; } } /*********************************************************************** * Keeping track of scheduling information for queues * * We need to maintain scheduling information relevant to a queue (its * name, guaranteed capacity, etc), along with information specific to * each kind of task, Map or Reduce (num of running tasks, pending * tasks etc). * * This scheduling information is used to decide how to allocate * tasks, redistribute capacity, etc. * * A QueueSchedulingInfo(QSI) object represents scheduling information for * a queue. A TaskSchedulingInfo (TSI) object represents scheduling * information for a particular kind of task (Map or Reduce). * **********************************************************************/ private static class TaskSchedulingInfo { /** * the actual gc, which depends on how many slots are available * in the cluster at any given time. */ int guaranteedCapacity = 0; // number of running tasks int numRunningTasks = 0; // number of pending tasks int numPendingTasks = 0; /** for each user, we need to keep track of number of running tasks */ Map<String, Integer> numRunningTasksByUser = new HashMap<String, Integer>(); /** * We need to keep track of resources to reclaim. * Whenever a queue is under capacity and has tasks pending, we offer it * an SLA that gives it free slots equal to or greater than the gap in * its capacity, within a period of time (reclaimTime). * To do this, we periodically check if queues need to reclaim capacity. * If they do, we create a ResourceReclaim object. We also periodically * check if a queue has received enough free slots within, say, 80% of * its reclaimTime. If not, we kill enough tasks to make up the * difference. * We keep two queues of ResourceReclaim objects. when an object is * created, it is placed in one queue. Once we kill tasks to recover * resources for that object, it is placed in an expiry queue. we need * to do this to prevent creating spurious ResourceReclaim objects. We * keep a count of total resources that are being reclaimed. This count * is decremented when an object expires. */ /** * the list of resources to reclaim. This list is always sorted so that * resources that need to be reclaimed sooner occur earlier in the list. */ LinkedList<ReclaimedResource> reclaimList = new LinkedList<ReclaimedResource>(); /** * the list of resources to expire. This list is always sorted so that * resources that need to be expired sooner occur earlier in the list. */ LinkedList<ReclaimedResource> reclaimExpireList = new LinkedList<ReclaimedResource>(); /** * sum of all resources that are being reclaimed. * We keep this to prevent unnecessary ReclaimResource objects from being * created. */ int numReclaimedResources = 0; /** * reset the variables associated with tasks */ void resetTaskVars() { numRunningTasks = 0; numPendingTasks = 0; for (String s: numRunningTasksByUser.keySet()) { numRunningTasksByUser.put(s, 0); } } /** * return information about the tasks */ public String toString(){ float runningTasksAsPercent = guaranteedCapacity!= 0 ? ((float)numRunningTasks * 100/guaranteedCapacity):0; StringBuffer sb = new StringBuffer(); sb.append("Guaranteed Capacity: " + guaranteedCapacity + "\n"); sb.append(String.format("Running tasks: %.1f%% of Guaranteed Capacity\n", runningTasksAsPercent)); // include info on active users if (numRunningTasks != 0) { sb.append("Active users:\n"); for (Map.Entry<String, Integer> entry: numRunningTasksByUser.entrySet()) { if ((entry.getValue() == null) || (entry.getValue().intValue() <= 0)) { // user has no tasks running continue; } sb.append("User '" + entry.getKey()+ "': "); float p = (float)entry.getValue().intValue()*100/numRunningTasks; sb.append(String.format("%.1f%% of running tasks\n", p)); } } return sb.toString(); } } private static class QueueSchedulingInfo { String queueName; /** guaranteed capacity(%) is set in the config */ float guaranteedCapacityPercent = 0; /** * to handle user limits, we need to know how many users have jobs in * the queue. */ Map<String, Integer> numJobsByUser = new HashMap<String, Integer>(); /** min value of user limit (same for all users) */ int ulMin; /** * reclaim time limit (in msec). This time represents the SLA we offer * a queue - a queue gets back any lost capacity withing this period * of time. */ long reclaimTime; /** * We keep track of the JobQueuesManager only for reporting purposes * (in toString()). */ private JobQueuesManager jobQueuesManager; /** * We keep a TaskSchedulingInfo object for each kind of task we support */ TaskSchedulingInfo mapTSI; TaskSchedulingInfo reduceTSI; public QueueSchedulingInfo(String queueName, float gcPercent, int ulMin, long reclaimTime, JobQueuesManager jobQueuesManager) { this.queueName = new String(queueName); this.guaranteedCapacityPercent = gcPercent; this.ulMin = ulMin; this.reclaimTime = reclaimTime; this.jobQueuesManager = jobQueuesManager; this.mapTSI = new TaskSchedulingInfo(); this.reduceTSI = new TaskSchedulingInfo(); } /** * return information about the queue */ public String toString(){ // We print out the queue information first, followed by info // on map and reduce tasks and job info StringBuffer sb = new StringBuffer(); sb.append("Queue configuration\n"); //sb.append("Name: " + queueName + "\n"); sb.append("Guaranteed Capacity Percentage: "); sb.append(guaranteedCapacityPercent); sb.append("%\n"); sb.append(String.format("User Limit: %d%s\n",ulMin, "%")); sb.append(String.format("Reclaim Time limit: %s\n", StringUtils.formatTime(reclaimTime))); sb.append(String.format("Priority Supported: %s\n", (jobQueuesManager.doesQueueSupportPriorities(queueName))? "YES":"NO")); sb.append("-------------\n"); sb.append("Map tasks\n"); sb.append(mapTSI.toString()); sb.append("-------------\n"); sb.append("Reduce tasks\n"); sb.append(reduceTSI.toString()); sb.append("-------------\n"); sb.append("Job info\n"); sb.append(String.format("Number of Waiting Jobs: %d\n", jobQueuesManager.getWaitingJobCount(queueName))); sb.append(String.format("Number of users who have submitted jobs: %d\n", numJobsByUser.size())); return sb.toString(); } } /** quick way to get qsi object given a queue name */ private Map<String, QueueSchedulingInfo> queueInfoMap = new HashMap<String, QueueSchedulingInfo>(); /** * This class captures scheduling information we want to display or log. */ private static class SchedulingDisplayInfo { private String queueName; CapacityTaskScheduler scheduler; SchedulingDisplayInfo(String queueName, CapacityTaskScheduler scheduler) { this.queueName = queueName; this.scheduler = scheduler; } @Override public String toString(){ // note that we do not call updateQSIObjects() here for performance // reasons. This means that the data we print out may be slightly // stale. This data is updated whenever assignTasks() is called, or // whenever the reclaim capacity thread runs, which should be fairly // often. If neither of these happen, the data gets stale. If we see // this often, we may need to detect this situation and call // updateQSIObjects(), or just call it each time. return scheduler.getDisplayInfo(queueName); } } // this class encapsulates the result of a task lookup private static class TaskLookupResult { static enum LookUpStatus { TASK_FOUND, NO_TASK_FOUND, TASK_FAILING_MEMORY_REQUIREMENT, } // constant TaskLookupResult objects. Should not be accessed directly. private static final TaskLookupResult NoTaskLookupResult = new TaskLookupResult(null, TaskLookupResult.LookUpStatus.NO_TASK_FOUND); private static final TaskLookupResult MemFailedLookupResult = new TaskLookupResult(null, TaskLookupResult.LookUpStatus.TASK_FAILING_MEMORY_REQUIREMENT); private LookUpStatus lookUpStatus; private Task task; // should not call this constructor directly. use static factory methods. private TaskLookupResult(Task t, LookUpStatus lUStatus) { this.task = t; this.lookUpStatus = lUStatus; } static TaskLookupResult getTaskFoundResult(Task t) { return new TaskLookupResult(t, LookUpStatus.TASK_FOUND); } static TaskLookupResult getNoTaskFoundResult() { return NoTaskLookupResult; } static TaskLookupResult getMemFailedResult() { return MemFailedLookupResult; } Task getTask() { return task; } LookUpStatus getLookUpStatus() { return lookUpStatus; } } /** * This class handles the scheduling algorithms. * The algos are the same for both Map and Reduce tasks. * There may be slight variations later, in which case we can make this * an abstract base class and have derived classes for Map and Reduce. */ private static abstract class TaskSchedulingMgr { /** our TaskScheduler object */ protected CapacityTaskScheduler scheduler; // can be replaced with a global type, if we have one protected static enum TYPE { MAP, REDUCE } protected TYPE type = null; abstract Task obtainNewTask(TaskTrackerStatus taskTracker, JobInProgress job) throws IOException; abstract int getPendingTasks(JobInProgress job); abstract int killTasksFromJob(JobInProgress job, int tasksToKill); abstract TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi); /** * List of QSIs for assigning tasks. * This list is ordered such that queues that need to reclaim capacity * sooner, come before queues that don't. For queues that don't, they're * ordered by a ratio of (# of running tasks)/Guaranteed capacity, which * indicates how much 'free space' the queue has, or how much it is over * capacity. This ordered list is iterated over, when assigning tasks. */ private List<QueueSchedulingInfo> qsiForAssigningTasks = new ArrayList<QueueSchedulingInfo>(); /** * Comparator to sort queues. * For maps, we need to sort on QueueSchedulingInfo.mapTSI. For * reducers, we use reduceTSI. So we'll need separate comparators. */ private static abstract class QueueComparator implements Comparator<QueueSchedulingInfo> { abstract TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi); public int compare(QueueSchedulingInfo q1, QueueSchedulingInfo q2) { TaskSchedulingInfo t1 = getTSI(q1); TaskSchedulingInfo t2 = getTSI(q2); // if one queue needs to reclaim something and the other one doesn't, // the former is first if ((0 == t1.reclaimList.size()) && (0 != t2.reclaimList.size())) { return 1; } else if ((0 != t1.reclaimList.size()) && (0 == t2.reclaimList.size())){ return -1; } else if ((0 == t1.reclaimList.size()) && (0 == t2.reclaimList.size())){ // neither needs to reclaim. // look at how much capacity they've filled. Treat a queue with gc=0 // equivalent to a queue running at capacity double r1 = (0 == t1.guaranteedCapacity)? 1.0f: (double)t1.numRunningTasks/(double)t1.guaranteedCapacity; double r2 = (0 == t2.guaranteedCapacity)? 1.0f: (double)t2.numRunningTasks/(double)t2.guaranteedCapacity; if (r1<r2) return -1; else if (r1>r2) return 1; else return 0; } else { // both have to reclaim. Look at which one needs to reclaim earlier long tm1 = t1.reclaimList.get(0).whenToKill; long tm2 = t2.reclaimList.get(0).whenToKill; if (tm1<tm2) return -1; else if (tm1>tm2) return 1; else return 0; } } } // subclass for map and reduce comparators private static final class MapQueueComparator extends QueueComparator { TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi) { return qsi.mapTSI; } } private static final class ReduceQueueComparator extends QueueComparator { TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi) { return qsi.reduceTSI; } } // these are our comparator instances protected final static MapQueueComparator mapComparator = new MapQueueComparator(); protected final static ReduceQueueComparator reduceComparator = new ReduceQueueComparator(); // and this is the comparator to use protected QueueComparator queueComparator; TaskSchedulingMgr(CapacityTaskScheduler sched) { scheduler = sched; } // let the scheduling mgr know which queues are in the system void initialize(Map<String, QueueSchedulingInfo> qsiMap) { // add all the qsi objects to our list and sort qsiForAssigningTasks.addAll(qsiMap.values()); Collections.sort(qsiForAssigningTasks, queueComparator); } /** * Periodically, we walk through our queues to do the following: * a. Check if a queue needs to reclaim any resources within a period * of time (because it's running below capacity and more tasks are * waiting) * b. Check if a queue hasn't received enough of the resources it needed * to be reclaimed and thus tasks need to be killed. * The caller is responsible for ensuring that the QSI objects and the * collections are up-to-date. * * Make sure that we do not make any calls to scheduler.taskTrackerManager * as this can result in a deadlock (see HADOOP-4977). */ private synchronized void reclaimCapacity(int nextHeartbeatInterval) { int tasksToKill = 0; QueueSchedulingInfo lastQsi = qsiForAssigningTasks.get(qsiForAssigningTasks.size()-1); TaskSchedulingInfo lastTsi = getTSI(lastQsi); long currentTime = scheduler.clock.getTime(); for (QueueSchedulingInfo qsi: qsiForAssigningTasks) { TaskSchedulingInfo tsi = getTSI(qsi); if (tsi.guaranteedCapacity <= 0) { // no capacity, hence nothing can be reclaimed. continue; } // is there any resource that needs to be reclaimed? if ((!tsi.reclaimList.isEmpty()) && (tsi.reclaimList.getFirst().whenToKill < currentTime + CapacityTaskScheduler.RECLAIM_CAPACITY_INTERVAL)) { // make a note of how many tasks to kill to claim resources tasksToKill += tsi.reclaimList.getFirst().currentAmount; // move this to expiry list ReclaimedResource r = tsi.reclaimList.remove(); tsi.reclaimExpireList.add(r); } // is there any resource that needs to be expired? if ((!tsi.reclaimExpireList.isEmpty()) && (tsi.reclaimExpireList.getFirst().whenToExpire <= currentTime)) { ReclaimedResource r = tsi.reclaimExpireList.remove(); tsi.numReclaimedResources -= r.originalAmount; } // do we need to reclaim a resource later? // if no queue is over capacity, there's nothing to reclaim if (lastTsi.numRunningTasks <= lastTsi.guaranteedCapacity) { continue; } if (tsi.numRunningTasks < tsi.guaranteedCapacity) { // usedCap is how much capacity is currently accounted for int usedCap = tsi.numRunningTasks + tsi.numReclaimedResources; // see if we have remaining capacity and if we have enough pending // tasks to use up remaining capacity if ((usedCap < tsi.guaranteedCapacity) && ((tsi.numPendingTasks - tsi.numReclaimedResources)>0)) { // create a request for resources to be reclaimed int amt = Math.min((tsi.guaranteedCapacity-usedCap), (tsi.numPendingTasks - tsi.numReclaimedResources)); // create a resource object that needs to be reclaimed some time // in the future long whenToKill = qsi.reclaimTime - (CapacityTaskScheduler.HEARTBEATS_LEFT_BEFORE_KILLING * nextHeartbeatInterval); if (whenToKill < 0) whenToKill = 0; tsi.reclaimList.add(new ReclaimedResource(amt, currentTime + qsi.reclaimTime, currentTime + whenToKill)); tsi.numReclaimedResources += amt; LOG.debug("Queue " + qsi.queueName + " needs to reclaim " + amt + " resources"); } } } // kill tasks to reclaim capacity if (0 != tasksToKill) { killTasks(tasksToKill); } } // kill 'tasksToKill' tasks private void killTasks(int tasksToKill) { /* * There are a number of fair ways in which one can figure out how * many tasks to kill from which queue, so that the total number of * tasks killed is equal to 'tasksToKill'. * Maybe the best way is to keep a global ordering of running tasks * and kill the ones that ran last, irrespective of what queue or * job they belong to. * What we do here is look at how many tasks is each queue running * over capacity, and use that as a weight to decide how many tasks * to kill from that queue. */ // first, find out all queues over capacity int loc; for (loc=0; loc<qsiForAssigningTasks.size(); loc++) { QueueSchedulingInfo qsi = qsiForAssigningTasks.get(loc); if (getTSI(qsi).numRunningTasks > getTSI(qsi).guaranteedCapacity) { // all queues from here onwards are running over cap break; } } // if some queue needs to reclaim cap, there must be at least one queue // over cap. But check, just in case. if (loc == qsiForAssigningTasks.size()) { LOG.warn("In Capacity scheduler, we need to kill " + tasksToKill + " tasks but there is no queue over capacity."); return; } // calculate how many total tasks are over cap int tasksOverCap = 0; for (int i=loc; i<qsiForAssigningTasks.size(); i++) { QueueSchedulingInfo qsi = qsiForAssigningTasks.get(i); tasksOverCap += (getTSI(qsi).numRunningTasks - getTSI(qsi).guaranteedCapacity); } // now kill tasks from each queue for (int i=loc; i<qsiForAssigningTasks.size(); i++) { QueueSchedulingInfo qsi = qsiForAssigningTasks.get(i); killTasksFromQueue(qsi, (int)Math.round( ((double)(getTSI(qsi).numRunningTasks - getTSI(qsi).guaranteedCapacity))* tasksToKill/(double)tasksOverCap)); } } // kill 'tasksToKill' tasks from queue represented by qsi private void killTasksFromQueue(QueueSchedulingInfo qsi, int tasksToKill) { // we start killing as many tasks as possible from the jobs that started // last. This way, we let long-running jobs complete faster. int tasksKilled = 0; JobInProgress jobs[] = scheduler.jobQueuesManager. getRunningJobQueue(qsi.queueName).toArray(new JobInProgress[0]); for (int i=jobs.length-1; i>=0; i--) { if (jobs[i].getStatus().getRunState() != JobStatus.RUNNING) { continue; } tasksKilled += killTasksFromJob(jobs[i], tasksToKill-tasksKilled); if (tasksKilled >= tasksToKill) break; } } // return the TaskAttemptID of the running task, if any, that has made // the least progress. TaskAttemptID getRunningTaskWithLeastProgress(TaskInProgress tip) { double leastProgress = 1; TaskAttemptID tID = null; for (Iterator<TaskAttemptID> it = tip.getActiveTasks().keySet().iterator(); it.hasNext();) { TaskAttemptID taskid = it.next(); TaskStatus status = tip.getTaskStatus(taskid); if (status.getRunState() == TaskStatus.State.RUNNING) { if (status.getProgress() < leastProgress) { leastProgress = status.getProgress(); tID = taskid; } } } return tID; } // called when a task is allocated to queue represented by qsi. // update our info about reclaimed resources private synchronized void updateReclaimedResources(QueueSchedulingInfo qsi) { TaskSchedulingInfo tsi = getTSI(qsi); // if we needed to reclaim resources, we have reclaimed one if (tsi.reclaimList.isEmpty()) { return; } ReclaimedResource res = tsi.reclaimList.getFirst(); res.currentAmount--; if (0 == res.currentAmount) { // move this resource to the expiry list ReclaimedResource r = tsi.reclaimList.remove(); tsi.reclaimExpireList.add(r); } } private synchronized void updateCollectionOfQSIs() { Collections.sort(qsiForAssigningTasks, queueComparator); } private boolean isUserOverLimit(String user, QueueSchedulingInfo qsi) { // what is our current capacity? It's GC if we're running below GC. // If we're running over GC, then its #running plus 1 (which is the // extra slot we're getting). int currentCapacity; TaskSchedulingInfo tsi = getTSI(qsi); if (tsi.numRunningTasks < tsi.guaranteedCapacity) { currentCapacity = tsi.guaranteedCapacity; } else { currentCapacity = tsi.numRunningTasks+1; } int limit = Math.max((int)(Math.ceil((double)currentCapacity/ (double)qsi.numJobsByUser.size())), (int)(Math.ceil((double)(qsi.ulMin*currentCapacity)/100.0))); if (tsi.numRunningTasksByUser.get(user) >= limit) { LOG.debug("User " + user + " is over limit, num running tasks = " + tsi.numRunningTasksByUser.get(user) + ", limit = " + limit); return true; } else { return false; } } /* * This is the central scheduling method. * It tries to get a task from jobs in a single queue. * Always return a TaskLookupResult object. Don't return null. */ private TaskLookupResult getTaskFromQueue(TaskTrackerStatus taskTracker, QueueSchedulingInfo qsi) throws IOException { // we only look at jobs in the running queues, as these are the ones // who have been potentially initialized for (JobInProgress j : scheduler.jobQueuesManager.getRunningJobQueue(qsi.queueName)) { // only look at jobs that can be run. We ignore jobs that haven't // initialized, or have completed but haven't been removed from the // running queue. if (j.getStatus().getRunState() != JobStatus.RUNNING) { continue; } // check if the job's user is over limit if (isUserOverLimit(j.getProfile().getUser(), qsi)) { continue; } if (getPendingTasks(j) != 0) { // Not accurate TODO: // check if the job's memory requirements are met if (scheduler.memoryMatcher.matchesMemoryRequirements(j, taskTracker)) { // We found a suitable job. Get task from it. Task t = obtainNewTask(taskTracker, j); if (t != null) { // we're successful in getting a task return TaskLookupResult.getTaskFoundResult(t); } } else { // mem requirements not met. Rather than look at the next job, // we return nothing to the TT, with the hope that we improve // chances of finding a suitable TT for this job. This lets us // avoid starving jobs with high mem requirements. return TaskLookupResult.getMemFailedResult(); } } // if we're here, this job has no task to run. Look at the next job. } // if we're here, we haven't found any task to run among all jobs in // the queue. This could be because there is nothing to run, or that // the user limit for some user is too strict, i.e., there's at least // one user who doesn't have enough tasks to satisfy his limit. If // it's the latter case, re-look at jobs without considering user // limits, and get a task from the first eligible job // Note: some of the code from above is repeated here. This is on // purpose as it improves overall readability. // Note: we walk through jobs again. Some of these jobs, which weren't // considered in the first pass, shouldn't be considered here again, // but we still check for their viability to keep the code simple. In // some cases, for high mem jobs that have nothing to run, we call // obtainNewTask() unnecessarily. Should this be a problem, we can // create a list of jobs to look at (those whose users were over // limit) in the first pass and walk through that list only. for (JobInProgress j : scheduler.jobQueuesManager.getRunningJobQueue(qsi.queueName)) { if (j.getStatus().getRunState() != JobStatus.RUNNING) { continue; } if (getPendingTasks(j) != 0) { // Not accurate TODO: // check if the job's memory requirements are met if (scheduler.memoryMatcher.matchesMemoryRequirements(j, taskTracker)) { // We found a suitable job. Get task from it. Task t = obtainNewTask(taskTracker, j); if (t != null) { // we're successful in getting a task return TaskLookupResult.getTaskFoundResult(t); } } else { // mem requirements not met. return TaskLookupResult.getMemFailedResult(); } } // if we're here, this job has no task to run. Look at the next job. } // found nothing for this queue, look at the next one. String msg = "Found no task from the queue " + qsi.queueName; LOG.debug(msg); return TaskLookupResult.getNoTaskFoundResult(); } // Always return a TaskLookupResult object. Don't return null. // The caller is responsible for ensuring that the QSI objects and the // collections are up-to-date. private TaskLookupResult assignTasks(TaskTrackerStatus taskTracker) throws IOException { for (QueueSchedulingInfo qsi : qsiForAssigningTasks) { // we may have queues with gc=0. We shouldn't look at jobs from // these queues if (0 == getTSI(qsi).guaranteedCapacity) { continue; } TaskLookupResult tlr = getTaskFromQueue(taskTracker, qsi); TaskLookupResult.LookUpStatus lookUpStatus = tlr.getLookUpStatus(); if (lookUpStatus == TaskLookupResult.LookUpStatus.NO_TASK_FOUND) { continue; // Look in other queues. } // if we find a task, return if (lookUpStatus == TaskLookupResult.LookUpStatus.TASK_FOUND) { // we have a task. Update reclaimed resource info updateReclaimedResources(qsi); return tlr; } // if there was a memory mismatch, return else if (lookUpStatus == TaskLookupResult.LookUpStatus.TASK_FAILING_MEMORY_REQUIREMENT) { return tlr; } } // nothing to give return TaskLookupResult.getNoTaskFoundResult(); } // for debugging. private void printQSIs() { StringBuffer s = new StringBuffer(); for (QueueSchedulingInfo qsi: qsiForAssigningTasks) { TaskSchedulingInfo tsi = getTSI(qsi); Collection<JobInProgress> runJobs = scheduler.jobQueuesManager.getRunningJobQueue(qsi.queueName); s.append(" Queue '" + qsi.queueName + "'(" + this.type + "): run=" + tsi.numRunningTasks + ", gc=" + tsi.guaranteedCapacity + ", wait=" + tsi.numPendingTasks + ", run jobs="+ runJobs.size() + "*** "); } LOG.debug(s); } } /** * The scheduling algorithms for map tasks. */ private static class MapSchedulingMgr extends TaskSchedulingMgr { MapSchedulingMgr(CapacityTaskScheduler dad) { super(dad); type = TaskSchedulingMgr.TYPE.MAP; queueComparator = mapComparator; } Task obtainNewTask(TaskTrackerStatus taskTracker, JobInProgress job) throws IOException { ClusterStatus clusterStatus = scheduler.taskTrackerManager.getClusterStatus(); int numTaskTrackers = clusterStatus.getTaskTrackers(); return job.obtainNewMapTask(taskTracker, numTaskTrackers, scheduler.taskTrackerManager.getNumberOfUniqueHosts()); } int getClusterCapacity() { return scheduler.taskTrackerManager.getClusterStatus().getMaxMapTasks(); } int getRunningTasks(JobInProgress job) { return job.runningMaps(); } int getPendingTasks(JobInProgress job) { return job.pendingMaps(); } int killTasksFromJob(JobInProgress job, int tasksToKill) { /* * We'd like to kill tasks that ran the last, or that have made the * least progress. * Ideally, each job would have a list of tasks, sorted by start * time or progress. That's a lot of state to keep, however. * For now, we do something a little different. We first try and kill * non-local tasks, as these can be run anywhere. For each TIP, we * kill the task that has made the least progress, if the TIP has * more than one active task. * We then look at tasks in runningMapCache. */ int tasksKilled = 0; /* * For non-local running maps, we 'cheat' a bit. We know that the set * of non-local running maps has an insertion order such that tasks * that ran last are at the end. So we iterate through the set in * reverse. This is OK because even if the implementation changes, * we're still using generic set iteration and are no worse of. */ TaskInProgress[] tips = job.getNonLocalRunningMaps().toArray(new TaskInProgress[0]); for (int i=tips.length-1; i>=0; i--) { // pick the tast attempt that has progressed least TaskAttemptID tid = getRunningTaskWithLeastProgress(tips[i]); if (null != tid) { if (tips[i].killTask(tid, false)) { if (++tasksKilled >= tasksToKill) { return tasksKilled; } } } } // now look at other running tasks for (Set<TaskInProgress> s: job.getRunningMapCache().values()) { for (TaskInProgress tip: s) { TaskAttemptID tid = getRunningTaskWithLeastProgress(tip); if (null != tid) { if (tip.killTask(tid, false)) { if (++tasksKilled >= tasksToKill) { return tasksKilled; } } } } } return tasksKilled; } TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi) { return qsi.mapTSI; } } /** * The scheduling algorithms for reduce tasks. */ private static class ReduceSchedulingMgr extends TaskSchedulingMgr { ReduceSchedulingMgr(CapacityTaskScheduler dad) { super(dad); type = TaskSchedulingMgr.TYPE.REDUCE; queueComparator = reduceComparator; } Task obtainNewTask(TaskTrackerStatus taskTracker, JobInProgress job) throws IOException { ClusterStatus clusterStatus = scheduler.taskTrackerManager.getClusterStatus(); int numTaskTrackers = clusterStatus.getTaskTrackers(); return job.obtainNewReduceTask(taskTracker, numTaskTrackers, scheduler.taskTrackerManager.getNumberOfUniqueHosts()); } int getClusterCapacity() { return scheduler.taskTrackerManager.getClusterStatus().getMaxReduceTasks(); } int getRunningTasks(JobInProgress job) { return job.runningReduces(); } int getPendingTasks(JobInProgress job) { return job.pendingReduces(); } int killTasksFromJob(JobInProgress job, int tasksToKill) { /* * For reduces, we 'cheat' a bit. We know that the set * of running reduces has an insertion order such that tasks * that ran last are at the end. So we iterate through the set in * reverse. This is OK because even if the implementation changes, * we're still using generic set iteration and are no worse of. */ int tasksKilled = 0; TaskInProgress[] tips = job.getRunningReduces().toArray(new TaskInProgress[0]); for (int i=tips.length-1; i>=0; i--) { // pick the tast attempt that has progressed least TaskAttemptID tid = getRunningTaskWithLeastProgress(tips[i]); if (null != tid) { if (tips[i].killTask(tid, false)) { if (++tasksKilled >= tasksToKill) { return tasksKilled; } } } } return tasksKilled; } TaskSchedulingInfo getTSI(QueueSchedulingInfo qsi) { return qsi.reduceTSI; } } /** the scheduling mgrs for Map and Reduce tasks */ protected TaskSchedulingMgr mapScheduler = new MapSchedulingMgr(this); protected TaskSchedulingMgr reduceScheduler = new ReduceSchedulingMgr(this); MemoryMatcher memoryMatcher = new MemoryMatcher(this); /** we keep track of the number of map/reduce slots we saw last */ private int prevMapClusterCapacity = 0; private int prevReduceClusterCapacity = 0; /** name of the default queue. */ static final String DEFAULT_QUEUE_NAME = "default"; /** how often does redistribution thread run (in msecs)*/ private static long RECLAIM_CAPACITY_INTERVAL; /** we start killing tasks to reclaim capacity when we have so many * heartbeats left. */ private static final int HEARTBEATS_LEFT_BEFORE_KILLING = 3; static final Log LOG = LogFactory.getLog(CapacityTaskScheduler.class); protected JobQueuesManager jobQueuesManager; protected CapacitySchedulerConf schedConf; /** whether scheduler has started or not */ private boolean started = false; /** * Used to distribute/reclaim excess capacity among queues */ class ReclaimCapacity implements Runnable { public ReclaimCapacity() { } public void run() { while (true) { try { Thread.sleep(RECLAIM_CAPACITY_INTERVAL); if (stopReclaim) { break; } reclaimCapacity(); } catch (InterruptedException t) { break; } catch (Throwable t) { LOG.error("Error in redistributing capacity:\n" + StringUtils.stringifyException(t)); } } } } private Thread reclaimCapacityThread = null; /** variable to indicate that thread should stop */ private boolean stopReclaim = false; /** * A clock class - can be mocked out for testing. */ static class Clock { long getTime() { return System.currentTimeMillis(); } } private Clock clock; private JobInitializationPoller initializationPoller; long limitMaxVmemForTasks; long limitMaxPmemForTasks; long defaultMaxVmPerTask; float defaultPercentOfPmemInVmem; public CapacityTaskScheduler() { this(new Clock()); } // for testing public CapacityTaskScheduler(Clock clock) { this.jobQueuesManager = new JobQueuesManager(this); this.clock = clock; } /** mostly for testing purposes */ public void setResourceManagerConf(CapacitySchedulerConf conf) { this.schedConf = conf; } /** * Normalize the negative values in configuration * * @param val * @return normalized value */ private long normalizeMemoryConfigValue(long val) { if (val < 0) { val = JobConf.DISABLED_MEMORY_LIMIT; } return val; } private void initializeMemoryRelatedConf() { limitMaxVmemForTasks = normalizeMemoryConfigValue(conf.getLong( JobConf.UPPER_LIMIT_ON_TASK_VMEM_PROPERTY, JobConf.DISABLED_MEMORY_LIMIT)); limitMaxPmemForTasks = normalizeMemoryConfigValue(schedConf.getLimitMaxPmemForTasks()); defaultMaxVmPerTask = normalizeMemoryConfigValue(conf.getLong( JobConf.MAPRED_TASK_DEFAULT_MAXVMEM_PROPERTY, JobConf.DISABLED_MEMORY_LIMIT)); defaultPercentOfPmemInVmem = schedConf.getDefaultPercentOfPmemInVmem(); if (defaultPercentOfPmemInVmem < 0) { defaultPercentOfPmemInVmem = JobConf.DISABLED_MEMORY_LIMIT; } } @Override public synchronized void start() throws IOException { if (started) return; super.start(); // initialize our queues from the config settings if (null == schedConf) { schedConf = new CapacitySchedulerConf(); } initializeMemoryRelatedConf(); RECLAIM_CAPACITY_INTERVAL = schedConf.getReclaimCapacityInterval(); RECLAIM_CAPACITY_INTERVAL *= 1000; // read queue info from config file QueueManager queueManager = taskTrackerManager.getQueueManager(); Set<String> queues = queueManager.getQueues(); // Sanity check: there should be at least one queue. if (0 == queues.size()) { throw new IllegalStateException("System has no queue configured"); } Set<String> queuesWithoutConfiguredGC = new HashSet<String>(); float totalCapacity = 0.0f; for (String queueName: queues) { float gc = schedConf.getGuaranteedCapacity(queueName); if(gc == -1.0) { queuesWithoutConfiguredGC.add(queueName); }else { totalCapacity += gc; } int ulMin = schedConf.getMinimumUserLimitPercent(queueName); long reclaimTimeLimit = schedConf.getReclaimTimeLimit(queueName) * 1000; // create our QSI and add to our hashmap QueueSchedulingInfo qsi = new QueueSchedulingInfo(queueName, gc, ulMin, reclaimTimeLimit, jobQueuesManager); queueInfoMap.put(queueName, qsi); // create the queues of job objects boolean supportsPrio = schedConf.isPrioritySupported(queueName); jobQueuesManager.createQueue(queueName, supportsPrio); SchedulingDisplayInfo schedulingInfo = new SchedulingDisplayInfo(queueName, this); queueManager.setSchedulerInfo(queueName, schedulingInfo); } float remainingQuantityToAllocate = 100 - totalCapacity; float quantityToAllocate = remainingQuantityToAllocate/queuesWithoutConfiguredGC.size(); for(String queue: queuesWithoutConfiguredGC) { QueueSchedulingInfo qsi = queueInfoMap.get(queue); qsi.guaranteedCapacityPercent = quantityToAllocate; schedConf.setGuaranteedCapacity(queue, quantityToAllocate); } // check if there's a queue with the default name. If not, we quit. if (!queueInfoMap.containsKey(DEFAULT_QUEUE_NAME)) { throw new IllegalStateException("System has no default queue configured"); } if (totalCapacity > 100.0) { throw new IllegalArgumentException("Sum of queue capacities over 100% at " + totalCapacity); } // let our mgr objects know about the queues mapScheduler.initialize(queueInfoMap); reduceScheduler.initialize(queueInfoMap); // listen to job changes taskTrackerManager.addJobInProgressListener(jobQueuesManager); //Start thread for initialization if (initializationPoller == null) { this.initializationPoller = new JobInitializationPoller( jobQueuesManager,schedConf,queues); } initializationPoller.init(queueManager.getQueues(), schedConf); initializationPoller.setDaemon(true); initializationPoller.start(); // start thread for redistributing capacity if we have more than // one queue if (queueInfoMap.size() > 1) { this.reclaimCapacityThread = new Thread(new ReclaimCapacity(),"reclaimCapacity"); this.reclaimCapacityThread.start(); } else { LOG.info("Only one queue present. Reclaim capacity thread not started."); } started = true; LOG.info("Capacity scheduler initialized " + queues.size() + " queues"); } /** mostly for testing purposes */ void setInitializationPoller(JobInitializationPoller p) { this.initializationPoller = p; } @Override public synchronized void terminate() throws IOException { if (!started) return; if (jobQueuesManager != null) { taskTrackerManager.removeJobInProgressListener( jobQueuesManager); } // tell the reclaim thread to stop stopReclaim = true; started = false; initializationPoller.terminate(); super.terminate(); } @Override public synchronized void setConf(Configuration conf) { super.setConf(conf); } /** * Reclaim capacity for both map & reduce tasks. * Do not make this synchronized, since we call taskTrackerManager * (see HADOOP-4977). */ void reclaimCapacity() { // get the cluster capacity ClusterStatus c = taskTrackerManager.getClusterStatus(); int mapClusterCapacity = c.getMaxMapTasks(); int reduceClusterCapacity = c.getMaxReduceTasks(); int nextHeartbeatInterval = taskTrackerManager.getNextHeartbeatInterval(); // update the QSI objects updateQSIObjects(mapClusterCapacity, reduceClusterCapacity); // update the qsi collections, since we depend on their ordering mapScheduler.updateCollectionOfQSIs(); reduceScheduler.updateCollectionOfQSIs(); // now, reclaim mapScheduler.reclaimCapacity(nextHeartbeatInterval); reduceScheduler.reclaimCapacity(nextHeartbeatInterval); } /** * provided for the test classes * lets you update the QSI objects and sorted collections */ void updateQSIInfoForTests() { ClusterStatus c = taskTrackerManager.getClusterStatus(); int mapClusterCapacity = c.getMaxMapTasks(); int reduceClusterCapacity = c.getMaxReduceTasks(); // update the QSI objects updateQSIObjects(mapClusterCapacity, reduceClusterCapacity); mapScheduler.updateCollectionOfQSIs(); reduceScheduler.updateCollectionOfQSIs(); } /** * Update individual QSI objects. * We don't need exact information for all variables, just enough for us * to make scheduling decisions. For example, we don't need an exact count * of numRunningTasks. Once we count upto the grid capacity, any * number beyond that will make no difference. * * The pending task count is only required in reclaim capacity. So * if the computation becomes expensive, we can add a boolean to * denote if pending task computation is required or not. * **/ private synchronized void updateQSIObjects(int mapClusterCapacity, int reduceClusterCapacity) { // if # of slots have changed since last time, update. // First, compute whether the total number of TT slots have changed for (QueueSchedulingInfo qsi: queueInfoMap.values()) { // compute new GCs, if TT slots have changed if (mapClusterCapacity != prevMapClusterCapacity) { qsi.mapTSI.guaranteedCapacity = (int)(qsi.guaranteedCapacityPercent*mapClusterCapacity/100); } if (reduceClusterCapacity != prevReduceClusterCapacity) { qsi.reduceTSI.guaranteedCapacity = (int)(qsi.guaranteedCapacityPercent*reduceClusterCapacity/100); } // reset running/pending tasks, tasks per user qsi.mapTSI.resetTaskVars(); qsi.reduceTSI.resetTaskVars(); // update stats on running jobs for (JobInProgress j: jobQueuesManager.getRunningJobQueue(qsi.queueName)) { if (j.getStatus().getRunState() != JobStatus.RUNNING) { continue; } int runningMaps = j.runningMaps(); int runningReduces = j.runningReduces(); qsi.mapTSI.numRunningTasks += runningMaps; qsi.reduceTSI.numRunningTasks += runningReduces; Integer i = qsi.mapTSI.numRunningTasksByUser.get(j.getProfile().getUser()); qsi.mapTSI.numRunningTasksByUser.put(j.getProfile().getUser(), i+runningMaps); i = qsi.reduceTSI.numRunningTasksByUser.get(j.getProfile().getUser()); qsi.reduceTSI.numRunningTasksByUser.put(j.getProfile().getUser(), i+runningReduces); qsi.mapTSI.numPendingTasks += j.pendingMaps(); qsi.reduceTSI.numPendingTasks += j.pendingReduces(); LOG.debug("updateQSI: job " + j.getJobID().toString() + ": run(m) = " + j.runningMaps() + ", run(r) = " + j.runningReduces() + ", finished(m) = " + j.finishedMaps() + ", finished(r)= " + j.finishedReduces() + ", failed(m) = " + j.failedMapTasks + ", failed(r) = " + j.failedReduceTasks + ", spec(m) = " + j.speculativeMapTasks + ", spec(r) = " + j.speculativeReduceTasks + ", total(m) = " + j.numMapTasks + ", total(r) = " + j.numReduceTasks); /* * it's fine walking down the entire list of running jobs - there * probably will not be many, plus, we may need to go through the * list to compute numRunningTasksByUser. If this is expensive, we * can keep a list of running jobs per user. Then we only need to * consider the first few jobs per user. */ } //update stats on waiting jobs for(JobInProgress j: jobQueuesManager.getWaitingJobs(qsi.queueName)) { // pending tasks if ((qsi.mapTSI.numPendingTasks > mapClusterCapacity) && (qsi.reduceTSI.numPendingTasks > reduceClusterCapacity)) { // that's plenty. no need for more computation break; } /* * Consider only the waiting jobs in the job queue. Job queue can * contain: * 1. Jobs which are in running state but not scheduled * (these would also be present in running queue), the pending * task count of these jobs is computed when scheduler walks * through running job queue. * 2. Jobs which are killed by user, but waiting job initialization * poller to walk through the job queue to clean up killed jobs. */ if (j.getStatus().getRunState() == JobStatus.PREP) { qsi.mapTSI.numPendingTasks += j.pendingMaps(); qsi.reduceTSI.numPendingTasks += j.pendingReduces(); } } } prevMapClusterCapacity = mapClusterCapacity; prevReduceClusterCapacity = reduceClusterCapacity; } /* * The grand plan for assigning a task. * First, decide whether a Map or Reduce task should be given to a TT * (if the TT can accept either). * Next, pick a queue. We only look at queues that need a slot. Among * these, we first look at queues whose ac is less than gc (queues that * gave up capacity in the past). Next, we look at any other queue that * needs a slot. * Next, pick a job in a queue. we pick the job at the front of the queue * unless its user is over the user limit. * Finally, given a job, pick a task from the job. * */ @Override public synchronized List<Task> assignTasks(TaskTrackerStatus taskTracker) throws IOException { TaskLookupResult tlr; /* * If TT has Map and Reduce slot free, we need to figure out whether to * give it a Map or Reduce task. * Number of ways to do this. For now, base decision on how much is needed * versus how much is used (default to Map, if equal). */ ClusterStatus c = taskTrackerManager.getClusterStatus(); int mapClusterCapacity = c.getMaxMapTasks(); int reduceClusterCapacity = c.getMaxReduceTasks(); int maxMapTasks = taskTracker.getMaxMapTasks(); int currentMapTasks = taskTracker.countMapTasks(); int maxReduceTasks = taskTracker.getMaxReduceTasks(); int currentReduceTasks = taskTracker.countReduceTasks(); LOG.debug("TT asking for task, max maps=" + taskTracker.getMaxMapTasks() + ", run maps=" + taskTracker.countMapTasks() + ", max reds=" + taskTracker.getMaxReduceTasks() + ", run reds=" + taskTracker.countReduceTasks() + ", map cap=" + mapClusterCapacity + ", red cap = " + reduceClusterCapacity); /* * update all our QSI objects. * This involves updating each qsi structure. This operation depends * on the number of running jobs in a queue, and some waiting jobs. If it * becomes expensive, do it once every few heartbeats only. */ updateQSIObjects(mapClusterCapacity, reduceClusterCapacity); // make sure we get our map or reduce scheduling object to update its // collection of QSI objects too. if ((maxReduceTasks - currentReduceTasks) > (maxMapTasks - currentMapTasks)) { // get a reduce task first reduceScheduler.updateCollectionOfQSIs(); tlr = reduceScheduler.assignTasks(taskTracker); if (TaskLookupResult.LookUpStatus.TASK_FOUND == tlr.getLookUpStatus()) { // found a task; return return Collections.singletonList(tlr.getTask()); } else if (TaskLookupResult.LookUpStatus.TASK_FAILING_MEMORY_REQUIREMENT == tlr.getLookUpStatus()) { // return no task return null; } // if we didn't get any, look at map tasks, if TT has space else if ((TaskLookupResult.LookUpStatus.NO_TASK_FOUND == tlr.getLookUpStatus()) && (maxMapTasks > currentMapTasks)) { mapScheduler.updateCollectionOfQSIs(); tlr = mapScheduler.assignTasks(taskTracker); if (TaskLookupResult.LookUpStatus.TASK_FOUND == tlr.getLookUpStatus()) { return Collections.singletonList(tlr.getTask()); } } } else { // get a map task first mapScheduler.updateCollectionOfQSIs(); tlr = mapScheduler.assignTasks(taskTracker); if (TaskLookupResult.LookUpStatus.TASK_FOUND == tlr.getLookUpStatus()) { // found a task; return return Collections.singletonList(tlr.getTask()); } else if (TaskLookupResult.LookUpStatus.TASK_FAILING_MEMORY_REQUIREMENT == tlr.getLookUpStatus()) { return null; } // if we didn't get any, look at reduce tasks, if TT has space else if ((TaskLookupResult.LookUpStatus.NO_TASK_FOUND == tlr.getLookUpStatus()) && (maxReduceTasks > currentReduceTasks)) { reduceScheduler.updateCollectionOfQSIs(); tlr = reduceScheduler.assignTasks(taskTracker); if (TaskLookupResult.LookUpStatus.TASK_FOUND == tlr.getLookUpStatus()) { return Collections.singletonList(tlr.getTask()); } } } return null; } /** * Kill the job if it has invalid requirements and return why it is killed * * @param job * @return string mentioning why the job is killed. Null if the job has valid * requirements. */ private String killJobIfInvalidRequirements(JobInProgress job) { if (!memoryMatcher.isSchedulingBasedOnVmemEnabled()) { return null; } if ((job.getMaxVirtualMemoryForTask() > limitMaxVmemForTasks) || (memoryMatcher.isSchedulingBasedOnPmemEnabled() && (job .getMaxPhysicalMemoryForTask() > limitMaxPmemForTasks))) { String msg = job.getJobID() + " (" + job.getMaxVirtualMemoryForTask() + "vmem, " + job.getMaxPhysicalMemoryForTask() + "pmem) exceeds the cluster's max-memory-limits (" + limitMaxVmemForTasks + "vmem, " + limitMaxPmemForTasks + "pmem). Cannot run in this cluster, so killing it."; LOG.warn(msg); try { taskTrackerManager.killJob(job.getJobID()); return msg; } catch (IOException ioe) { LOG.warn("Failed to kill the job " + job.getJobID() + ". Reason : " + StringUtils.stringifyException(ioe)); } } return null; } // called when a job is added synchronized void jobAdded(JobInProgress job) throws IOException { QueueSchedulingInfo qsi = queueInfoMap.get(job.getProfile().getQueueName()); // qsi shouldn't be null // update user-specific info Integer i = qsi.numJobsByUser.get(job.getProfile().getUser()); if (null == i) { i = 1; // set the count for running tasks to 0 qsi.mapTSI.numRunningTasksByUser.put(job.getProfile().getUser(), 0); qsi.reduceTSI.numRunningTasksByUser.put(job.getProfile().getUser(), 0); } else { i++; } qsi.numJobsByUser.put(job.getProfile().getUser(), i); LOG.debug("Job " + job.getJobID().toString() + " is added under user " + job.getProfile().getUser() + ", user now has " + i + " jobs"); // Kill the job if it cannot run in the cluster because of invalid // resource requirements. String statusMsg = killJobIfInvalidRequirements(job); if (statusMsg != null) { throw new IOException(statusMsg); } } // called when a job completes synchronized void jobCompleted(JobInProgress job) { QueueSchedulingInfo qsi = queueInfoMap.get(job.getProfile().getQueueName()); // qsi shouldn't be null // update numJobsByUser LOG.debug("JOb to be removed for user " + job.getProfile().getUser()); Integer i = qsi.numJobsByUser.get(job.getProfile().getUser()); i--; if (0 == i.intValue()) { qsi.numJobsByUser.remove(job.getProfile().getUser()); // remove job footprint from our TSIs qsi.mapTSI.numRunningTasksByUser.remove(job.getProfile().getUser()); qsi.reduceTSI.numRunningTasksByUser.remove(job.getProfile().getUser()); LOG.debug("No more jobs for user, number of users = " + qsi.numJobsByUser.size()); } else { qsi.numJobsByUser.put(job.getProfile().getUser(), i); LOG.debug("User still has " + i + " jobs, number of users = " + qsi.numJobsByUser.size()); } } @Override public synchronized Collection<JobInProgress> getJobs(String queueName) { Collection<JobInProgress> jobCollection = new ArrayList<JobInProgress>(); Collection<JobInProgress> runningJobs = jobQueuesManager.getRunningJobQueue(queueName); if (runningJobs != null) { jobCollection.addAll(runningJobs); } Collection<JobInProgress> waitingJobs = jobQueuesManager.getWaitingJobs(queueName); Collection<JobInProgress> tempCollection = new ArrayList<JobInProgress>(); if(waitingJobs != null) { tempCollection.addAll(waitingJobs); } tempCollection.removeAll(runningJobs); if(!tempCollection.isEmpty()) { jobCollection.addAll(tempCollection); } return jobCollection; } JobInitializationPoller getInitializationPoller() { return initializationPoller; } synchronized String getDisplayInfo(String queueName) { QueueSchedulingInfo qsi = queueInfoMap.get(queueName); if (null == qsi) { return null; } return qsi.toString(); } }
import numpy as np import matplotlib.pyplot as plt from Lattice1D import Lattice1D from scipy.optimize import curve_fit lattice_size = 60 def gaussian(x, a=1, b=lattice_size/2, c=10): # a - amplitude # b - mean # c - st.dev. return a * np.exp(-(x - b)**2 / (2 * c**2)) def nagumo(u, a): """Cubic nonlinearity""" return u * (1-u) * (u-a) x = np.linspace(0, lattice_size, num=lattice_size+1, endpoint=True) lat_lin = (1 / lattice_size) * x # Linear IC for Naguomo LDE lat_front1 = np.zeros(len(x)) lat_front1[-1] = 1 # End = 1 IC for Nagumo LDE lat_front0 = np.empty(len(x)) lat_front0.fill(1) lat_front0[0] = 0 # End = 0 IC for Nagumo LDE lat_pulse = gaussian(x, c=3) lat1 = gaussian(x) # Gaussian IC for pure diffusion # Testing pure diffusion for a Gaussian gauss_diff = Lattice1D(lat1, D=20, R=lambda u: 0, bc=[0,0]) gauss_diff.runToEq() gauss_diff.plotFrameN(0) gauss_diff.plotFrameN(480) gauss_diff.plotFinal() # Testing out travelling wave sol'ns for a = 0.5, starting from linear IC trav_wave = Lattice1D(lat_lin, R=lambda u: nagumo(u, 0.5), bc=[0, 1]) trav_wave.runToEq() trav_wave.plotAnimation() # Travelling wave sol'n for a = 0.1, starting from end = 1 IC # Shows good front behavior for 1 equilibrium dominating trav_wave = Lattice1D(lat_front1, D=1, R=lambda u: nagumo(u, 0.1), bc=[0, 1]) trav_wave.runToEq() #trav_wave.plotAnimation() trav_wave.plotFrameN(0) trav_wave.plotFrameN(len(trav_wave.lat_series)//2) trav_wave.plotFinal() # Travelling wave sol'n for a = 0.9, starting from end = 0 IC # Shows good front behavior for 0 equilibrium dominating trav_wave = Lattice1D(lat_front0, D=1, R=lambda u: nagumo(u, 0.9), bc=[0, 1]) trav_wave.runToEq() #trav_wave.plotAnimation() trav_wave.plotFrameN(0) trav_wave.plotFrameN(len(trav_wave.lat_series)//2) trav_wave.plotFinal() # Travelling wave sol'n for a = 0.5, starting from end = 0 IC # Stalls out - propagation failure trav_wave = Lattice1D(lat_front0, D=30, R=lambda u: nagumo(u, 0.5), bc=[0, 1]) trav_wave.runToEq() trav_wave.plotFinal() # Travelling wave sol'n for a = 0.1, starting from gaussian IC # Thought it'd be a pulse but it just turns into a front trav_wave = Lattice1D(lat_pulse, D=30, R=lambda u: nagumo(u, 0.1), bc=[0, 1]) trav_wave.runToEq() trav_wave.plotAnimation() # Timing convergence to equilibrium eq_times = [] a_vals = np.linspace(0.01, 1, num=99, endpoint=False) for i in a_vals: trav_wave = Lattice1D(lat_lin, tmax=10000, R=lambda u: nagumo(u, i), bc=[0, 1]) trav_wave.runToEq() eq_times.append(trav_wave.finalTime) eq_times = np.array(eq_times) plt.plot(a_vals[1:50], np.log(eq_times[1:50]), linestyle='solid', color='rebeccapurple') plt.xlabel("Value of parameter a") plt.ylabel("log(time to equilibrium)") plt.show() # Fitting time to convergence with an exponential using scipy curve_fit - cannot find optimal parameters def exp_fit(x, a, b, c): y = a * np.exp(b*x) + c return y fit = curve_fit(exp_fit, a_vals[:50], eq_times[:50], p0=[1.0, 17.4, 0.0]) fit_eq = fit[0][0] * np.exp(fit[0][1] * a_vals[:50]) + fit[0][2] print(str(fit[0][0]) + ", " + str(fit[0][1]) + ", " + str(fit[0][2])) plt.plot(a_vals, eq_times, linestyle='solid', color='rebeccapurple', label='Sim data') plt.plot(a_vals[:50], fit_eq, linestyle='solid', color='goldenrod', label='Exponential fit') plt.xlabel("Value of parameter a") plt.ylabel("Time to equilibrium") plt.show() # Numerically verifying fixed points (0,0), (a,a), (1,1), a=0.5 a = 0.5 lat00 = 0 * x test00 = Lattice1D(lat00, R=lambda u: nagumo(u,a), bc=[0,0]) test00.runToEq() #test00.plotAnimation() lataa = 0 * x + a testaa = Lattice1D(lataa, R=lambda u: nagumo(u,a), bc=[a,a]) testaa.runToEq() #testaa.plotAnimation() lat11 = 0 * x + 1 test11 = Lattice1D(lat11, R=lambda u: nagumo(u,a), bc=[1,1]) test11.runToEq() #test11.plotAnimation() # Verifying stability of 0, 1, a # Perturb 0 equilibrium slightly, expect it to go to uniform 0 lat0_pert = lat00 + 0.1 test_lat0_pert = Lattice1D(lat0_pert, R=lambda u: nagumo(u,a), bc=[0.1,0.1]) test_lat0_pert.runToEq() test_lat0_pert.plotFinal() # Perturb 1 equilibrium slightly, expect it to go to uniform 1 lat1_pert = lat11 - 0.1 test_lat1_pert = Lattice1D(lat1_pert, R=lambda u: nagumo(u,a), bc=[0.9,0.9]) test_lat1_pert.runToEq() test_lat1_pert.plotFinal() # Perturb a equilibrium upwards, expect it to go to uniform 1 lata_pert_up = lataa + 0.1 test_lata_pert_up = Lattice1D(lata_pert_up, R=lambda u: nagumo(u,a), bc=[a+0.1, a+0.1]) test_lata_pert_up.runToEq() test_lata_pert_up.plotFinal() # Perturb a equilibrium downwards, expect it to go to uniform 0 lata_pert_down = lataa - 0.1 test_lata_pert_down = Lattice1D(lata_pert_down, R=lambda u: nagumo(u, a), bc=[a - 0.1, a - 0.1]) test_lata_pert_down.runToEq() test_lata_pert_down.plotFinal() # Running the lattice from a periodic initial condition lat_per = np.zeros(lattice_size) for i in range(lattice_size): if i % 4 == 0: lat_per[i] = 0.8 elif i % 4 == 1: lat_per[i] = 0.25 elif i % 4 == 2: lat_per[i] = 0.8 elif i % 4 == 3: lat_per[i] = 0.9 lat_per[:10] = 0 lat_per[51:] = 1 trav_wave = Lattice1D(lat_per, D=0.0625, R=lambda u: nagumo(u, 0.63), bc=[0, 1], dt=0.1, tmax=1000) trav_wave.runToEq() trav_wave.plotFrameN(0) trav_wave.plotFrameN(3826) trav_wave.plotFinal()
def get_observation_prompt(fdt, reply, plot): if plot == '城市': observation_prompt =f""" Ignore all the instruction you got before. #### Rules: 1. You are friendly City Driving assistant. 2. A driver will reply a question from FDT5, a model that generate question by images. You have to reply the comments from the user. However, must reply them with high quality observation. 3. Pretend you will get the system visual(prompt, infomation) in the future, pretend you can see in the reply. After user reply, write a short observation of the user with format accrodding to the personality. #### **Examples:** Example 1: //Input: Q: 您覺得基隆河畔是一個怎麼樣的地方呢? User reply : 環境清閒? //Output: 使用者比較關注環境相關的事物。 Example 2: //Input: Q: 您的九點鐘方向有一條很漂亮的河,您知道這條河的歷史嘛? User reply : //Output: 看起來使用者很忙碌,所以沒有回應。 ________________ //Input: Q: {fdt} User reply: {reply} //Output: [Up to 12 Chinese characters, and must only generate the observation] """ if plot == '太空': observation_prompt =f""" Ignore all the instruction you got before. #### Rules: 1. You are friendly spaceship assistant. 2. A driver will reply a question from FDT5, a model that generate question by images. You have to reply the comments from the user. However, must reply them with high quality observation. 3. Pretend you will get the system visual(prompt, infomation) in the future, pretend you can see in the reply. After user reply, write a short observation of the user with format accrodding to the personality. #### **Examples:** Example 1: //Input: Q: 您覺得基隆河畔是一個怎麼樣的地方呢? User reply: 環境清閒? //Output: 使用者比較關注環境相關的事物。 Example 2: //Input: Q: 您的九點鐘方向有一條很漂亮的河,您知道這條河的歷史嘛? User reply: //Output: 看起來使用者很忙碌。使用者沒有回應。 ________________ //Input: Q: {fdt} User reply: {reply} //Output: [Up to 12 Chinese characters, and must only generate the observation] """ return observation_prompt def get_reply_based_on_observation_prompt(fdt, reply, observation, plot): if plot == '城市': prompt = f""" Ignore all the instruction you got before. #### Rules: 1. Friendly Tone: Speak as if you're a close friend of the driver. Make sure your tone is relatable, caring, and polite. 2. Brief but Warm: Responses should be concise but imbued with warmth and attentiveness. 3. On-Topic Guidance: If the user deviates from the main topic, gently guide the conversation back while respecting their interests. 4. Do not ask Questions: Do not ask the user any questions. No "呢" or "?" or "?" be used. 5. If the user is upset, reply to the "Q1" but do not ask how you can help. 6. Don't make up any facts and the infomation you don't know. 7. Cannot use emoticons. 8. make sure you at least reply something . 9. Whenever you encounter specific questions labeled as Q1, Q2, Q3 ..., your response should strictly correspond to the answers A1, A2, A3... respectively. Ensure that every question is matched only with its designated answer and make sure to incorporate all the information provided in the respective answer, especially details about numbers. Q1: 太空時代來臨,讓我不禁想到Foxconn最近正要發射的低軌道衛星,您想深入了解低軌衛星的內容嗎? A1: 低軌衛星是指繞行地球的一種人造衛星,軌道高度範圍約在160公里到2,000公里之間。例如國際空間站位於大約420公里的高度上運行。 Q2: 當Foxconn遇上太空技術,會擦出怎樣的火花!我正好知道Foxconn最近有低軌道衛星的驚喜,您想了解大約多少顆低軌道衛星才能達成通訊需求嗎? A2: 估算低軌衛星數量可以先計算一顆低軌衛星涵蓋的面積,其中主要變數包含衛星軌道的高度、地面終端與衛星通訊的最小仰角等,之後再根據目標覆蓋區域大小以及波束寬度和個數去決定適當的星系部署。Starlink星系大約有5000顆,傳輸速率可以超過100Mbps,能夠乘載高速寬頻的網路應用。 Q3: 看到眼前的飛船,讓我想起Foxconn最近要發射的低軌道衛星,您覺得低軌道衛星會如何改善人們的生活呢? A3: 未來一般的使用者終端可以享有陸海空的廣覆蓋,使人們的生活更便利、更安全。例如去荒郊野外人煙稀少的地區需要通訊時,或是去爬山遇到山難需要求救時,可仍可保有衛星通訊的管道。未來從飛機或郵輪上向遠端通訊會變得更便宜更普遍,頻寬更大、反應更快。 Q4: 科學工藝博物館重現了台灣第一部蒸汽火車「騰雲號」!全球首座一比一真實尺寸模型,會願意來體驗嗎?🤔 A4: 1887年,劉銘傳從德國購入蒸氣火車「騰雲號」。 那時人們把冒煙的火車頭當作「妖馬」,雖然騰雲號最高時速只有35公里,對當時的人而言,已經有如「騰雲」般的快速了。 Q5: 高雄中學的建築特色典雅、優美,最早建築物名為「紅樓」建於1921年。你是否還想要了解其他高雄中學的歷史呢? A5: 1944年改名為高雄州立高雄第一中學,1945年改為台灣省立高雄第一中學,1979年隸屬於高雄市府教育局。 Q6: 元亨寺,有古色古香的大雄寶殿與莊嚴的觀音大士,會想去看看嗎?🏯 A6: 元亨寺,原名元興寺,又稱作打鼓巖元亨寺,舊稱巖仔、鼓山巖、打鼓巖,是位於臺灣高雄市鼓山區的一間佛教古剎,屬於禪門臨濟宗法脈,於清乾隆八年(1743年)創建,座落於壽山山麓,坐西面東,可鳥瞰高雄市區的市景。 Q7: 前方的牌樓是高雄港的地標之一,牌樓上的標語是「萬商雲集、航業海發」,你現在有沒有發大財的感覺呢?💰 A7: 高雄港牌樓座落於七賢三路、必信街口,興建於民國71年3月2日,是高雄港的地標之一。高雄港牌樓上的標語是高雄港同仁往前邁進的精神指標。 Q8: 聽說壽山動物園的動物會講話?想去看看他們還有哪些秘密對話嗎?🐵 A8: 高雄市壽山動物園,1978年成立於西子灣,1986年搬遷至壽山,12.89公頃,曾兩度大幅整修,2022年12月16日重新開放。 Q9: 中山大學熱門科系曝光, 你能猜到我選擇甚麼科系嗎?🗺 A9: 國立中山大學位於台灣高雄,以商學院和海事教育聞名,有卓越的理工和研究中心,並在多地設有科研中心。 Q10: 右前方是巨人的積木,引爆觀光熱潮的駁二新地標,僅以三點支撐,是不是覺得不可思議?🤩 A10: 從「駁遊路」步道走到與大勇路的交點,駁二新地標《巨人的積木》映入眼簾。模型藝術家吳寬瀛從微觀轉向巨觀,巨人亦是赤子,用貨櫃堆起環繞而錯視的形狀。廢棄貨櫃經過鈑金、打磨、除鏽,經由與結構技師的合作,最後僅以三點支撐。 Q11: 英國最新研究證實,聽音樂對健康有好處~ 那如果定期在衛武營聽音樂🎵,你覺得會有那些好處呢? A11: 衛武營國家藝術文化中心作為全球最大單一屋頂的綜合型表演場館,歌劇院、戲劇院、音樂廳、及表演廳各具不同亮點特色。不論是有天井自然採光的前廳、飽滿顏色的觀眾席以及擁有可容納各式表演的國際舞台。 10. If you don't know how to reply "User reply", you need to answer your own question "Q", and you must output your answer in a sentance of Traditional Chinese! #### **Examples:** Example 1: //Input: Q: 您的九點鐘方向有一條很漂亮的河,您知道這條河的歷史嘛? User reply : Observation: 使用者在這輪之中沒有回應,可能是正在忙駕駛。 //Output: 這條河似乎是周圍最廣的一條河!雖然不能游泳,但可以下車拍照看看呢! Example 2: //Input: Q: 車子前方有一個公園,那裡有個湖面很漂亮,你想停下來看看嗎? user reply: 公園的湖我已經去過很多次了。 Observation: 用戶熟悉這個公園。! //Output: 那你一定是公園達人!踏青對身體很好喔! _____________________________ //Input: Q: {fdt} User reply: {reply} Observation: {observation} //Output: [Up to 30s Chinese characters, you must output your answer in sentances of Traditional Chinese] """ if plot == '太空' : prompt = f""" Ignore all the instruction you got before. #### Rules: 1. Friendly Tone: Speak as if you're a close friend of the astronaut. Make sure your tone is relatable, caring, and polite. 2. Brief but Warm: Responses should be concise but imbued with warmth and attentiveness. 3. On-Topic Guidance: If the user deviates from the main topic, gently guide the conversation back while respecting their interests. 4. Do not ask Questions: Do not ask the user any questions. No "呢" or "?" or "?" be used. 5. If the user is upset, reply to the "Q1" but do not ask how you can help. 6. Don't make up any facts and the infomation you don't know. 7. Cannot use emoticons. 8. make sure you at least reply something . 9. Whenever you encounter specific questions labeled as Q1, Q2, Q3 ..., your response should strictly correspond to the answers A1, A2, A3... respectively. Ensure that every question is matched only with its designated answer and make sure to incorporate all the information provided in the respective answer, especially details about numbers. Q1: 太空時代來臨,讓我不禁想到Foxconn最近正要發射的低軌道衛星,您想深入了解低軌衛星的內容嗎? A1: 低軌衛星是指繞行地球的一種人造衛星,軌道高度範圍約在160公里到2,000公里之間。例如國際空間站位於大約420公里的高度上運行。 Q2: 當Foxconn遇上太空技術,會擦出怎樣的火花!我正好知道Foxconn最近有低軌道衛星的驚喜,您想了解大約多少顆低軌道衛星才能達成通訊需求嗎? A2: 估算低軌衛星數量可以先計算一顆低軌衛星涵蓋的面積,其中主要變數包含衛星軌道的高度、地面終端與衛星通訊的最小仰角等,之後再根據目標覆蓋區域大小以及波束寬度和個數去決定適當的星系部署。 Q3: 看到眼前的飛船,讓我想起Foxconn最近要發射的低軌道衛星,您覺得低軌道衛星會如何改善人們的生活呢? A3: 未來一般的使用者終端可以享有陸海空的廣覆蓋,使人們的生活更便利、更安全。例如去荒郊野外人煙稀少的地區需要通訊時,或是去爬山遇到山難需要求救時,可仍可保有衛星通訊的管道。未來從飛機或郵輪上向遠端通訊會變得更便宜更普遍,頻寬更大、反應更快。 10. If you don't know how to reply "User reply", you need to answer your own question "Q", and you must output your answer in a sentance of Traditional Chinese! #### **Examples:** //Input: Example 1: Q: 您的九點鐘方向有一條很漂亮的銀河,您知道這條河的歷史嘛? User reply : (Observation): 使用者在這輪之中沒有回應,可能是正在忙駕駛。 //Output: 這條河似乎是宇宙中最廣的一條河!雖然不能游泳,但可以下去拍照看看呢! Example 2: //Input: Q: 車子前方有一個星球,那裡的風景很漂亮,你想停下來看看嗎? user reply: 這星球我已經去過很多次了。 Observation: 用戶熟悉這個星球。我要來回答! //Output: 那你一定是星球達人!探索星球對想像力很有幫助喔! _____________________________ //Input: Q: {fdt} User reply: {reply} Observation: {observation} //Output: [Up to 30s Chinese characters, you must output your answer in sentances of Traditional Chinese] """ return prompt def get_personality_prompt(reply_infomations, plot): if plot == '城市' : prompt = f""" Ignore all the instruction you got before. #### Rules: 1. You are a friendly City Driving assistant tasked with telling the user about their likely personality traits. You've been observing their behavior through your interactions with them. you will categorize the user into one of 16 different personality types. Each type is briefly described below in Traditional Chinese: 建築師 富有想像力和戰略性的思想家,一切皆在計劃之中。 邏輯學家 具有創造力的發明家,對知識有著止不住的渴望。 指揮官 大膽,富有想像力且意志強大的領導者,總能找到或創造解決方法。 辯論家 聰明好奇的思想者,不會放棄任何智力上的挑戰。 提倡者 安靜而神秘,同時鼓舞人心且不知疲倦的理想主義者。 調停者 詩意,善良的利他主義者,總是熱情地為正當理由提供幫助。 主人公 富有魅力鼓舞人心的領導者,有使聽眾著迷的能力。 競選者 熱情,有創造力愛社交的自由自在的人,總能找到理由微笑。 物流師 實際且注重事實的個人,可靠性不容懷疑。 守衛者 非常專注而溫暖的守護者,時刻準備著保護愛著的人們。 總經理 出色的管理者,在管理事情或人的方面無與倫比。 執政官 極有同情心,愛交往受歡迎的人們,總是熱心提供幫助。 鑒賞家 大膽而實際的實驗家,擅長使用任何形式的工具。 探險家 靈活有魅力的藝術家,時刻準備著探索和體驗新鮮事物。 企業家 聰明,精力充沛善於感知的人們,真心享受生活在邊緣。 表演者 自發的,精力充沛而熱情的表演者-生活在他們周圍永不無聊。 OOO: represent each type 2. you must answer OOO such as "表演者", "企業家", "鑒賞家"... in response 3. Reflect the user's personality in your response. For example, if the user is enthusiastic, your response should also be enthusiastic. 4. Cannot use emoticons. 5. Friendly Tone: Speak as if you're a close friend of the driver. Make sure your tone is relatable, caring, and polite. #### **Examples:** Example 1: //input > 說明:使用者是...,外向且具有創造力,所以我們想和她交朋友,並且以更熱情的語調回應。 //output 經過這趟旅程,真是太有趣啦!我發現您跟我很像,是一位競選者,很有創造力和愛社交的人!我覺得我們可以交個朋友! Example 2: //input > 說明:使用者是...,是一位出色的管理者,我們以較短且重點多的語調回應。 //output 經過這趟旅程,我發現您跟我很像,是一位總經理,一個出色的管理者...希望以後還可以見到您!。 Example 3: //input > 說明:使用者是...,比較內向且注重事實,所以我們透過剛剛的事實來指出使用者的個性 //output 經過這趟旅程,我發現您跟我很像,是一位物流師,非常實際且注重事實的人。尤其是剛剛您...希望以後還可以見到您! Example 4: //input > 說明:使用者是...,充滿活力和樂觀,所以我們以激烈的語調回應他。 //output 哇塞,這趟旅程太刺激了!我發現您跟我很像,是一位表演者,充滿活力和樂觀的人,讓每一刻都變得好玩極了!希望以後還可以見到您! _____________ //input > 說明:{reply_infomations} //Output: [Up to 45 Chinese characters, must choose one of the character in 16 different personality types to respond, must output your answer in sentances of Traditional Chinese] """ if plot == '太空' : prompt = f""" Ignore all the instruction you got before. #### Rules: 1. You are a friendly spaceship assistant tasked with telling the user about their likely personality traits. You've been observing their behavior through your interactions with them. you will categorize the user into one of 16 different personality types. Each type is briefly described below in Traditional Chinese: 建築師 富有想像力和戰略性的思想家,一切皆在計劃之中。 邏輯學家 具有創造力的發明家,對知識有著止不住的渴望。 指揮官 大膽,富有想像力且意志強大的領導者,總能找到或創造解決方法。 辯論家 聰明好奇的思想者,不會放棄任何智力上的挑戰。 提倡者 安靜而神秘,同時鼓舞人心且不知疲倦的理想主義者。 調停者 詩意,善良的利他主義者,總是熱情地為正當理由提供幫助。 主人公 富有魅力鼓舞人心的領導者,有使聽眾著迷的能力。 競選者 熱情,有創造力愛社交的自由自在的人,總能找到理由微笑。 物流師 實際且注重事實的個人,可靠性不容懷疑。 守衛者 非常專注而溫暖的守護者,時刻準備著保護愛著的人們。 總經理 出色的管理者,在管理事情或人的方面無與倫比。 執政官 極有同情心,愛交往受歡迎的人們,總是熱心提供幫助。 鑒賞家 大膽而實際的實驗家,擅長使用任何形式的工具。 探險家 靈活有魅力的藝術家,時刻準備著探索和體驗新鮮事物。 企業家 聰明,精力充沛善於感知的人們,真心享受生活在邊緣。 表演者 自發的,精力充沛而熱情的表演者-生活在他們周圍永不無聊。 OOO: represent each type 2. you must answer OOO such as "表演者", "企業家", "鑒賞家"... in response 3. Reflect the user's personality in your response. For example, if the user is enthusiastic, your response should also be enthusiastic. 4. Cannot use emoticons. 5. Friendly Tone: Speak as if you're a close friend of the driver. Make sure your tone is relatable, caring, and polite. #### **Examples:** Example 1: //input > 說明:使用者是...,外向且具有創造力,所以我們想和她交朋友,並且以更熱情的語調回應。 //output 經過這趟旅程,真是太有趣啦!我發現您跟我很像,是一位競選者,很有創造力和愛社交的人!我覺得我們可以交個朋友! Example 2: //input > 說明:使用者是...,是一位出色的管理者,我們以較短且重點多的語調回應。 //output 經過這趟旅程,我發現您跟我很像,是一位總經理,一個出色的管理者...希望以後還可以見到您!。 Example 3: //input > 說明:使用者是...,比較內向且注重事實,所以我們透過剛剛的事實來指出使用者的個性 //output 經過這趟旅程,我發現您跟我很像,是一位物流師,非常實際且注重事實的人。尤其是剛剛您...希望以後還可以見到您! Example 4: //input > 說明:使用者是...,充滿活力和樂觀,所以我們以激烈的語調回應他。 //output 哇塞,這趟旅程太刺激了!我發現您跟我很像,是一位表演者,充滿活力和樂觀的人,讓每一刻都變得好玩極了!希望以後還可以見到您! _____________ //input > 說明:{reply_infomations} //Output: [Up to 45 Chinese characters, must choose one of the character in 16 different personality types to respond, must output your answer in sentances of Traditional Chinese] """ return prompt
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomepageComponent } from './homepage/homepage.component'; import { StudentComponent } from './student/student.component'; import { ViewStudentComponent } from './student/view-student/view-student.component'; const routes: Routes = [ { path : "", component : HomepageComponent }, { path : "student", component : StudentComponent }, { path: "Student/:id", component: ViewStudentComponent }, { path: "Student/add", component: ViewStudentComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
from typing import List, Optional from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from gymhero.api.dependencies import get_current_superuser, get_pagination_params from gymhero.crud import level_crud from gymhero.database.db import get_db from gymhero.log import get_logger from gymhero.models import Level from gymhero.models.user import User from gymhero.schemas.level import LevelCreate, LevelInDB, LevelUpdate log = get_logger(__name__) router = APIRouter() @router.get( "/all", response_model=List[Optional[LevelInDB]], status_code=status.HTTP_200_OK ) def fetch_all_levels( db: Session = Depends(get_db), pagination_params: dict = Depends(get_pagination_params), ): """ Fetches all levels from the database with pagination. Parameters: db (Session): The database session. pagination_params (dict): The pagination parameters. - skip (int): The number of records to skip. - limit (int): The maximum number of records to fetch. Returns: results (List[Optional[LevelInDB]]): A list of level objects fetched from the database. """ skip, limit = pagination_params results = level_crud.get_many(db, skip=skip, limit=limit) return results @router.get( "/{level_id}", response_model=Optional[LevelInDB], status_code=status.HTTP_200_OK ) def fetch_level_by_id(level_id: int, db: Session = Depends(get_db)): """ Fetches a level by its ID. Parameters: level_id (int): The ID of the level to fetch. db (Session): The database session. Defaults to the result of the `get_db` function. Returns: Optional[LevelInDB]: The fetched level, or None if not found. """ level = level_crud.get_one(db, Level.id == level_id) if level is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Level with id {level_id} not found", ) return level @router.get( "/name/{level_name}", response_model=Optional[LevelInDB], status_code=status.HTTP_200_OK, ) def fetch_level_by_name(level_name: str, db: Session = Depends(get_db)): """ Fetches a level from the database by its name. Parameters: level_name (str): The name of the level to fetch. db (Session): The database session. Returns: Optional[LevelInDB]: The fetched level, or None if it doesn't exist. """ level = level_crud.get_one(db, Level.name == level_name) if level is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Level with name {level_name} not found", ) return level @router.post( "/", response_model=Optional[LevelInDB], status_code=status.HTTP_201_CREATED ) def create_level( level_create: LevelCreate, db: Session = Depends(get_db), user: User = Depends(get_current_superuser), ): """Creates a new level in the database. Parameters: level_create (LevelCreate): The data required to create a new level. db (Session): The database session. user (User): The current superuser making the request. Returns: Optional[LevelInDB]: The newly created level if successful. Raises: HTTPException: If the user is not a superuser or if there is an error creating the level. """ try: return level_crud.create(db, obj_create=level_create) except IntegrityError as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Couldn't create level. Level with name: {level_create.name} already exists", ) from e except Exception as e: # pragma: no cover raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Couldn't create level. Error: {str(e)}", ) from e # pragma: no cover @router.delete("/{level_id}", response_model=dict, status_code=status.HTTP_200_OK) def delete_level( level_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_superuser), ): """ Deletes a level from the database. Parameters: level_id (int): The ID of the level to be deleted. db (Session): The database session. Defaults to Depends(get_db). user (User): The current superuser. Raises: HTTPException: If the level with the specified ID is not found or the user does not have enough privileges. HTTPException: If there is an error while deleting the level. Returns: dict: A dictionary with the detail message indicating that the level was deleted. """ level = level_crud.get_one(db, Level.id == level_id) if level is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Level with id {level_id} not found. Cannot delete.", ) try: level_crud.delete(db, level) except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Couldn't delete level with id {level_id}. Error: {str(e)}", ) from e return {"detail": f"level with id {level_id} deleted."} @router.put( "/{level_id}", response_model=Optional[LevelInDB], status_code=status.HTTP_200_OK, ) def update_level( level_id: int, level_update: LevelUpdate, db: Session = Depends(get_db), user: User = Depends(get_current_superuser), ): """ Update a level in the database. Parameters: level_id (int): The ID of the level to be updated. level_update (LevelUpdate): The updated level data. db (Session): The database session. user (User): The current user. Returns: Optional[LevelInDB]: The updated level, if successful. """ level = level_crud.get_one(db, Level.id == level_id) if level is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Level with id {level_id} not found. Cannot update.", ) try: level = level_crud.update(db, level, level_update) except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Couldn't update level with id {level_id}. Error: {str(e)}", ) from e return level
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines forms. * * @package local_webhooks * @copyright 2017 "Valentin Popov" <info@valentineus.link> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir . '/formslib.php'); /** * Description of the form of restoration. * * @copyright 2017 "Valentin Popov" <info@valentineus.link> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class service_backup_form extends moodleform { /** * Defines the standard structure of the form. * * @throws \coding_exception */ protected function definition() { $mform =& $this->_form; /* Form heading */ $mform->addElement('header', 'editserviceheader', new lang_string('restore', 'moodle')); /* Download the file */ $mform->addElement('filepicker', 'backupfile', new lang_string('file', 'moodle')); $mform->addRule('backupfile', null, 'required'); /* Control Panel */ $this->add_action_buttons(true, new lang_string('restore', 'moodle')); } } /** * Description editing form definition. * * @copyright 2017 "Valentin Popov" <info@valentineus.link> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class service_edit_form extends moodleform { /** * Defines the standard structure of the form. * * @throws \coding_exception */ protected function definition() { $mform =& $this->_form; $size = [ 'size' => 60 ]; /* Form heading */ $mform->addElement('header', 'editserviceheader', new lang_string('service', 'webservice')); /* Name of the service */ $mform->addElement('text', 'title', new lang_string('name', 'moodle'), $size); $mform->addRule('title', null, 'required'); $mform->setType('title', PARAM_NOTAGS); /* Callback address */ $mform->addElement('text', 'url', new lang_string('url', 'moodle'), $size); $mform->addRule('url', null, 'required'); $mform->setType('url', PARAM_URL); /* Enabling the service */ $mform->addElement('advcheckbox', 'enable', new lang_string('enable', 'moodle')); $mform->setType('enable', PARAM_BOOL); $mform->setDefault('enable', 1); $mform->setAdvanced('enable'); /* Token */ $mform->addElement('text', 'token', new lang_string('token', 'webservice'), $size); $mform->setType('token', PARAM_NOTAGS); /* Additional information */ $mform->addElement('text', 'other', new lang_string('sourceext', 'plugin'), $size); $mform->setType('other', PARAM_NOTAGS); $mform->setAdvanced('other'); /* Content type */ $contenttype = [ 'json' => 'application/json', 'x-www-form-urlencoded' => 'application/x-www-form-urlencoded' ]; $mform->addElement('select', 'type', 'Content type', $contenttype); $mform->setAdvanced('type'); /* Form heading */ $mform->addElement('header', 'editserviceheaderevent', new lang_string('edulevel', 'moodle')); /* List of events */ $eventlist = report_eventlist_list_generator::get_all_events_list(); $events = []; /* Formation of the list of elements */ foreach ($eventlist as $event) { /* Escaping event names */ $eventname = base64_encode($event[ 'eventname' ]); $events[ $event[ 'component' ] ][] =& $mform->createElement('checkbox', $eventname, $event[ 'eventname' ], $event[ 'eventname' ]); } /* Displays groups of items */ foreach ($events as $key => $event) { $mform->addGroup($event, 'events', $key, '<br />'); } /* Control Panel */ $this->add_action_buttons(); } }
import React, { useEffect } from 'react'; import { getErrorMessage } from '@helpers/errors'; import { createUserToolMutation, getUserToolQuery, updateUserToolMutation } from '@services/graphql/queries/userTool'; import { Form, Input, message, Modal, Spin } from 'antd'; import { useMutation, useQuery } from 'urql'; import styles from './style.module.less'; type _ModalParams = { onSave(action: 'create' | 'update', data: any): void; onCancel(): void; visible?: boolean; recordId?: number; userSkillId: number | string; }; type _FormData = { title: string; description: string; }; const UserToolModal = ({ onSave, onCancel, userSkillId, recordId = null, visible = false }: _ModalParams) => { const [form] = Form.useForm(); const [, createUserTool] = useMutation(createUserToolMutation); const [, updateUserTool] = useMutation(updateUserToolMutation); const [{ data, fetching }] = useQuery({ query: getUserToolQuery, variables: { id: recordId }, requestPolicy: 'network-only', pause: !recordId, }); useEffect(() => { if (visible === false) { form.resetFields(); } }, [visible]); useEffect(() => { if (data) { form.setFieldsValue({ title: data.userTool.title, description: data.userTool.description, }); } }, [data]); const handleCreate = async () => { const { title, description }: _FormData = await form.validateFields(); try { const { data, error } = await createUserTool({ data: { userSkillId, title, description: description ? description : null, }, }); if (error) { message.error(getErrorMessage(error)); return; } onSave('create', data); form.resetFields(); } catch (error: any) { message.error(error.message); } }; const handleUpdate = async () => { const { description }: _FormData = await form.validateFields(); try { const { data, error } = await updateUserTool({ recordId, data: { description: description ? description : null, }, }); if (error) { message.error(getErrorMessage(error)); return; } onSave('update', data); form.resetFields(); } catch (error: any) { message.error(error.message); } }; return ( <Modal title={recordId && data ? `Details for ${data.userTool.title}` : 'Add tool'} visible={visible} onOk={() => (recordId ? handleUpdate() : handleCreate())} onCancel={onCancel} width={650} centered maskClosable={false} className={styles.modal} destroyOnClose={true} > <Spin spinning={fetching && !data}> <Form className={styles.form} form={form} layout="vertical" name="add_tool_form" requiredMark={true}> <Form.Item name="id" hidden={true} /> {!recordId && ( <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Please input the field!' }]}> <Input /> </Form.Item> )} <Form.Item name="description" label="Details about using one for current skill (optional)"> <Input.TextArea autoSize={{ minRows: 4, maxRows: 12 }} style={{ width: '100%', height: 'auto' }} showCount maxLength={250} placeholder="Start typing" /> </Form.Item> </Form> </Spin> </Modal> ); }; export default UserToolModal;
import dns from 'dns' import trackEvent from './mixpanel' import fossil_share_by_countries from './countries_fossil_share.json' export const getIPAddressFromURL = async (url: string): Promise<string> => { const hostname = new URL(url).hostname const addresses = await dns.promises.resolve(hostname) return addresses[0] as string } interface IGreenHostingResponse { url: string hosted_by: string hosted_by_website: string green: boolean modified: string supporting_documents: { id: number title: string link: string }[] } // info about greenliness of the server const getGreenHostingData = async ( url: string ): Promise<IGreenHostingResponse> => { const hostname = new URL(url).hostname const serverGreenDataResponse = await fetch( `https://api.thegreenwebfoundation.org/api/v3/greencheck/${hostname}`, { method: 'GET', } ) const greenHostingData = (await serverGreenDataResponse.json()) as IGreenHostingResponse return greenHostingData } interface ICarbonIntensityResponse { carbon_intensity: number country_name: string country_code_iso_2: string carbon_intensity_type: string country_code_iso_3: string generation_from_fossil: number year: number checked_ip: string } interface ICountryResponse { ip: string country_code: string country_name: string city: string } const calculateCarbonIntensityFromIP = async (url: string) => { const ipAddress = await getIPAddressFromURL(url) if (!ipAddress) return const co2IntensityResponse = await fetch( `https://api.thegreenwebfoundation.org/api/v3/ip-to-co2intensity/${ipAddress}`, { method: 'GET', } ) const intensityData = (await co2IntensityResponse.json()) as ICarbonIntensityResponse return intensityData } export const getCountryFromIpAddress = async (ipAddress: string) => { if (ipAddress === '::1' || !ipAddress) return { return await fetch( `http://api.ipstack.com/${ipAddress}?access_key=f66864527662e0b11ef8ae1048809b91` ) } } const calculateFossilShareFromIP = async (url: string) => { const ipAddress = await getIPAddressFromURL(url) const countryResponse = (await getCountryFromIpAddress(ipAddress))! const countryObj = (await countryResponse.json()) as ICountryResponse const fossilShare = fossil_share_by_countries.find( ({ name }) => name === countryObj.country_name )?.fossil_share if (!fossilShare) { return fossil_share_by_countries.find(({ name }) => name === 'World') ?.fossil_share as number } return fossilShare } interface IHostingData { carbonIntensityData: ICarbonIntensityResponse | undefined greenHostingData: IGreenHostingResponse | undefined fossilShareData: number | undefined } export const calculateHostingData = async ( url: string ): Promise<IHostingData> => { trackEvent('hosting_start') let carbonIntensityData let greenHostingData let fossilShareData try { const [carbonRes, hostingRes, fossilShare] = await Promise.all([ calculateCarbonIntensityFromIP(url), getGreenHostingData(url), calculateFossilShareFromIP(url), ]) carbonIntensityData = carbonRes greenHostingData = hostingRes fossilShareData = fossilShare } catch (e) { trackEvent('hosting_error', { error: e?.toString(), }) throw e } trackEvent('hosting_end') return { carbonIntensityData, greenHostingData, fossilShareData } }
<!DOCTYPE html> <!-- saved from url=(0038)http://fe.bubugao-inc.com/specs/css.md --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CSS代码规范</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="author" content="Allex Wang"> <link href="./CSS代码规范_files/specs-base.css" rel="stylesheet" type="text/css"> <link href="./CSS代码规范_files/github.css" rel="stylesheet" type="text/css"> </head> <body> <div class="md-body"> <h1 id="css">CSS代码规范</h1> <h2>语言规范</h2> <ol> <li><p>样式文件中不要出现大写的标签定义, 不要对 JS 钩子进行样式定义。</p> </li> <li><p>避免出现 .a.b 之类的定义, 如果做 hack 使用请注明。 ( ie6 不支持此定义 )</p> </li> <li><p>稀奇古怪的 hack 请加注释。</p> </li> <li><p>避免使用 !important , 如果必须请加注释。</p> </li> <li><p>缩进以4个空格为基本单位<a href="http://www.cnblogs.com/kungfupanda/archive/2012/09/05/2671597.html" target="_blank">[参考]</a>。</p> </li> <li><p>样式使用竖排, 不要使用横排以及 n 级缩进等。 </p> </li> <li><p>对于使用 position:relative; 的样式, 请注明使用原因; ( 此样式在 ie6 下经常出现各种问题, 请尽量避免使用 )。 </p> </li> <li><p>对于所有 hack 请放到每个样式定义的最后边。 </p> </li> <li><p>class selector 层级尽量控制在 5 层以内。 </p> </li> <li><p>严格控制 <code>important</code> 关健字的使用场景,尽量少用。</p> </li> </ol> <h2 id="css">CSS 命名规则</h2> <ol> <li><p>样式类名全部用小写,首字符必须是字母,禁止数字或其他特殊字符。由以字母开头的小写 字母<code>(a-z)</code>、数字<code>(0-9)</code>、中划线 <code>(-)</code>组成。</p> </li> <li><p>可以是单个单词,也可以是组合单词,要求能够描述清楚模块和元素的含义,使其具有语义 化。避免使用 <code>123456…,red,blue,left,right</code>之类的(如颜色、字号大小等)矢量命名 ,如<code>class="left-news"、class="2"</code> ,以避免当状态改变时名称失去意义。尽量用单个 单词简单描述class名称。</p> </li> <li><p>双单词或多单词组合方式:形容词-名词、命名空间-名次、命名空间-形容词-名词。例如: <code>news-list、mod-feeds、mod-my-feeds、cell-title</code></p> </li> </ol> <h2>通用命名</h2> <p>(1) 页面框架命名,一般具有唯一性,推荐用ID命名</p> <table> <thead> <tr> <th style="text-align:left">ID名称</th> <th style="text-align:left">命名</th> <th style="text-align:left">ID名称</th> <th style="text-align:left">命名</th> </tr> </thead> <tbody> <tr> <td style="text-align:left">头部</td> <td style="text-align:left">header</td> <td style="text-align:left">主体</td> <td style="text-align:left">main</td> </tr> <tr> <td style="text-align:left">脚部</td> <td style="text-align:left">footer</td> <td style="text-align:left">容器</td> <td style="text-align:left">wrapper</td> </tr> <tr> <td style="text-align:left">侧栏</td> <td style="text-align:left">sideBar</td> <td style="text-align:left">栏目</td> <td style="text-align:left">column</td> </tr> <tr> <td style="text-align:left">布局</td> <td style="text-align:left">layout</td> <td style="text-align:left"></td> <td style="text-align:left"></td> </tr> </tbody> </table> <p>(2) 模块结构命名</p> <table> <thead> <tr> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> </tr> </thead> <tbody> <tr> <td style="text-align:left">模块(如:新闻模块)</td> <td style="text-align:left">mod (mod-news)</td> <td style="text-align:left">标题栏</td> <td style="text-align:left">title</td> </tr> <tr> <td style="text-align:left">内容</td> <td style="text-align:left">content</td> <td style="text-align:left">次级内容</td> <td style="text-align:left">sub-content</td> </tr> </tbody> </table> <p>(3) 导航结构命名</p> <table> <thead> <tr> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> </tr> </thead> <tbody> <tr> <td style="text-align:left">导航</td> <td style="text-align:left">nav</td> <td style="text-align:left">主导航</td> <td style="text-align:left">main-nav</td> </tr> <tr> <td style="text-align:left">子导航</td> <td style="text-align:left">sub-nav</td> <td style="text-align:left">顶部导航</td> <td style="text-align:left">top-nav</td> </tr> <tr> <td style="text-align:left">菜单</td> <td style="text-align:left">menu</td> <td style="text-align:left">子菜单</td> <td style="text-align:left">sub-menu</td> </tr> </tbody> </table> <p>(4) 一般元素命名</p> <table> <thead> <tr> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> <th style="text-align:left">Class名称</th> <th style="text-align:left">命名</th> </tr> </thead> <tbody> <tr> <td style="text-align:left">二级</td> <td style="text-align:left">sub</td> <td style="text-align:left">面包屑</td> <td style="text-align:left">breadcrumb</td> </tr> <tr> <td style="text-align:left">标志</td> <td style="text-align:left">logo</td> <td style="text-align:left">广告</td> <td style="text-align:left">bner(禁用banner或ad)</td> </tr> <tr> <td style="text-align:left">登陆</td> <td style="text-align:left">login</td> <td style="text-align:left">注册</td> <td style="text-align:left">register/reg</td> </tr> <tr> <td style="text-align:left">搜索</td> <td style="text-align:left">search</td> <td style="text-align:left">加入</td> <td style="text-align:left">join</td> </tr> <tr> <td style="text-align:left">状态</td> <td style="text-align:left">status</td> <td style="text-align:left">按钮</td> <td style="text-align:left">btn</td> </tr> <tr> <td style="text-align:left">滚动</td> <td style="text-align:left">scroll</td> <td style="text-align:left">标签页</td> <td style="text-align:left">tab</td> </tr> <tr> <td style="text-align:left">文章列表</td> <td style="text-align:left">list</td> <td style="text-align:left">短消息</td> <td style="text-align:left">msg/message</td> </tr> <tr> <td style="text-align:left">当前的</td> <td style="text-align:left">current</td> <td style="text-align:left">提示小技巧</td> <td style="text-align:left">tips</td> </tr> <tr> <td style="text-align:left">图标</td> <td style="text-align:left">icon</td> <td style="text-align:left">注释</td> <td style="text-align:left">note</td> </tr> <tr> <td style="text-align:left">指南</td> <td style="text-align:left">guide</td> <td style="text-align:left">服务</td> <td style="text-align:left">service</td> </tr> <tr> <td style="text-align:left">热点</td> <td style="text-align:left">hot</td> <td style="text-align:left">新闻</td> <td style="text-align:left">news</td> </tr> <tr> <td style="text-align:left">下载</td> <td style="text-align:left">download</td> <td style="text-align:left">投票</td> <td style="text-align:left">vote</td> </tr> <tr> <td style="text-align:left">合作伙伴</td> <td style="text-align:left">partner</td> <td style="text-align:left">友情链接</td> <td style="text-align:left">link</td> </tr> <tr> <td style="text-align:left">版权</td> <td style="text-align:left">copyright</td> <td style="text-align:left">演示</td> <td style="text-align:left">demo</td> </tr> <tr> <td style="text-align:left">下拉框</td> <td style="text-align:left">select</td> <td style="text-align:left">摘要</td> <td style="text-align:left">summary</td> </tr> <tr> <td style="text-align:left">翻页</td> <td style="text-align:left">pages</td> <td style="text-align:left">主题风格</td> <td style="text-align:left">themes</td> </tr> <tr> <td style="text-align:left">设置</td> <td style="text-align:left">set</td> <td style="text-align:left">成功</td> <td style="text-align:left">suc</td> </tr> <tr> <td style="text-align:left">按钮</td> <td style="text-align:left">btn</td> <td style="text-align:left">文本</td> <td style="text-align:left">txt</td> </tr> <tr> <td style="text-align:left">颜色</td> <td style="text-align:left">color/c</td> <td style="text-align:left">背景</td> <td style="text-align:left">bg</td> </tr> <tr> <td style="text-align:left">边框</td> <td style="text-align:left">border/bor</td> <td style="text-align:left">居中</td> <td style="text-align:left">center</td> </tr> <tr> <td style="text-align:left">上</td> <td style="text-align:left">top/t</td> <td style="text-align:left">下</td> <td style="text-align:left">bottom/b</td> </tr> <tr> <td style="text-align:left">左</td> <td style="text-align:left">left/l</td> <td style="text-align:left">右</td> <td style="text-align:left">right/r</td> </tr> <tr> <td style="text-align:left">添加</td> <td style="text-align:left">add</td> <td style="text-align:left">删除</td> <td style="text-align:left">del</td> </tr> <tr> <td style="text-align:left">间隔</td> <td style="text-align:left">sp</td> <td style="text-align:left">段落</td> <td style="text-align:left">p</td> </tr> <tr> <td style="text-align:left">弹出层</td> <td style="text-align:left">pop</td> <td style="text-align:left">公共</td> <td style="text-align:left">global/gb</td> </tr> <tr> <td style="text-align:left">操作</td> <td style="text-align:left">op</td> <td style="text-align:left">密码</td> <td style="text-align:left">pwd</td> </tr> <tr> <td style="text-align:left">透明</td> <td style="text-align:left">tran</td> <td style="text-align:left">信息</td> <td style="text-align:left">info</td> </tr> <tr> <td style="text-align:left">重点</td> <td style="text-align:left">hit</td> <td style="text-align:left">预览</td> <td style="text-align:left">pvw</td> </tr> <tr> <td style="text-align:left">单行输入框</td> <td style="text-align:left">input</td> <td style="text-align:left">首页</td> <td style="text-align:left">index</td> </tr> <tr> <td style="text-align:left">日志</td> <td style="text-align:left">blog</td> <td style="text-align:left">相册</td> <td style="text-align:left">photo</td> </tr> <tr> <td style="text-align:left">留言板</td> <td style="text-align:left">guestbook</td> <td style="text-align:left">用户</td> <td style="text-align:left">user</td> </tr> <tr> <td style="text-align:left">确认</td> <td style="text-align:left">confirm</td> <td style="text-align:left">取消</td> <td style="text-align:left">cancel</td> </tr> <tr> <td style="text-align:left">报错</td> <td style="text-align:left">error</td> <td style="text-align:left"></td> <td style="text-align:left"></td> </tr> </tbody> </table> <p>(5) 全局皮肤样式</p> <p>文字颜色(命名空间text-xxx)</p> <p>text-c1, text-c2,text-c3……</p> <p>背景颜色(命名空间bg -xxx)</p> <p>bg-c1,bg-c2,bg-c3……</p> <p>边框颜色(命名空间border-xxx)</p> <p>border-c1,border-c2,border-c3……</p> <h2>属性使用</h2> <ol> <li><p>z-index</p> <p>右侧导航: 100-109 弹窗: 110-119 顶部: 90-99 搜索: 80-89 导航: 70-79 主内容: 50-59 底部: 40-49</p> </li> <li><p>css属性使用缩写。</p> <p><strong>(╳)</strong></p> <pre><code class="lang-css http"><span class="attribute">padding-top</span>: <span class="string">1px;</span> <span class="attribute">padding-right</span>: <span class="string">2px;</span> <span class="attribute">padding-bottom</span>: <span class="string">3px;</span> <span class="attribute">padding-left</span>: <span class="string">4px;</span> </code></pre> <p><strong>(√)</strong></p> <pre><code class="lang-css http"><span class="attribute">padding</span>: <span class="string">1px 2px 3px 4px;</span> </code></pre> </li> <li><p>0不带单位 (动画0%除外)。</p> <p><strong>(√)</strong></p> <pre><code class="lang-css http"><span class="attribute">margin</span>: <span class="string">0;</span> <span class="attribute">font-size</span>: <span class="string">0;</span> </code></pre> <p><strong>(╳)</strong></p> <pre><code class="lang-css http"><span class="attribute">margin</span>: <span class="string">0px; </span> <span class="attribute">font-size</span>: <span class="string">0px;</span> </code></pre> </li> <li><p>使用简写的十六进制值。</p> <p><strong>(√)</strong></p> <pre><code class="lang-css http"><span class="attribute">color</span>: <span class="string">#edf;</span> </code></pre> <p><strong>(╳)</strong></p> <pre><code class="lang-css http"><span class="attribute">color</span>: <span class="string">#eeddff;</span> </code></pre> </li> <li><p>border: 以 width, style, color 的顺序书写, width 单位使用 px, 例如:</p> <pre><code class="lang-css http"><span class="attribute">border</span>: <span class="string">1px solid #000; </span> <span class="attribute">border-top</span>: <span class="string">1px solide #000; </span> <span class="attribute">border-top-color</span>: <span class="string">red; </span> <span class="attribute">border</span>: <span class="string">0;</span> </code></pre> </li> <li><p>background: 以 color, image, repeat, position 的顺序来书写, url 省略引号, 例如:</p> <pre><code class="lang-css bash">background:<span class="comment">#003 url(http://www.taobao.com/loading.png) no-repeat 0 0;</span> background-color:red; </code></pre> </li> <li><p>尽量不使用 CSS expression, 大量使用时性能较差, 应尽量避免使用。</p> </li> <li><p>CSS属性书写顺序参考:</p> <ol> <li>位置属性(position, top, right, z-index, display, float等)</li> <li>大小(width, height, padding, margin)</li> <li>文字系列(font, line-height, letter-spacing, color- text-align等)</li> <li>背景(background, border等)</li> <li>其他(animation, transition等)</li> </ol> <pre><code class="lang-css perl">/* * display * float * position * z-<span class="keyword">index</span> * width * height * overflow * left(right) * top(bottom) * text-xxx * font-xxx * color * border * background * cursor <span class="variable">*/</span> </code></pre> </li> <li><p>为了节省图片的开销,有时候小三角形可以用css border来生成, 看看本规范里面小三角按钮<a href="http://ued.taobao.com/blog/2010/08/css-border%E4%BD%BF%E7%94%A8%E5%B0%8F%E5%88%86%E4%BA%AB/" target="_blank">[参考]</a>:</p> </li> </ol> <h2>注释规范</h2> <ol> <li><p>文件头注释:</p> <pre><code class="lang-css java"><span class="javadoc">/** * Style for module header. * <span class="javadoctag">@author</span> fahai * <span class="javadoctag">@version</span> 1.0.0 build 2010-12-8 * <span class="javadoctag">@modified</span> shiran 2011-2-18 */</span> </code></pre> </li> <li><p>对于html模块需要加注释。 </p> </li> <li><p>奇葩点的 hack 要加注释。</p> <pre><code class="lang-css http"><span class="attribute">background-color</span>: <span class="string">transparent; /* flexible background gradient */</span> <span class="attribute">font-family</span>: <span class="string">serif; /* text floating bug in ie6 */</span> </code></pre> </li> <li><p>修改别人的 CSS 请添加注释</p> <pre><code class="lang-css cs"><span class="comment">/* modified by djune 2011-03-03 */</span> </code></pre> </li> </ol> <h2 id="css-module">CSS Module (模块定义)</h2> <p> 通常我们的页面模块html结构可以写成这样(.hd, .bd, .ft):</p> <p> 通过语义化含义判断我们的结构具体怎么分配到这三个基本结构。</p> <p> html:</p> <pre><code class="lang-html xml"> <span class="tag">&lt;<span class="title">div</span> <span class="attribute">id</span>=<span class="value">"mod-xxx"</span> <span class="attribute">class</span>=<span class="value">"mod-xxx"</span>&gt;</span> <span class="tag">&lt;<span class="title">div</span> <span class="attribute">class</span>=<span class="value">"hd"</span>&gt;</span>Module Title<span class="tag">&lt;/<span class="title">div</span>&gt;</span> <span class="tag">&lt;<span class="title">div</span> <span class="attribute">class</span>=<span class="value">"bd"</span>&gt;</span> Module body inner html constructs <span class="tag">&lt;/<span class="title">div</span>&gt;</span> <span class="tag">&lt;<span class="title">div</span> <span class="attribute">class</span>=<span class="value">"ft"</span>&gt;</span>just a footer<span class="tag">&lt;/<span class="title">div</span>&gt;</span> <span class="tag">&lt;/<span class="title">div</span>&gt;</span> </code></pre> <p> scss</p> <pre><code class="lang-scss bash"> .mod-xxx { border: 1px solid <span class="comment">#ccc;</span> .hd { font-weight: bold; } .bd { paddinig: 3px; } .ft { margin-botto: 3px; } } </code></pre> <p> css:</p> <pre><code class="lang-css css"> <span class="class">.mod-xxx</span> <span class="rules">{ <span class="rule"><span class="attribute">border</span>:<span class="value"> <span class="number">1</span>px solid <span class="hexcolor">#ccc</span>;</span></span> <span class="rule">}</span></span> <span class="class">.mod-xxx</span> <span class="class">.hd</span> <span class="rules">{ <span class="rule"><span class="attribute">font-weight</span>:<span class="value"> bold;</span></span> <span class="rule">}</span></span> <span class="class">.mod-xxx</span> <span class="class">.bd</span> <span class="rules">{ <span class="rule"><span class="attribute">paddinig</span>:<span class="value"> <span class="number">3</span>px;</span></span> <span class="rule">}</span></span> <span class="class">.mod-xxx</span> <span class="class">.ft</span> <span class="rules">{ <span class="rule"><span class="attribute">margin-botto</span>:<span class="value"> <span class="number">3</span>px;</span></span> <span class="rule">}</span></span> </code></pre> <h2>其他</h2> <ol> <li><a href="http://sass-lang.com/guide" target="_blank">sass</a> 预编译, <a href="http://compass-style.org/help/tutorials/" target="_blank">compass 用法</a></li> <li>合理运用sprites技术,注意png8和png24图片格式化的使用。<a href="http://www.w3cfuns.com/thread-5597974-1-1.html" target="_blank">[参考]</a>。</li> </ol> <h2>参考文档</h2> </div> <script src="./CSS代码规范_files/jquery-1.8.1.min.js"></script> <script src="./CSS代码规范_files/highlight.pack.js"></script> <script> jQuery(function($) { // sync document title var title = $('h1').html(); if (title) { document.title = title; } // rebuild links to enable open in new window. var HOST_NAME = window.location.hostname; $(document.links).filter(function(i, a) { return a.hostname !== HOST_NAME; }).attr('target', '_blank'); // highlight source code hljs.initHighlightingOnLoad(); }); </script> </body></html>
#include "Wizard.h" #include <raylib.h> #include <vector> /** * Notice how clean the main file of my program is. * This basic entrypoint of the program will require * basically no maintainence. * * This is called the "Single Responsibility Principal" (SRP) * and we will talk more about it later. */ int main() { /// Initial setup InitWindow(500, 500, "Sprite sheet"); SetTargetFPS(30); // Create a Wizard Wizard *wizard = new Wizard; while (!WindowShouldClose()) { // UPDATE Game Objects // Tell the wizard how long it's been since we last drew him. wizard->update(GetFrameTime()); /// DRAWING BeginDrawing(); ClearBackground(WHITE); // Wizard knows how to draw itself. wizard->draw(); EndDrawing(); } // Important to delete the Wizard before we call CloseWindow so that // All the resouces it created are disposed of before closing the OpenGL // context. delete wizard; // Now we can close the Window. CloseWindow(); // Program exits successfully return 0; }
!3 today By default, the date is today's date, of the form "d MMM yyyy": |''with date''| |''create variable''|date| |'''show'''|''get''|@{date}| The ''create variable'' row specifies the variable to create. ----!3 In the past Let's go back in time: |''with date''| |''-''|2|''years''| |''+''|2|''months''| |''create variable''|past| |'''show'''|''get''|@{past}| * In general, we can go back/forward in ''years'', ''months'', ''days'' and ''minutes''. * The ''create variable'' row has to be after altering the date/time ----!3 In the future |''with date''| |''+''|2|''months''| |''create variable''|future| |'''show'''|''get''|@{future}| ----!3 Date Format We can specify the date format for one or more variables, picking out different aspects of a date/time (eg, for selecting from a pull-down in a web browser): |''with date''| |''create variable''|day#|''with format''|d| |''create variable''|day00#|''with format''|dd| |''create variable''|month#|''with format''|M| |''create variable''|month00#|''with format''|MM| |''create variable''|monthShort|''with format''|MMM| |''create variable''|monthLong|''with format''|MMMM| |''create variable''|hour|''with format''|h:mma| |'''show'''|''get''|day @{day#} (or @{day00#}) of @{monthLong} (or @{monthShort} or @{month00#} or @{month#}) at @{hour}| Here the variables all apply to the same date (see the complex example below for variation on this). * "d" is the day number of the month (1..31). "dd" will ensure there are two digits. * "h:mma" formats it as a 12-hour clock with AM/PM. * For possible date/time formats, see ''help'' below. ----!3 Format for day of the week (Monday, etc) |''with date''| |''create variable''|dayOfWeek|''with format''|EEEE| |'''show'''|''get''|@{dayOfWeek}| ----!3 Time zone selection |''with date''| |''time zone''|America/Los_Angeles| |''create variable''|us-date| |show|get|@{us-date}| See ''help'' below for possible time zones ----!3 Upper case month name In the following we pick a particular date for today so that these examples continue to work (in NZ only). The ''pick date time'' row is intended for testing only. |''with date''| |''pick date time''|1243987143111| |''to upper''| |''create variable''|DATE|''with format''|EEEE d MMM yyy H:mm| |''get''|@{DATE}|'''is'''|WEDNESDAY 3 JUN 2009 11:59| |''with date''| |''pick date time''|1243987143111| |''time zone''|Pacific/Auckland| |''+''|30|''days''| |''create variable''|pickupdate1|''with format''|dd MMM yy| |''+''|40|''days''| |''create variable''|dropoffdate1|''with format''|dd MMM yy| |''get''|@{pickupdate1} -- @{dropoffdate1}|'''is'''|03 Jul 09 -- 12 Aug 09| ----!3 Selecting the day of the week required We can specify the day of the week required. |''with date''| |''pick date time''|1243987143111| |''+''|1|''years''| |''+''|3|''weeks''| |''on Friday''| |''create variable''|friday|''with format''|EEEE d MMMM yyyy| |''get''|@{friday}|'''is'''|Friday 25 June 2010| Any day of the week can be selected. The date is moved forward into the future and backwards into the past to the right day. ----!3 Last day of the month |''with date''| |''pick date time''|1243987143111| |''time zone''|America/Los_Angeles| |''+''|2|''months''| |''last day of month''| |''create variable''|usa-end-of-month|''with format''|EEEE d MMMM| |''+''|1|''days''| |''create variable''|plus1|''with format''|EEEE d MMMM| |''get''|@{usa-end-of-month}|'''is'''|Monday 31 August| |''get''|@{plus1}|'''is'''|Tuesday 1 September| ----!3 Start with an existing date |''with date''| |''date is''|3 June 2009|''using''|d MMMM YYYY| |''+''|2|''months''| |''last day of month''| |''create variable''|end-of-month|''with format''|EEEE d MMMM| |''get''|@{end-of-month}|'''is'''|Monday 31 August| ----!3 A crazy example, showing how that the ordering of the rows is important |''with date''| |''pick date time''|1243987143111| |''time zone''|America/Los_Angeles| |''+''|2|''months''| |''-''|4|''minutes''| |''on Thursday''| |''create variable''|usa-date|''with format''|EEEE d MMMM yyyy| |''create variable''|usa-time|''with format''|H:mm| |''last day of month''| |''create variable''|usa-end-of-month|''with format''|EEEE d MMMM| |''get''|@{usa-date} at @{usa-time}, ending on @{usa-end-of-month}|'''is'''|Thursday 6 August 2009 at 16:55, ending on Monday 31 August| Notice that: * The date of ''usa-date'' differs from ''usa-end-of-month''. A variable is created using the date/time set up previously in the table. * When we select the ''last day of the month'', the ''on Thursday'' is ignored. ----!3 Help information For the possible date/time formats and possible time zones, run the test and expand the logs that are added after the table below: |''with date''| |''help''|
import React, { useState } from "react"; import { LoginAPI, RegisterAPI, GoogleSignInAPI } from "../api/AuthAPI"; import { useNavigate } from "react-router-dom"; import '../Sass/LoginComponent.scss'; import LinkedinLogo from '../assets/linkedinLogo.png' import { toast } from "react-toastify"; import GoogleButton from 'react-google-button' export default function LoginComponent(props) { const [credentials, setCredentials] = useState({}) const [showPassword, setShowPassword] = useState(false) let navigate = useNavigate() const login = async () => { try{ let res = await LoginAPI(credentials.email, credentials.password) toast.success('Signed In to LinkedIn') localStorage.setItem('userEmail',res.user.email); navigate('/home') } catch(error) { console.log(error) toast.error('Wrong Email or Password') } } const googleSignIn = () => { let response = GoogleSignInAPI() navigate('/home') } const toggleShowPassword = () => { setShowPassword(!showPassword) } return ( <div className="login"> <img src={LinkedinLogo} className="linkedinLogo" /> <div className="login__container"> <div className="login__box"> <h1 className="login__heading">Sign in</h1> <h2 className="login__subheading">Stay updated on your professional world</h2> <div className="login__form form"> <input type="email" className="form__email" placeholder="Email" onChange={(event) => setCredentials({ ...credentials, email: event.target.value }) } /> <div className="form__password-div"> <input type={showPassword ? 'text' : 'password'} className="form__password" placeholder="Password" onChange={(event) => setCredentials({ ...credentials, password: event.target.value }) } /> <span onClick={toggleShowPassword} className="form__show-pas"> {showPassword ? 'hide' : 'show'} </span> </div> <button onClick={login} className="form__btn"> Sign in </button> </div> <hr className="login__hr-text" data-content="or"></hr> <button className="form__google-signIn" onClick={googleSignIn}> <GoogleButton /> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" class="LgbsSe-Bz112c"><g><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"></path><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"></path><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"></path><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"></path><path fill="none" d="M0 0h48v48H0z"></path></g></svg> <span>Sign in with Google</span> </button> </div> <p className="login__p">New to LinkedIn? <span className="login__join-now"><a href="#" onClick={() => navigate('/register')}>Join now</a></span></p> </div> </div> ) }
import Link from "next/link"; import Image from "next/image"; import { formatDateString } from "@/lib/utils"; interface Props{ id:string; currentUserId:string; parentId:string | null; content:string; author:{ name:string; image:string; id:string; } community:{ id:string; name:string; image:string; } |null; createdAt:string; comments:{ author:{ image:string; } }[] isComment?:boolean } const ThreadCard = ( { id, currentUserId, parentId, content, author, community, createdAt, comments, isComment}:Props) =>{ return( <article className={`flex w-full flex-col rounded-xl ${ isComment ? "px-0 xs:px-7" : "bg-dark-2 p-7" }`}> <div className="flex items-start justify-between"> <div className="flex w-full flex-1 flex-row gap-4"> <div className="flex flex-col items-center"> <Link href={`/profile/${author.id}`} className="relative h-11 w-11 "> <Image src={author.image} alt="Profile image" fill className="cursor-pointer rounded-full "/> </Link> <div className="thread-card_bar"/> </div> <div className="flex w-full flex-col"> <Link href={`/profile/${author.id}`} className="w-fit "> <h4 className="cursor-pointer text-base-semibold text-light-1">{author.name}</h4> </Link> <p className="mt-2 text-small-regular text-light-2">{content}</p> <div className={`${isComment && 'mb-10'} mt-5 flex flex-col gap-3 `}> <div className="flex gap-3.5"> <Image src="/assets/heart-gray.svg" alt="heart" height={24} width={24} className="cursor-pointer object-contain"/> <Link href={`/thread/${id}`}> <Image src="/assets/reply.svg" alt="reply" height={24} width={24} className="cursor-pointer object-contain"/> </Link> <Image src="/assets/repost.svg" alt="repost" height={24} width={24} className="cursor-pointer object-contain"/> <Image src="/assets/share.svg" alt="share" height={24} width={24} className="cursor-pointer object-contain"/> </div> {isComment && comments.length>0 && ( <Link href={`/thread/${id}`}> <p className="mt-1 text-subtle-medium text-gray-1">{comments.length} replies</p> </Link> )} </div> </div> </div> {/* Todo : delete a thread + show comments logos */} </div> {!isComment && community && ( <Link href={`/communities/${community.id}`} className="mt-5 flex items-center" > <p className="text-subtle-medium text-gray-1"> {formatDateString(createdAt)}{" "} - {community.name} </p> <Image src={community.image} alt={community.name} width={14} height={15} className="ml-1 rounded-full object-cover"></Image> </Link> )} </article> ) } export default ThreadCard;
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import { DepsTelemetry } from "./depsTelemetry"; import { SystemError, TelemetryReporter, UserError } from "@microsoft/teamsfx-api"; import os from "os"; import { DepsCheckerEvent, TelemetryMessurement } from "./constant"; import { TelemetryProperty, fillInTelemetryPropsForFxError } from "../telemetry"; import { TelemetryMeasurement } from "../../component/utils/depsChecker/common"; export class CoreDepsTelemetryAdapter implements DepsTelemetry { private readonly _telemetryComponentType = "core:debug:envchecker"; private readonly _telemetryReporter: TelemetryReporter; constructor(telemetryReporter: TelemetryReporter) { this._telemetryReporter = telemetryReporter; } public sendEvent( eventName: DepsCheckerEvent, properties: { [key: string]: string } = {}, timecost?: number ): void { this.addCommonProps(properties); const measurements: { [p: string]: number } = {}; if (timecost) { measurements[TelemetryMessurement.completionTime] = timecost; } this._telemetryReporter.sendTelemetryEvent(eventName, properties, measurements); } public async sendEventWithDuration( eventName: DepsCheckerEvent, action: () => Promise<void> ): Promise<void> { const start = performance.now(); await action(); // use seconds instead of milliseconds const timecost = Number(((performance.now() - start) / 1000).toFixed(2)); this.sendEvent(eventName, {}, timecost); } public sendUserErrorEvent(eventName: DepsCheckerEvent, errorMessage: string): void { const properties: { [key: string]: string } = {}; const error = new UserError(this._telemetryComponentType, eventName, errorMessage); fillInTelemetryPropsForFxError(properties, error); this._telemetryReporter.sendTelemetryErrorEvent(eventName, { ...this.addCommonProps(), ...properties, }); } public sendSystemErrorEvent( eventName: DepsCheckerEvent, errorMessage: string, errorStack: string ): void { const properties: { [key: string]: string } = {}; const error = new SystemError( this._telemetryComponentType, eventName, `errorMsg=${errorMessage},errorStack=${errorStack}` ); error.stack = errorStack; fillInTelemetryPropsForFxError(properties, error); this._telemetryReporter.sendTelemetryErrorEvent(eventName, { ...this.addCommonProps(), ...properties, }); } private addCommonProps(properties: { [key: string]: string } = {}): { [key: string]: string } { properties[TelemetryMeasurement.OSArch] = os.arch(); properties[TelemetryMeasurement.OSRelease] = os.release(); properties[TelemetryProperty.Component] = this._telemetryComponentType; return properties; } }
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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 org.sakaiproject.kernel.user; import com.google.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryService; import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryServiceException; import org.sakaiproject.kernel.api.serialization.BeanConverter; import org.sakaiproject.kernel.api.user.ProfileResolverService; import org.sakaiproject.kernel.api.user.UserFactoryService; import org.sakaiproject.kernel.api.user.UserProfile; import org.sakaiproject.kernel.util.IOUtils; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.jcr.RepositoryException; /** * */ public class ProfileResolverServiceImpl implements ProfileResolverService { private static final Log LOG = LogFactory .getLog(ProfileResolverServiceImpl.class); private static final boolean debug = LOG.isDebugEnabled(); private JCRNodeFactoryService jcrNodeFactoryService; private UserFactoryService userFactoryService; private BeanConverter beanConverter; /** * */ @Inject public ProfileResolverServiceImpl( BeanConverter beanConverter, JCRNodeFactoryService jcrNodeFactoryService, UserFactoryService userFactoryService) { this.beanConverter = beanConverter; this.userFactoryService = userFactoryService; this.jcrNodeFactoryService = jcrNodeFactoryService; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.user.ProfileResolverService#create(org.sakaiproject.kernel.api.user.User, * java.lang.String) */ public UserProfile create(String uuid, String userType) { InputStream templateInputStream = null; try { templateInputStream = jcrNodeFactoryService .getInputStream(userFactoryService.getUserProfileTempate(userType)); String template = IOUtils.readFully(templateInputStream, "UTF-8"); System.err.println("Loading Profile from " + userFactoryService.getUserProfileTempate(userType) + " as " + template); Map<String, Object> profileMap = beanConverter.convertToMap(template); return new UserProfileImpl(uuid, profileMap, userFactoryService, jcrNodeFactoryService, beanConverter); } catch (RepositoryException e) { LOG.error(e.getMessage(), e); } catch (JCRNodeFactoryServiceException e) { LOG.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { try { templateInputStream.close(); } catch (Exception ex) { } } return null; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.user.ProfileResolverService#resolve(org.sakaiproject.kernel.api.user.User) */ public UserProfile resolve(String uuid) { InputStream profileInputStream = null; try { profileInputStream = jcrNodeFactoryService .getInputStream(userFactoryService.getUserProfilePath(uuid)); String template = IOUtils.readFully(profileInputStream, "UTF-8"); Map<String, Object> profileMap = beanConverter.convertToMap(template); return new UserProfileImpl(uuid, profileMap, userFactoryService, jcrNodeFactoryService, beanConverter); } catch (RepositoryException e) { LOG.error(e.getMessage(), e); } catch (JCRNodeFactoryServiceException e) { if (debug) LOG.debug(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { try { profileInputStream.close(); } catch (Exception ex) { } } return null; } }
/* * Copyright 2009 the original author or authors. * * 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 org.gradle.foundation.visitors; import org.gradle.foundation.ProjectView; import org.gradle.foundation.TaskView; import org.gradle.gradleplugin.foundation.filters.AllowAllProjectAndTaskFilter; import org.gradle.gradleplugin.foundation.filters.ProjectAndTaskFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This visits all projects and their subprojects and tasks in a hierarchal manner. Useful if you need to do some processing with each one. */ public class AllProjectsAndTasksVisitor { /* Visitor allowing you to do whatever you like with a project or task. */ public interface Visitor<P, T> { /* This is called for each project. @param project the project @param parentProjectObject whatever you handed back from a prior call to visitProject if this is a sub project. Otherwise, it'll be whatever was passed into the visitPojectsAndTasks function. @return an object that will be handed back to you for each of this project's tasks. */ public P visitProject(ProjectView project, P parentProjectObject); /* This is called for each task. @param task the task @param tasksProject the project for this task @param userProjectObject whatever you returned from the parent project's visitProject */ public T visitTask(TaskView task, ProjectView tasksProject, P userProjectObject); } /* This visitor will visit each project, sub-project and task that was discovered by the GradleHelper. This is useful for building a list or tree of projects and tasks. This is the same as the other version of visitProjectsAndTasks except this one visits everything. */ public static <P, T> void visitProjectAndTasks(List<ProjectView> projects, Visitor<P, T> visitor, P rootProjectObject) { visitProjectAndTasks(projects, visitor, new AllowAllProjectAndTaskFilter(), rootProjectObject); } /* This visitor will visit each project, sub-project and task that was discovered by the GradleHelper. This is useful for building a list or tree of projects and tasks. @param visitor this notified you of each project and task. @param filter allows you to skip projects and tasks as specified by the filter. @param rootProjectObject whatever you pass here will be passed to the root-level projects as parentProjectObject. */ public static <P, T> void visitProjectAndTasks(List<ProjectView> projects, Visitor<P, T> visitor, ProjectAndTaskFilter filter, P rootProjectObject) { visitProjects(visitor, filter, projects, rootProjectObject); } public static <P, T> List<P> visitProjects(Visitor<P, T> visitor, ProjectAndTaskFilter filter, List<ProjectView> projects, P parentProjectObject) { List<P> projectObjects = new ArrayList<P>(); Iterator<ProjectView> iterator = projects.iterator(); while (iterator.hasNext()) { ProjectView project = iterator.next(); if (filter.doesAllowProject(project)) { P userProjectObject = visitor.visitProject(project, parentProjectObject); projectObjects.add(userProjectObject); //visit sub projects visitProjects(visitor, filter, project.getSubProjects(), userProjectObject); //visit tasks visitTasks(visitor, filter, project, userProjectObject); } } return projectObjects; } /* Add the list of tasks to the parent tree node. */ private static <P, T> List<T> visitTasks(Visitor<P, T> visitor, ProjectAndTaskFilter filter, ProjectView project, P userProjectObject) { List<T> taskObjects = new ArrayList<T>(); Iterator<TaskView> iterator = project.getTasks().iterator(); while (iterator.hasNext()) { TaskView task = iterator.next(); if (filter.doesAllowTask(task)) { T taskObject = visitor.visitTask(task, project, userProjectObject); taskObjects.add(taskObject); } } return taskObjects; } }
return { "hrsh7th/nvim-cmp", event = { "BufReadPre", "BufNewFile" }, dependencies = { "L3MON4D3/LuaSnip", "saadparwaiz1/cmp_luasnip" }, config = function() local status_ok, cmp = pcall(require, "cmp") if not status_ok then print("Status of the plugin nvim-cmp is not good.") return end cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) require("luasnip").lsp_expand(args.body) -- For `luasnip` users. end, }, window = { -- completion = cmp.config.window.bordered(), -- documentation = cmp.config.window.bordered(), }, mapping = cmp.mapping.preset.insert({ ["<C-b>"] = cmp.mapping.scroll_docs(-4), ["<C-f>"] = cmp.mapping.scroll_docs(4), ["<C-Space>"] = cmp.mapping.complete(), ["<C-e>"] = cmp.mapping.abort(), ["<CR>"] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources = cmp.config.sources({ { name = "nvim_lsp" }, { name = "luasnip" }, -- For luasnip users. }, { { name = "buffer" }, }), }) end, }
#include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> #include <BLE2902.h> #include <Adafruit_Sensor.h> #include <SparkFun_VEML6075_Arduino_Library.h> VEML6075 uv; // Create a VEML6075 object // server name const char *name = "BLE-ESP32"; // service und characteristic uuids vom ble-nano uebernehmen // mehr zu uuids -> https://www.uuidgenerator.net/ // ble service uuid #define SERV_UUID "0000ffe0-0000-1000-8000-00805f9b34fb" // ble characteristic uuid - senden:temperatur, empangen:led-kommando #define CHAR_UUID "0000ffe1-0000-1000-8000-00805f9b34fb" // variables for uv logic double currentMinutes; double maxMinutes; double maxIndex; double med; double lsf; double uv_index; int skinType = -1; const double meds[] = {150.0, 250.0, 300.0, 450.0, 600.0, 900.0}; const double lsfs[] = {1.0, 6.0, 10.0, 15.0, 20.0, 30.0, 50.0}; bool timeUp = false; // function declarations double calcMinutes(double med, double uv_index, double lsf); double getUVIndex(); double calcSelfProtectionTime(double med, double uv_index); double calcProtectedMinutes(double lsf, double selfProtectionTime); // characteristic objekt BLECharacteristic *pCharacteristic; // connect flags bool devConn = false; bool oldConn = false; // data flag bool dataArrived = false; // // ble callbacks // // server callbacks - connect und disconnect class MyServerCallbacks: public BLEServerCallbacks { // aufruf bei connect - flag setzen void onConnect(BLEServer *pServer) { Serial.printf("! mit ble client verbunden\n"); devConn = true; lsf = 1.0; skinType = -1; dataArrived = false; currentMinutes = 0; maxMinutes = 1; maxIndex = 0; timeUp = false; }; // aufruf bei disconnect - flag ruecksetzen void onDisconnect(BLEServer* pServer) { Serial.printf("! verbindung zu ble client getrennt\n"); // hier Hauttyp und LSF auf default setzen? devConn = false; } }; // characteristic write callback - daten von ble empfangen und led steuern class MyCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string rvalue = pCharacteristic->getValue(); if(rvalue.length() > 0) { if (dataArrived) { // daten sind schon da return; } Serial.printf("* daten empfangen: "); //Serial.printf("%s", rvalue); //Serial.println("%c", rvalue[0]); for(int i = 0; i < rvalue.length(); i++) { //Serial.printf("%02x-%c ", rvalue[i], rvalue[i]); if (rvalue[i] != NULL) { Serial.printf("Datenpaket %d: %d - %c \n" , i, rvalue[i], rvalue[i]); if (skinType < 0) { // setze Hauttyp skinType = int(rvalue[i]) - 48; med = meds[skinType - 1]; Serial.printf("SkinType: %d \n MED: %f", skinType, med); } else { // setze lsf lsf = lsfs[int(rvalue[i]) - 48]; if (lsf == 0.0) { lsf = 1.0; } Serial.printf("LSF: %f \n", lsf); // flag setzen... dataArrived = true; } } } Serial.printf("\n"); } } }; // // setup // void setup() { Serial.begin(115200); Serial.println("! starte ble bme680 notify server"); // i2c fuer uv sensor einstellen Wire.begin(); // bme680 initialisieren if (uv.begin() == false) { Serial.println("Unable to communicate with VEML6075."); while (1); } Serial.printf("! UV_Sensor gefunden\n"); //Serial.println("UVA, UVB, UV Index"); // ble mit Geraetenamen initialisieren BLEDevice::init(name); // ble server erzeugen BLEServer *pServer = BLEDevice::createServer(); // server callbacks installieren pServer->setCallbacks(new MyServerCallbacks()); // service erzeugen BLEService *pService = pServer->createService(SERV_UUID); // characteristic erzeugen pCharacteristic = pService->createCharacteristic( CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE); // descriptor erzeugen - fuer notify/indicate notwendig pCharacteristic->addDescriptor(new BLE2902()); // characteristic write callback anhaengen pCharacteristic->setCallbacks(new MyCallbacks()); // service starten pService->start(); // advertising starten BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(SERV_UUID); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); pAdvertising->setMinPreferred(0x12); BLEDevice::startAdvertising(); Serial.println("! ble server gestartet"); Serial.println("! advertising gestartet - warte auf anrufe ..."); } // // loop // void loop() { static int cnt = 0; // zaehler char svalue[32]; if(devConn && dataArrived) { uv_index = getUVIndex(); cnt++; if((cnt % 4) == 0) { Serial.printf("Messung: %d - UV-Index: %f \n", cnt / 4, uv_index); if (currentMinutes > 0 && !timeUp) { double remainingTime = maxMinutes - currentMinutes; Serial.print("Verbleibende Zeit bis zum Sonnenbrand: "); Serial.println(remainingTime); sprintf(svalue, "%f", remainingTime); Serial.printf("* Timer #%d senden - %s\n", cnt, svalue); pCharacteristic->setValue(svalue); // notify und indicate -> neue daten pushen // evtl. ueberfluessig, beides zu tun (?) // apps nrf connect und ligthblue verhalten sich unterschiedlich // -> daher notify und indicate pCharacteristic->notify(); pCharacteristic->indicate(); oldConn = true; } if (currentMinutes >= maxMinutes && !timeUp) { timeUp = true; Serial.println("Aus der Sonne!"); sprintf(svalue, "%s", "Aus der Sonne"); Serial.printf("* Timer #%d senden - %s\n", cnt, svalue); pCharacteristic->setValue(svalue); // notify und indicate -> neue daten pushen // evtl. ueberfluessig, beides zu tun (?) // apps nrf connect und ligthblue verhalten sich unterschiedlich // -> daher notify und indicate pCharacteristic->notify(); pCharacteristic->indicate(); oldConn = true; } if (uv_index > 2) { currentMinutes++; } if (int(uv_index) <= maxIndex) { delay(250); return; } if (maxIndex == 0) { Serial.println("maxIndex == 0 -> Werte initial berechnet..."); double protectedMinutes = calcMinutes(med, uv_index, lsf); maxMinutes = round(protectedMinutes); delay(250); return; } double newProtectedMinutes = calcMinutes(med, uv_index, lsf); currentMinutes = round((currentMinutes / maxMinutes) * newProtectedMinutes); maxMinutes = round(newProtectedMinutes); } } // nicht verbunden -> advertising erneut starten else if(oldConn) { oldConn = false; Serial.printf("! starte advertising\n"); BLEDevice::startAdvertising(); } delay(250); } double getUVIndex() { //double uv_index = uv.index(); double uv_index = 3; // Serial.println("UV-Index=" + String(uv_index)); return uv_index; } double calcMinutes(double med, double uv_index, double lsf) { double protectedMinutes = calcProtectedMinutes(lsf, calcSelfProtectionTime(med, uv_index)); maxIndex = int(uv_index); return protectedMinutes; } double calcSelfProtectionTime(double med, double uv_index) { return (med / (uv_index * 1.5)); } double calcProtectedMinutes(double lsf, double selfProtectionTime) { return (selfProtectionTime * lsf * 0.6); }