text
stringlengths
184
4.48M
<?php //Trabajamos con sesiones, empezamos poniendo session_start() session_start(); //Cargamos el Autoload de composer require dirname(__DIR__, 2)."/vendor/autoload.php"; use Libreria\Autores; function Hayerror($n, $a, $p) { $error = false; if (strlen($n) == 0) { $_SESSION['error_nombre'] = "Rellena el campo nombre"; $error = true; } if (strlen($a) == 0) { $_SESSION['error_apellidos'] = "Rellena el campo apellidos"; $error = true; } if (strlen($p) == 0) { $_SESSION['error_pais'] = "Rellena el campo pais"; $error = true; } return $error; } if (isset($_POST['crear'])) { # Procesamos el formulario $nombre = trim(ucwords($_POST['nombre'])); $apellidos = trim(ucwords($_POST['apellidos'])); $pais = trim(ucwords($_POST['pais'])); if (!Hayerror($nombre, $apellidos, $pais)) { # Podemos hacer el insert (new Autores)->setNombre($nombre) ->setApellidos($apellidos) ->setPais($pais) ->create(); //Mandamos un mensaje al index, diciendo que se ha creado con exito $_SESSION['mensaje'] = "Autor Creado con exito"; header("Location: index.php"); die(); } header("Location: {$_SERVER['PHP_SELF']}"); } else { # Pintamos el formulario ?> <!DOCTYPE html> <html lang="es"> <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"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Crear Autor</title> </head> <body style="background-color:silver"> <h3 class="text-center">Nuevo Autor</h3> <div class="container mt-2"> <form name="cautor" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <div class="bg-success text-white rounded p-4 shadow-lg m-auto" style="width:48rem"> <div class="mb-3"> <label for="nombreAutor" class="form-label">Nombre Autor</label> <input type="text" class="form-control" id="nombre" name="nombre" required placeholder="Nombre"> <?php if (isset($_SESSION['error_nombre'])) { echo <<< TEXTO <div class="mt-2 text-danger ft-bold" style="font-size:small"> {$_SESSION['error_nombre']} </div> TEXTO; unset($_SESSION['error_nombre']); } ?> </div> <div class="mb-3"> <label for="ApllidosAutor" class="form-label">Apellidos Autor</label> <input type="text" class="form-control" id="ape" name="apellidos" required placeholder="Apellidos"> <?php if (isset($_SESSION['error_apellidos'])) { echo <<< TEXTO <div class="mt-2 text-danger ft-bold" style="font-size:small"> {$_SESSION['error_apellidos']} </div> TEXTO; unset($_SESSION['error_apellidos']); } ?> </div> <div class="mb-3"> <label for="PaisAutor" class="form-label">Pais Autor</label> <input type="text" class="form-control" id="pais" name="pais" required placeholder="Pais"> <?php if (isset($_SESSION['error_pais'])) { echo <<< TEXTO <div class="mt-2 text-danger fw-bold" style="font-size:small"> {$_SESSION['error_pais']} </div> TEXTO; unset($_SESSION['error_pais']); } ?> </div> <div class="mb-3"> <button type="submit" class="btn btn-primary" name="crear"><i class="fas fa-save"></i> Crear</button> <button type="reset" class="btn btn-warning"><i class="fas fa-broom"></i> Limpiar</button> </div> </div> </form> </div> </body> </html> <?php } ?>
const { generatePages } = require('../info/inventory') const { reply } = require('../../utils/messageUtils') exports.command = { name: 'getinv', aliases: ['geti'], description: 'Fetches a users inventory.', long: 'Fetches a users inventory using their ID.', args: { 'User ID': 'ID of user to check.' }, examples: ['getinv 168958344361541633'], permissions: ['sendMessages', 'addReactions', 'embedLinks', 'externalEmojis'], ignoreHelp: false, requiresAcc: false, requiresActive: false, guildModsOnly: false, async execute (app, message, { args, prefix, guildInfo }) { const userID = args[0] if (!userID) { return reply(message, '❌ You forgot to include a user ID.') } const userInfo = await app.common.fetchUser(userID, { cacheIPC: false }) app.btnCollector.paginate(message, await generatePages(app, userInfo, message.channel.guild.id, undefined)) } }
import { Pipe, PipeTransform } from '@angular/core'; import { ValidationErrors } from '@angular/forms'; @Pipe({ name: 'validationErrors' }) export class ValidationErrorsPipe implements PipeTransform { transform(errors?: ValidationErrors | null, ...args: unknown[]): unknown { if (!!errors) { let messages = []; if (errors['required']) messages.push('Complete el campo'); if (errors['email']) messages.push('No es un formato valido'); if (errors['maxLength']) messages.push(`Max ${errors['maxLength']?.requiredLength} characters`); if (errors['minLength']) messages.push(`Min ${errors['minLength']?.requiredLength} characters`); return messages.join('. ') + '.'; } return null; } }
// // PanierViewController.swift // Animalss // // Created by Mac Mini on 14/1/2024. // import UIKit import CoreData class PanierViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource{ var animals = [String]() @IBOutlet weak var tablefav: UITableView! override func viewDidLoad() { super.viewDidLoad() fetchSuspects() tablefav.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return animals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCell(withIdentifier: "mCelll") let cv=cell?.contentView let imageAn=cv?.viewWithTag(1) as! UIImageView let nameAn=cv?.viewWithTag(2) as! UILabel imageAn.image=UIImage(named: animals[indexPath.row]) nameAn.text=animals[indexPath.row] return cell! } func fetchSuspects() { let appDelegate=UIApplication.shared.delegate as! AppDelegate let persistentContainer=appDelegate.persistentContainer let managedContext=persistentContainer.viewContext let request=NSFetchRequest<NSManagedObject>(entityName: "Animal") do{ let result = try managedContext.fetch(request) for item in result{ animals.append(item.value(forKey: "name") as! String) print(animals) } }catch{ print("topPlayers fetching error") } } // this method handles row deletion func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { let selectedProduct=animals[indexPath.row] if editingStyle == .delete { let confirmationAlert = UIAlertController(title: "Animal DELETED", message: "Voulez vous suprimer cet animal?", preferredStyle: .alert) confirmationAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) confirmationAlert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: { [weak self] _ in // Delete the suspect from Core Data self?.deleteSuspectFromCoreData(at: indexPath.row) // Remove the suspect from the arrays self?.animals.remove(at: indexPath.row) // Delete the table view row tableView.deleteRows(at: [indexPath], with: .fade) })) present(confirmationAlert, animated: true, completion: nil) } } func deleteSuspectFromCoreData(at index: Int) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let persistentContainer = appDelegate.persistentContainer let managedContext = persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Animal") request.predicate = NSPredicate(format: "name == %@", animals[index]) do { let result = try managedContext.fetch(request) if let objectToDelete = result.first as? NSManagedObject { managedContext.delete(objectToDelete) // Save the changes try managedContext.save() } } catch { print("Error deleting suspect from Core Data: \(error)") } } }
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hw_technical_test_2/blocs/banner_cubit/banner_cubit.dart'; import 'package:hw_technical_test_2/blocs/banner_cubit/banner_state.dart'; class BannerSection extends StatefulWidget { const BannerSection({super.key}); @override State<BannerSection> createState() => _BannerSectionState(); } class _BannerSectionState extends State<BannerSection> { @override void initState() { context.read<BannerCubit>().getListBanner(); super.initState(); } @override Widget build(BuildContext context) { return BlocBuilder<BannerCubit, BannerState>(builder: (context, state) { if (state.status == BannerCubitStatus.success) { return SizedBox( height: 300, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: state.listBanner.length, itemBuilder: (context, index) { final item = state.listBanner[index]; return Image.network(item.imgUrl); }, ), ); } else { return Container(); } }); } }
<?php /** * @file * Handling for cross-posting. */ /** * Shows either the status owner (if the status was posted to one's own profile) * or the status owner and status poster (if the status was posted elsewhere). * Also shows the user picture. */ class statuses_views_handler_field_cross_pic extends views_handler_field { function option_definition() { $options = parent::option_definition(); if (module_exists('imagecache_profiles')) { $options['imagecache_preset'] = array( 'default' => variable_get('user_picture_imagecache_profiles_default', ''), 'translatable' => FALSE, ); } return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); if (module_exists('imagecache_profiles')) { $options = $this->options; $form['imagecache_preset'] = array( '#title' => t('Image style'), '#type' => 'select', '#options' => image_style_options(TRUE), '#default_value' => $options['imagecache_preset'], ); } } function construct() { parent::construct(); $this->additional_fields['recipient'] = 'recipient'; $this->additional_fields['type'] = 'type'; } function render($values) { $recipient_id = $values->{$this->aliases['recipient']}; $sender_id = $values->{$this->field_alias}; $sender = user_load($sender_id); $type = $values->{$this->aliases['type']}; $options = $this->options; $preset = NULL; if (isset($options['imagecache_preset']) && $options['imagecache_preset']) { $preset = $options['imagecache_preset']; } if ($sender_id == $recipient_id && $type == 'user') { return t('!picture !user', array( '!picture' => '<span class="statuses-sender-picture">' . statuses_display_user_picture($sender, $preset) . '</span>', '!user' => '<span class="statuses-sender">' . theme('username', array('account' => $sender)) . '</span>', )); } elseif ($type == 'user') { $recipient = user_load($recipient_id); $args = array( '!sender' => '<span class="statuses-sender">' . theme('username', array('account' => $sender)) . '</span>', '!recipient' => '<span class="statuses-recipient">' . theme('username', array('account' => $recipient)) . '</span>', '!sender-picture' => '<span class="statuses-sender-picture">' . statuses_display_user_picture($sender, $preset) . '</span>', '!recipient-picture' => '<span class="statuses-recipient-picture">' . statuses_display_user_picture($recipient, $preset) . '</span>', ); return t('!sender-picture !sender &raquo; !recipient-picture !recipient', $args); } else { $context = statuses_determine_context($type); $recipient = $context['handler']->load_recipient($recipient_id); $args = array( '!sender' => '<span class="statuses-sender">' . theme('username', array('account' => $sender)) . '</span>', '!recipient' => '<span class="statuses-recipient">' . $context['handler']->recipient_link($recipient) . '</span>', '!sender-picture' => '<span class="statuses-sender-picture">' . statuses_display_user_picture($sender, $preset) . '</span>', ); return t('!sender-picture !sender &raquo; !recipient', $args); } } }
""" List type - lista Összetett adattípus, iterable object Mutable data type - megváltoztatható A lista tulajdonságai: - hozzá tudunk adni elemet / elemeket - törölni tudunk elemet / elemeket - módosítani tudunk meglévő elemet / elemeket """ my_list = [1, 2, 3, "Ricsi", (1, 4, 3, 5), [1, 3, "Karcsi"]] my_list = [] ############################################################### # elem hozzáadása listához # append utasítás - 1 elem hozzáadása my_list.append(10) my_list.append("Ricsi") my_list.append('Karcsi') my_list.append((1, 2, 3, 4)) # print(my_list) # több elem hozzáadása a listához my_list = [] # my_list.extend("Ricsi") my_list = [] my_list.extend((1, 2, 3, 4, "Ricsi", 'Karcsi')) # print(my_list) my_list = [] my_list.append((1, 2, 3, 4, "Ricsi", 'Karcsi')) # print(my_list) # megadott helyre történő elem beszúrása my_list = [1, 2, 3] # az insert nagyon költséges művelet my_list.insert(1, "Ricsi") # print(my_list) ############################################################### # elemek törlését # index mentén való törlés my_list = [5, 6, 4, 3, 2, 6, 1, 6] # ha nem adok a pop()-nak értéket, akkor az utolsó elemet törli a listából # ha nagyobb értéket adok meg, mint ahány elem van a listában, hibát kapok: index error my_list.pop(4) # OOP-nál ide visszatérünk del my_list[2:4] # érték mentén töröl # ha olyan elemet akarok törölni, ami nincs benne a listában, akkor hibát kapok my_list = [5, 6, 4, 3, 2, 6, 1, 6] my_list.remove(6) my_list.remove(6) my_list.remove(6) # minden elem törlése my_list.clear() ####################################################################### # meglévő elem módosítása my_list = [5, 6, 4, 3, 2, 6, 1, 6] # my_list[0] = "Ricsi" # my_list[0:3] = "Ricsi" # my_list[0:3] = ["Ricsi"] # my_list[0:3] = "Ricsi", "Pisti" # my_list[0:3] = "Ricsi", # my_list[0:3] = [] my_list[0:3] = "Ricsi", [] , "Pisti" # print(my_list) ################################################################# a = 10 b = a a = 30 # print(a) # print(b) # print(id(a)) # print(id(b)) ################################################################# my_list = [1, 2, 3, 4, 5] my_list2 = my_list # referencia, kétirányú -> bármelyiket módosítom, mind a kettő változni fog my_list2 = my_list[::] my_list.append(10) my_list2.pop(0) # print(my_list) # print(my_list2) # print(id(my_list[1])) # print(id(my_list2[0])) ################################# my_tup = (1, 2, 3, [4, 5, 6]) my_tup[3][1] = 10 # print(my_tup) ############################ my_list = [1, 2, 3, ["Ricsi", "Karcsi"], ["Ricsi", "Karcsi"]] my_list[3][0] = 'Jani' # print(id(my_list[3])) # print(id(my_list[4])) # print(my_list) # print(id(my_list[3][1])) # print(id(my_list[4][1])) ############################################################################# # index mentén gyorsan tudsz törölni # csak index mentén tudsz módosítani # töröld a 3 -as értéket my_list = [4, 5, 6, 3, 1, 2, 3] my_list.remove(3) # cnt = my_list.count(3) # print(cnt) # a 3-as értékeket módosítsd 7-re my_list = [4, 5, 6, 3, 1, 2, 3] # index(keresett_ertek, index_kezdopot, index_vege) # -> index_kezdopont és a index_vege opcionális idx = my_list.index(3, 1, 4) my_list[idx] = 7 print(my_list)
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/document/bucket/bucketid.h> #include <vespa/document/base/documentid.h> #include <vespa/searchlib/docstore/compacter.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/stllike/hash_set.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/log/log.h> LOG_SETUP("store_by_bucket_test"); using namespace search::docstore; using document::BucketId; using vespalib::compression::CompressionConfig; vespalib::string createPayload(BucketId b) { constexpr const char * BUF = "Buffer for testing Bucket drain order."; vespalib::asciistream os; os << BUF << " " << b; return os.str(); } uint32_t userId(size_t i) { return i%100; } BucketId createBucketId(size_t i) { constexpr size_t USED_BITS=5; vespalib::asciistream os; os << "id:a:b:n=" << userId(i) << ":" << i; document::DocumentId docId(os.str()); BucketId b = docId.getGlobalId().convertToBucketId(); EXPECT_EQUAL(userId(i), docId.getGlobalId().getLocationSpecificBits()); b.setUsedBits(USED_BITS); return b; } void add(StoreByBucket & sbb, size_t i) { BucketId b = createBucketId(i); vespalib::string s = createPayload(b); sbb.add(b, i%10, i, {s.c_str(), s.size()}); } class VerifyBucketOrder : public StoreByBucket::IWrite { public: VerifyBucketOrder() : _lastLid(0), _lastBucketId(0), _uniqueUser(), _uniqueBucket(){ } ~VerifyBucketOrder() override; void write(BucketId bucketId, uint32_t chunkId, uint32_t lid, vespalib::ConstBufferRef data) override { (void) chunkId; EXPECT_LESS_EQUAL(_lastBucketId.toKey(), bucketId.toKey()); if (_lastBucketId != bucketId) { EXPECT_TRUE(_uniqueBucket.find(bucketId.getRawId()) == _uniqueBucket.end()); _uniqueBucket.insert(bucketId.getRawId()); } if (userId(_lastLid) != userId(lid)) { EXPECT_TRUE(_uniqueUser.find(userId(lid)) == _uniqueUser.end()); _uniqueUser.insert(userId(lid)); } _lastLid = lid; _lastBucketId = bucketId; EXPECT_EQUAL(0, memcmp(data.data(), createPayload(bucketId).c_str(), data.size())); } private: uint32_t _lastLid; BucketId _lastBucketId; vespalib::hash_set<uint32_t> _uniqueUser; vespalib::hash_set<uint64_t> _uniqueBucket; }; VerifyBucketOrder::~VerifyBucketOrder() = default; struct StoreIndex : public StoreByBucket::StoreIndex { ~StoreIndex() override; void store(const StoreByBucket::Index &index) override { _where.push_back(index); } std::vector<StoreByBucket::Index> _where; }; StoreIndex::~StoreIndex() = default; struct Iterator : public StoreByBucket::IndexIterator { explicit Iterator(const std::vector<StoreByBucket::Index> & where) : _where(where), _current(0) {} bool has_next() noexcept override { return _current < _where.size(); } StoreByBucket::Index next() noexcept override { return _where[_current++]; } const std::vector<StoreByBucket::Index> & _where; uint32_t _current; }; TEST("require that StoreByBucket gives bucket by bucket and ordered within") { std::mutex backing_lock; vespalib::MemoryDataStore backing(vespalib::alloc::Alloc::alloc(256), &backing_lock); vespalib::ThreadStackExecutor executor(8); StoreIndex storeIndex; StoreByBucket sbb(storeIndex, backing, executor, CompressionConfig::LZ4); for (size_t i(1); i <= 500u; i++) { add(sbb, i); } for (size_t i(1000); i > 500u; i--) { add(sbb, i); } sbb.close(); std::sort(storeIndex._where.begin(), storeIndex._where.end()); EXPECT_EQUAL(1000u, storeIndex._where.size()); VerifyBucketOrder vbo; Iterator all(storeIndex._where); sbb.drain(vbo, all); } constexpr uint32_t NUM_PARTS = 3; void verifyIter(BucketIndexStore &store, uint32_t partId, uint32_t expected_count) { auto iter = store.createIterator(partId); uint32_t count(0); while (iter->has_next()) { StoreByBucket::Index idx = iter->next(); EXPECT_EQUAL(store.toPartitionId(idx._bucketId), partId); count++; } EXPECT_EQUAL(expected_count, count); } TEST("test that iterators cover the whole corpus and maps to correct partid") { BucketIndexStore bucketIndexStore(32, NUM_PARTS); for (size_t i(1); i <= 500u; i++) { bucketIndexStore.store(StoreByBucket::Index(createBucketId(i), 1, 2, i)); } bucketIndexStore.prepareForIterate(); EXPECT_EQUAL(500u, bucketIndexStore.getLidCount()); EXPECT_EQUAL(32u, bucketIndexStore.getBucketCount()); constexpr uint32_t COUNT_0 = 175, COUNT_1 = 155, COUNT_2 = 170; verifyIter(bucketIndexStore, 0, COUNT_0); verifyIter(bucketIndexStore, 1, COUNT_1); verifyIter(bucketIndexStore, 2, COUNT_2); EXPECT_EQUAL(500u, COUNT_0 + COUNT_1 + COUNT_2); } TEST_MAIN() { TEST_RUN_ALL(); }
#include <assert.h> #ifndef FACTORIAL_H #define FACTORIAL_H /** @brief Calculate the factorial of a number. @param num The number for which factorial is to be calculated. @return The factorial of the number. @pre num must be a non-negative number. @note This function is suitable for numbers up to 20. For numbers > 20 use the functions factoriallf() that use double precision float to store the result, allowing numbers grether than 9223372036854776000 to be represented using exponential form. */ long long factorial(int num) { long long result = 1; int i; assert(num >= 0); for (i = 1; i <= num; i++) result *= i; return result; } /** @brief Calculate the factorial of a number using double precision. @param num The number for which factorial is to be calculated. @return The factorial of the number. @pre num must be a non-negative number (double precision). */ double factoriallf(int num) { double result = 1; int i; assert(num >= 0); for (i = 1; i <= num; i++) result *= i; return result; } #endif /* FACTORIAL_H */
/* eslint-disable react/jsx-props-no-spreading */ import styled from 'styled-components'; import { Link } from 'react-router-dom'; import { nanoid } from 'nanoid'; import numberFormat from '../utils/NumberFormat'; import optionPriceFormat from '../utils/OptionPriceFormat'; import defaultTheme from '../styles/DefaultTheme'; import useOrderFormStore from '../hooks/useOrderFormStore'; const Container = styled.div` margin-bottom: 6em; min-width: 980px; `; const Table = styled.table` border-top: 1px solid ${defaultTheme.colors.fourth}; border-bottom: 1px solid ${defaultTheme.colors.fourth} ; width: 100%; border-collapse: collapse; thead { font-size: .9em; border-bottom: 1px solid ${defaultTheme.colors.fourth}; height: 2.5em; } th, td { vertical-align: middle; text-align: center; font-size: .9em; color: ${defaultTheme.colors.sixth}; } tr { border-bottom: 1px solid ${defaultTheme.colors.fourth}; font-size: 1.1em; } th:nth-child(1) { width: 50%; } td:nth-child(1) { text-align: left; position: relative; } th:nth-child(3) { width: 10%; } td:nth-child(3) { display: flex; justify-content: center; align-items: center; } th:nth-child(4) { width: 15%; } td { /* border-right: 1px solid ${defaultTheme.colors.fourth}; */ height: 8em; div { display: flex; gap: .5em; } } td:last-child { border: none; } strong { font-size: 1.3em; font-weight: 700; margin-bottom: .5em; color: ${defaultTheme.colors.primary}; } `; const Item = styled(Link)` width: 18%; display: flex; align-items: center; color: ${defaultTheme.colors.primary}; `; const ImageContainer = styled.div` width: 6em; height: 6em; padding: .5em; margin-right: 1em; display: flex; align-items: center; border: 1px solid ${defaultTheme.colors.fourth}; `; const ProductInformation = styled.div` display: flex; flex-direction: column; justify-content: center; gap: .3em; `; export default function OrderProducts() { const orderFormStore = useOrderFormStore(); const { orderProducts } = orderFormStore; return ( <Container> <Table> <thead> <tr> <th>상품 정보</th> <th>옵션</th> <th>수량</th> <th>금액</th> </tr> </thead> <tbody> {orderProducts.map((item) => ( <tr key={nanoid()}> <td> <div> <Item to={`/products/${item.productId}`}> <ImageContainer> <img src={item.image} alt={item.name} height={68} width={68} /> </ImageContainer> </Item> <ProductInformation> <p>{item.name}</p> <p> {numberFormat(item.price)} 원 </p> </ProductInformation> </div> </td> <td> {item.optionName} {' '} {optionPriceFormat(item.optionPrice)} </td> <td> <p> {item.quantity} </p> </td> <td> {numberFormat((item.price + item.optionPrice) * item.quantity)} 원 </td> </tr> ))} </tbody> </Table> </Container> ); }
package com.example.imagetopdf.Adpters; import android.annotation.SuppressLint; import android.app.Activity; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.Priority; import com.bumptech.glide.request.RequestOptions; import com.example.imagetopdf.Class.imageModel; import com.example.imagetopdf.InterFace.FolderClickListener; import com.example.imagetopdf.R; import java.io.File; import java.util.ArrayList; public class ImageFolderAdapter extends RecyclerView.Adapter<ImageFolderAdapter.ViewHolder> { Activity activity; ArrayList<imageModel> objects = new ArrayList<>(); ArrayList<imageModel> filter = new ArrayList<>(); FolderClickListener Interface; RequestOptions options = new RequestOptions(); public ImageFolderAdapter(Activity activity,FolderClickListener Interface){ this.activity = activity; this.Interface = Interface; options = new RequestOptions(); } @NonNull @Override public ImageFolderAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(activity).inflate(R.layout.folder_view, parent, false); return new ViewHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull ImageFolderAdapter.ViewHolder holder, int position) { imageModel imageModel = filter.get(position); if (imageModel.getPathList().size() > 0){ Uri uri = Uri.fromFile(new File(imageModel.getPathList().get(0))); try { Glide.with(activity) .load(uri) .apply(options.centerCrop() .skipMemoryCache(true) .priority(Priority.LOW)) .into(holder.img); } catch (Exception e){ Glide.with(activity) .load(uri) .apply(options.centerCrop() .skipMemoryCache(true) .priority(Priority.LOW)) .into(holder.img); } holder.text.setText(imageModel.getBucketName()); holder.count.setText(imageModel.getPathList().size() + ""); holder.itemView.setOnClickListener(v -> { Interface.onFolderClick(imageModel,position); }); } } @Override public int getItemCount() { return filter.size(); } @Override public int getItemViewType(int position) { int val = 0; try { if (filter != null && filter.size() > 0) { val = filter.get(position).getType(); } else { val = 0; } } catch (Exception w) { } return val; } @SuppressLint("NotifyDataSetChanged") public void addAll(ArrayList<imageModel> itemData) { objects = new ArrayList<>(); objects.addAll(itemData); filter = new ArrayList<>(); filter.addAll(itemData); notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView img; TextView text,count; public ViewHolder(@NonNull View itemView) { super(itemView); img = itemView.findViewById(R.id.img); text = itemView.findViewById(R.id.text); count = itemView.findViewById(R.id.count); } } }
<template> <div class="propro"> <h2>xlsx</h2> <el-button @click="exportData">导出Excel</el-button> <!-- <el-upload>导入文件Excel</el-upload> --> <el-table :data="tableData" style="width: 100%"> <el-table-column prop="date" label="Date" width="180" /> <el-table-column prop="name" label="Name" width="180" /> <el-table-column prop="address" label="Address" /> </el-table> </div> </template> <script setup> // import xlsx from "xlsx"; // 报错 没有默认导出 // import * as xlsx from "xlsx"; import jsonToExcel from "@/utils/jsonToExcel"; const tableData = [ { date: "2016-05-03", name: "大大怪将军", address: "No. 189, Grove St, Los Angeles", }, { date: "2016-05-02", name: "小小怪下士", address: "No. 189, Grove St, Los Angeles", }, { date: "2016-05-04", name: "粗心超人", address: "No. 189, Grove St, Los Angeles", }, { date: "2016-05-01", name: "开行超人", address: "No. 189, Grove St, Los Angeles", }, ]; const header = { date: "时间", name: "名字", address: "地点", }; const exportData = () => { console.log("导出数据"); jsonToExcel(tableData, header); }; const list = [ { id: 1001, parentId: 0, name: "中国", }, { id: 1002, parentId: 1001, name: "湖南", }, { id: 1003, parentId: 1001, name: "广东", }, { id: 1004, parentId: 1003, name: "广州市", }, { id: 1005, parentId: 1003, name: "佛山市", }, { id: 1006, parentId: 1002, name: "长沙市", }, { id: 1007, parentId: 1002, name: "湘潭市", }, { id: 1008, parentId: 1004, name: "天河区", }, { id: 1009, parentId: 1005, name: "顺德区", }, ]; // console.log(list); const listToTree = (data) => { let obj = {}; data.map((item) => { obj[item.id] = item; }); // console.log(obj); let res = []; data.map((item) => { debugger; const parent = obj[item.parentId]; // console.log(parent); if (parent) { // 判断parent中有没有children 没有则创建 有就直接把item push到children里 parent.children = parent.children || []; parent.children.push(item); } else { res.push(item); } console.log("res", res); }); return res; }; listToTree(list); </script> <style lang="less" scoped></style>
import React, { useEffect, useState } from 'react' import Button from 'react-bootstrap/Button'; import Modal from 'react-bootstrap/Modal'; import Form from 'react-bootstrap/Form'; import { useFirebase } from '@/context/backend'; import { useRouter } from 'next/router'; const addUserType = async (em) => { const res = await fetch('https://bqbuyweqp1.execute-api.ap-south-1.amazonaws.com/default/add_user_type_jobportal', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "email": String(em), "userType": "candidate" }) }) const result = await res.json(); } function SignupPage(props) { const router = useRouter(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const firebase = useFirebase(); const handelSubmit = async (e) => { e.preventDefault(); firebase.signUpWithEmailAndPass(email, password) .then((userCredential) => { // Signed up const user = userCredential.user; addUserType(user.email); // ... if (props.shownewpage != "false") router.replace('/alljobs') }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; alert(errorMessage) // .. }); props.onHide(); } const signupGoogle = async (e) => { e.preventDefault(); firebase.signinWithGoogle() .then(res => { const user = res.user; addUserType(user.email); if (props.shownewpage != "false") router.replace('/alljobs') }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; const email = error.customData.email; const credential = GoogleAuthProvider.credentialFromError(error); alert(errorMessage) }); props.onHide(); } return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> Sign Up </Modal.Title> </Modal.Header> <Modal.Body> <Form onSubmit={handelSubmit}> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> <Form.Control onChange={e => setEmail(e.target.value)} type="email" value={email} placeholder="Enter email" /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <Form.Control onChange={e => setPassword(e.target.value)} value={password} type="password" placeholder="Password" /> </Form.Group> <Button variant="primary" type="submit"> Sign Up </Button> </Form> <Button variant="danger" className='my-3' type="button" onClick={signupGoogle}> Sign Up with Google </Button> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ) } export default SignupPage
import PropTypes from 'prop-types'; import ImageGalleryItem from '../ImageGalleryItem/ImageGalleryItem'; import style from '../styles.module.css'; const ImageGallery = ({images, openModal, }) => { return ( <ul className={style.ImageGallery}> {images.map(({id, webformatURL, largeImageURL, tags}) => ( <ImageGalleryItem key={id} webformatURL={webformatURL} openModal={() => openModal(largeImageURL, tags)} tag={tags} /> ))} </ul> ) } export default ImageGallery ImageGallery.propTypes = { images: PropTypes.arrayOf(PropTypes.shape({id:PropTypes.number.isRequired})), openModal: PropTypes.func.isRequired, }
<script> import { getContext } from 'svelte'; import { formatJSON, codeMirrorUtils } from '$lib/utils'; import { codemirror, withCodemirrorInstance } from '@neocodemirror/svelte'; import { json } from '@codemirror/lang-json'; import { yaml } from '@codemirror/legacy-modes/mode/yaml'; import { StreamLanguage } from '@codemirror/language'; const { setPageTitle } = getContext('root'); setPageTitle('YAML to JSON'); let leftEditor = withCodemirrorInstance(); let rightEditor = withCodemirrorInstance(); let errMsg = ''; let YAML; let sortKeys = false; let forceQuotes = false; let noArrayIndent = false; function toJSON() { errMsg = ''; const yamlVal = codeMirrorUtils.getValue($leftEditor); if (yamlVal.length > 0) { codeMirrorUtils.setFirst($leftEditor); try { let jsonVal = YAML.load(yamlVal); jsonVal = formatJSON(jsonVal, 2, true); codeMirrorUtils.setValue($rightEditor, jsonVal) codeMirrorUtils.selectAll($rightEditor) } catch (err) { errMsg = err; } } } function toYAML() { errMsg = ''; const jsonVal = codeMirrorUtils.getValue($rightEditor); if (jsonVal.length > 0) { codeMirrorUtils.setFirst($rightEditor); try { const obj = JSON.parse(jsonVal); let yamlVal = YAML.dump(obj, { indent: 2, sortKeys, noArrayIndent, forceQuotes }); codeMirrorUtils.setValue($leftEditor, yamlVal) codeMirrorUtils.selectAll($leftEditor) } catch (err) { errMsg = err; } } } const loadExternal = () => { YAML = globalThis.jsyaml; }; </script> <svelte:head> <script src="https://cdn.jsdelivr.net/npm/js-yaml@4.1.0/dist/js-yaml.min.js" on:load={loadExternal} ></script> </svelte:head> <div class="container mx-auto px-4"> <button class="btn-blue" on:click={toJSON}>toJSON</button> <button class="btn-blue" on:click={toYAML}>toYAML</button> <label for="sortKeys"> <input type="checkbox" id="sortKeys" bind:checked={sortKeys} /> sort keys </label> <label for="forceQuotes"> <input type="checkbox" id="forceQuotes" bind:checked={forceQuotes} /> force quotes </label> <label for="noArrayIndent"> <input type="checkbox" id="noArrayIndent" bind:checked={noArrayIndent} /> no array indent </label> <div class="leading-relaxed block text-red-500 font-mono"> {errMsg} </div> <div class="flex flex-wrap flex-row flex-1 space-x-0 justify-between items-stretch xl:space-x-2 xl:flex-nowrap"> <fieldset class="border border-gray-300 flex-none overflow-hidden bg-zinc-100 basis-full xl:basis-1/2"> <legend class="pr-2 font-semibold text-gray-400">YAML</legend> <div class="codemirror-editor" use:codemirror={{ value: '', tabSize: 2, instanceStore: leftEditor, extensions: [...codeMirrorUtils.baseExtensions, StreamLanguage.define(yaml)] }} /> </fieldset> <fieldset class="border border-gray-300 flex-none overflow-hidden bg-zinc-100 basis-full xl:basis-1/2"> <legend class="pr-2 font-semibold text-gray-400">JSON</legend> <div class="codemirror-editor" use:codemirror={{ value: '', lang: json(), tabSize: 2, instanceStore: rightEditor, extensions: codeMirrorUtils.baseExtensions }} /> </fieldset> </div> </div>
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>@yield('title')</title> <meta name="description" content="¡Mide tus entrenamientos con efectividad con Worflow!"> <meta name="keywords" content="entrenamiento, powerlifting, entrenamiento con pesas, gimnasio, deporte, salud, 'registrar entrenamiento'"> <link rel="icon" type="image/png" href="https://tailwindui.com/img/logos/workflow-mark-indigo-500.svg"> <meta property="og:title" content="Mide tus entrenamientos en el gimnasio con Workflow"> <meta property="og:description" content="Workflow es una aplicación web diseñada para todas aquellas personas que quieren llevar un reegistro completo, actualizado y escalable de sus entrenamientos."> <meta property="og:image" content=""> <meta property="og:type" content="website"> <meta property="og:url" content="https://workflow.adriangutierrezd.com"> <meta name="robots" content="noindex"> <!-- Fonts --> <link rel="stylesheet" href="https://use.typekit.net/nqz3mby.css"> {{-- Icons --}} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <!-- Styles --> <link rel="stylesheet" href="{{ mix('css/app.css') }}"> @livewireStyles <!-- Scripts --> <script src="{{ mix('js/app.js') }}" defer></script> <!-- Charting library --> <script src="https://unpkg.com/echarts/dist/echarts.min.js"></script> <!-- Chartisan --> <script src="https://unpkg.com/@chartisan/echarts/dist/chartisan_echarts.js"></script> <!-- Sweet Alert --> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> </head> <body class="font-sans antialiased"> <x-jet-banner /> @livewire('cookies') <div class="min-h-screen bg-gray-100"> <x-app-navigation></x-app-navigation> <!-- Page Content --> <main class="container py-8"> {{ $slot }} </main> <x-footer></x-footer> </div> @livewireScripts @stack('modals') @stack('scripts') @isset($_COOKIE['marketing']) {{-- Google Analytics Script --}} @endisset </body> </html>
import React from 'react'; import { View } from 'react-native'; import { AllHtmlEntities } from 'html-entities'; import { RadioButton } from 'components/RadioButton'; import { RadioWrapper, RadioWithLabel, RadioLabel } from './styles'; import { RadioGroupProps } from './types'; const entities = new AllHtmlEntities(); export const RADIO_WRAPPER_TEST_ID = 'radio-wrapper'; export const RadioGroup: React.FC<RadioGroupProps> = (props) => { const { options, onSelect, questionIndex } = props; return ( <View> {options.map(({ value, title, selected_answer }, i) => { const index: number = questionIndex !== undefined ? questionIndex : i; return ( <RadioWrapper key={value} testID={RADIO_WRAPPER_TEST_ID}> <RadioWithLabel onPress={() => onSelect(value, index)}> <RadioButton isSelected={selected_answer === value} /> <RadioLabel>{entities.decode(title)}</RadioLabel> </RadioWithLabel> </RadioWrapper> ); })} </View> ); };
"""All pyproject.toml wrangling.""" import functools import logging from typing import Any, Optional, cast import toml logger = logging.getLogger(__name__) @functools.cache def current_pyproject_toml(toml_file_path: str) -> Optional[dict[str, Any]]: """Load and cache pyproject.toml file.""" try: with open(toml_file_path, encoding="utf-8") as file: data = toml.load(file) except FileNotFoundError: print(f"'{toml_file_path}' not found.") return None return data def get_project_info_from_toml(toml_file_path: str = "pyproject.toml", use_pep621: bool = False) -> tuple[str, str]: """Read the pyproject.toml and return the project name and version based on priority.""" data = current_pyproject_toml(toml_file_path) if not data: return "", "" # Doesn't handle if both are present if use_pep621: # Check PEP 621 standardized fields first project_name = data.get("project", {}).get("name", "") project_version = data.get("project", {}).get("version", "") # Fallback to Poetry-specific fields if not found if not project_name: project_name = data.get("tool", {}).get("poetry", {}).get("name", "") if not project_version: project_version = data.get("tool", {}).get("poetry", {}).get("version", "") else: # Check Poetry-specific fields first project_name = data.get("tool", {}).get("poetry", {}).get("name", "") project_version = data.get("tool", {}).get("poetry", {}).get("version", "") # Fallback to PEP 621 standardized fields if not found if not project_name: project_name = data.get("project", {}).get("name", "") if not project_version: project_version = data.get("project", {}).get("version", "") # if not project_name or not project_version: # raise ValueError("Project name and/or version not found in pyproject.toml") return project_name, project_version def own_package_includes(toml_file_path: str = "pyproject.toml") -> list[str]: """Read the pyproject.toml and return the project name and version.""" # Load the pyproject.toml content data = current_pyproject_toml(toml_file_path) if not data: return [] poetry_tool = data.get("tool", {}).get("poetry", {}) includes = poetry_tool.get("include", []) return cast(list[str], [includes] if isinstance(includes, str) else includes) def toml_section_exists(toml_file_path: str = "pyproject.toml") -> bool: """Check we have a pyproject.toml file""" data = current_pyproject_toml(toml_file_path) if not data: return False # Check if the [tool.raypack] section exists raypack_config = data.get("tool", {}).get("raypack", {}) if raypack_config: return True return False # Read and override the default configuration from pyproject.toml, if available def override_config_from_toml(config: dict[str, Any], toml_file_path: str = "pyproject.toml") -> None: """Read the pyproject.toml and override the default CONFIG values.""" data = current_pyproject_toml(toml_file_path) if not data: print(f"'{toml_file_path}' not found. Using default configuration.") return # Check if the [tool.raypack] section exists raypack_config = data.get("tool", {}).get("raypack", {}) # Override the default CONFIG values with the values from the toml file config |= raypack_config
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let fixture: ComponentFixture<AppComponent>; let app: AppComponent; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [AppComponent]}).compileComponents() .then(() => { fixture = TestBed.createComponent(AppComponent); app = fixture.componentInstance; }) })) it('should create app', () => { expect(app).toBeTruthy(); }); it(`should have as title 'teco'`, () => { expect(app.title).toEqual('teco'); }); it('should render title', () => { fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('.content span')?.textContent).toContain('teco app is running!'); }); })
package designpattern.flyweight; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; public class TrafficSimulator { static List<Vehicle> vehicles; static Logger logger; static { vehicles = new ArrayList<>(); logger = Logger.getLogger(TrafficSimulator.class.getName()); System.setProperty("java.util.logging.SimpleFormatter.format", //"[%1$tF %1$tT] [%4$-7s] %5$s %n"); "[%1$tF %1$tl:%1$tM:%1$tS.%1$tL] [%4$-6s] %5$s %n"); } public static void main(String... args) { Thread createVehicle = new Thread( () -> { createVehicleAtRandom(); } ); Thread removeVehicle = new Thread( () -> { removeVehicle(); } ); createVehicle.setName("CREATE"); removeVehicle.setName("REMOVE"); // Scheduling entries and exit from Traffic ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(createVehicle, 0, 2, TimeUnit.SECONDS); executor.scheduleAtFixedRate(removeVehicle, 5, 2, TimeUnit.SECONDS); } public static void createVehicleAtRandom() { Random random = new Random(); int nextInt = random.nextInt(2); // values within 2 Vehicle vehicle; if (nextInt == 0) { vehicle = new Car("Ford"); } else { vehicle = new Truck("Eicher"); } vehicle.setLocation(random.nextInt(1000), random.nextInt(1000)); logger.log(Level.INFO, "A new " + vehicle.getType() + " is added in Traffic, location ->" + Arrays.toString(vehicle.getLocation())); vehicles.add(vehicle); } public static void removeVehicle() { Vehicle removedOne = vehicles.remove(0); logger.log(Level.INFO, "A " + removedOne.getType() + " is removed from Traffic, location ->" + Arrays.toString(removedOne.getLocation())); } }
<template> <section class="card" :class="{ 'has-rating': selectedRate && submitted }" > <template v-if="!selectedRate || !submitted"> <div class="star"> <img src="@/assets/icon-star.svg" alt="star" /> </div> <h1>How did we do?</h1> <p> Please let us know how we did with your support request. All feedback is appreciated to help us improve our offering! </p> <ol class="ratings"> <li v-for="(rate, rateKey) in ratings" :key="rateKey" @click="selectedRate = rate" :class="{ 'is-active': selectedRate === rate }" > {{ rate }} </li> </ol> <button @click="submitted = true"> SUBMIT </button> </template> <template v-else> <img src="@/assets/illustration-thank-you.svg" alt="thank you" class="card__thankyou" /> <span class="card__rate"> You selected {{ selectedRate }} out of 5 </span> <h2>Thank you!</h2> <p> We appreciate you taking the time to give a rating. If you ever need more support, don’t hesitate to get in touch! </p> </template> </section> </template> <style lang="scss"> @import '@/sass/style.scss'; </style> <script lang="ts"> export default { data: () => ({ ratings: 5, selectedRate: 0, submitted: false }) } </script>
from django.db import models from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.utils.text import slugify from taggit.managers import TaggableManager from core.models import PublishableBaseModel, ImageBaseModel from properties.utils import property_images # Create your models here. class Property(PublishableBaseModel): """ Any object that generate income and expense For see by public if published """ title = models.CharField(max_length=50, help_text="Property user friendly identity") type = TaggableManager( verbose_name='Type Tags', help_text="Property type tags since property can fall into multiple category" ) slug = models.SlugField(unique=True, db_index=True) description = models.TextField(null=True, blank=True) sqft_size = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True, help_text="Size in square foots") date_build = models.DateField(null=True, blank=True) amenities = models.TextField(null=True, blank=True, help_text="Comma separated amenities") location = models.ForeignKey("properties.Location", on_delete=models.CASCADE, related_name='properties') def primary_image(self): images = self.images.filter(is_primary=True) return images.first() if images.exists() else None def __str__(self): return self.title class Meta: ordering = ('-created_at',) verbose_name_plural = "Properties" @receiver(post_save, sender=Property) def update_slug_on_save(sender, instance, **kwargs): """ Signal receiver to update the slug after a Property instance is saved. """ # Disconnect the post_save signal temporarily post_save.disconnect(update_slug_on_save, sender=Property) # Update the slug instance.slug = slugify(f"{instance.title}-{instance.id}") instance.save(update_fields=['slug']) # Reconnect the post_save signal post_save.connect(update_slug_on_save, sender=Property) class PropertyImage(ImageBaseModel): image = models.ImageField(null=False, blank=False, upload_to=property_images) property = models.ForeignKey("properties.Property", on_delete=models.CASCADE, related_name='images') def __str__(self): return f"{self.property.title} image" class PropertyAttribute(models.Model): property = models.ForeignKey('properties.Property', on_delete=models.CASCADE, related_name='attributes') name = models.CharField(max_length=255) value = models.CharField(max_length=255) class Meta: unique_together = ('property', 'name') ordering = ('-name',) class Location(models.Model): address = models.CharField(max_length=255) city = models.CharField(max_length=100) state = models.CharField(max_length=100) country = models.CharField(max_length=100) zip_code = models.CharField(max_length=20) longitude = models.DecimalField(max_digits=22, decimal_places=16) latitude = models.DecimalField(max_digits=22, decimal_places=16) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.address}, {self.city}, {self.state}, {self.country}, {self.zip_code}" class Meta: ordering = ('-created_at',)
package site.metacoding.white.web; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import site.metacoding.white.dto.UserReqDto.JoinReqDto; @ActiveProfiles("test") // @Transactional // 통합테스트에서 RANDOM_PORT를 사용하면 새로운 스레드로 돌기 때문에 rollback 무의미 @Sql("classpath:truncate.sql") @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class UserApiControllerTest { @Autowired private TestRestTemplate rt; @Autowired private ObjectMapper om; private static HttpHeaders headers; @BeforeAll public static void init() { headers = new HttpHeaders(); // http 요청 header에 필요 headers.setContentType(MediaType.APPLICATION_JSON); } @Order(1) @Test public void join_test() throws JsonProcessingException { // given JoinReqDto joinReqDto = new JoinReqDto(); joinReqDto.setUsername("very"); joinReqDto.setPassword("1234"); String body = om.writeValueAsString(joinReqDto); System.out.println(body); // when HttpEntity<String> request = new HttpEntity<>(body, headers); ResponseEntity<String> response = rt.exchange("/join", HttpMethod.POST, request, String.class); // then // System.out.println(response.getStatusCode()); // System.out.println(response.getBody()); DocumentContext dc = JsonPath.parse(response.getBody()); // System.out.println(dc.jsonString()); Integer code = dc.read("$.code"); Assertions.assertThat(code).isEqualTo(1); } @Order(2) @Test public void join_test2() throws JsonProcessingException { // given JoinReqDto joinReqDto = new JoinReqDto(); joinReqDto.setUsername("very"); joinReqDto.setPassword("1234"); String body = om.writeValueAsString(joinReqDto); System.out.println(body); // when HttpEntity<String> request = new HttpEntity<>(body, headers); ResponseEntity<String> response = rt.exchange("/join", HttpMethod.POST, request, String.class); // then // System.out.println(response.getStatusCode()); // System.out.println(response.getBody()); DocumentContext dc = JsonPath.parse(response.getBody()); // System.out.println(dc.jsonString()); Integer code = dc.read("$.code"); Assertions.assertThat(code).isEqualTo(1); } }
import { Component } from 'react'; import PropTypes from 'prop-types'; import css from '../ContactForm/ContactForm.module.css'; class ContactForm extends Component { state = { name: '', number: '', }; handleChange = ({ target: { name, value } }) => { this.setState({ [name]: value }); }; handleSubmit = e => { e.preventDefault(); this.props.addContact({ ...this.state }); this.setState({ name: '', number: '' }); }; render() { const { name, number } = this.state; return ( <form onSubmit={this.handleSubmit} className={css.form}> <label className={css.label}> Name <input className={css.input} type="text" name="name" pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan" required placeholder="Enter name" value={name} onChange={this.handleChange} /> </label> <label className={css.label}> Number <input className={css.input} type="tel" name="number" pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}" title="Phone number must be digits and can contain spaces, dashes, parentheses and can start with +" required placeholder="Enter number" value={number} onChange={this.handleChange} /> </label> <button type="submit" disabled={!name || !number} className={css.submitButton} > Add contact </button> </form> ); } } ContactForm.propTypes = { addContact: PropTypes.func.isRequired, }; export default ContactForm;
package models import "time" type Billing struct { ID uint `json:"id" gorm:"primaryKey;autoIncrement" example:"1"` CompanyID uint `json:"company_id" gorm:"type:integer" example:"1"` Company Company `json:"company" gorm:"foreignKey:CompanyID"` Amount float64 `json:"amount" gorm:"type:float" example:"900.25"` // Available options: paid, unpaid, pending Status string `json:"status" gorm:"type:varchar(10)" example:"paid"` Comments string `json:"comments" gorm:"type:varchar(1000)" example:"Something about the invoice..."` // TODO - Check Stripe transaction ID standards for better example and update varchar length TransactionID string `json:"transaction_id" gorm:"type:varchar(100)" example:"12345678"` DueAt time.Time `json:"due_at" example:"2020-01-01T00:00:00Z"` IssuedAt time.Time `json:"issued_at" example:"2020-01-01T00:00:00Z"` CreatedAt time.Time `json:"created_at" example:"2020-01-01T00:00:00Z"` UpdatedAt time.Time `json:"updated_at" example:"2020-01-01T00:00:00Z"` } func GetBillings() ([]Billing, error) { var billings []Billing if err := DB.Preload("Company").Find(&billings).Error; err != nil { return nil, err } return billings, nil } func GetBilling(id uint) (*Billing, error) { var billing Billing if err := DB.Preload("Company").First(&billing, id).Error; err != nil { return nil, err } return &billing, nil } func GetBillingsByCompanyID(id uint) ([]Billing, error) { var billings []Billing if err := DB.Preload("Company").Where("company_id = ?", id).Find(&billings).Error; err != nil { return nil, err } return billings, nil } func (b *Billing) CreateBilling() error { err := DB.Create(&b).Error if err != nil { return err } return nil } func (b *Billing) UpdateBilling() (*Billing, error) { err := DB.Updates(&b).Error if err != nil { return nil, err } return b, nil } func (b *Billing) DeleteBilling() error { err := DB.Delete(&b).Error if err != nil { return err } return nil }
import nltk cfg = nltk.CFG.fromstring(""" S -> NP VP NP -> Det N | 'John' VP -> V NP Det -> 'the' | 'a' N -> 'dog' | 'ball' V -> 'chased' | 'caught' """) parser = nltk.ChartParser(cfg) def generate_parse_tree(sentence): words = sentence.split() trees = list(parser.parse(words)) if not trees: print(f"No parse tree found for the sentence: {sentence}") else: for tree in trees: print("Parse Tree:") tree.pretty_print() generate_parse_tree("the dog chased a ball")
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <data> <variable name="backListener" type="com.creative.share.apps.alforat.interfaces.Listeners.BackListener"/> <variable name="lang" type="String" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/gray1"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="0dp" android:layout_height="56dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" android:background="@color/colorPrimary" app:contentInsetEnd="0dp" app:contentInsetStart="0dp" app:contentInsetLeft="0dp" app:contentInsetRight="0dp" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:onClick="@{()->backListener.back()}" > <ImageView android:layout_width="35dp" android:layout_height="35dp" android:src="@drawable/ic_arrow_left" android:tint="@color/white" android:padding="8dp" android:clickable="false" android:longClickable="false" android:rotation='@{lang.equals("ar")?180:0}' /> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginStart="5dp" android:layout_marginEnd="5dp" android:textColor="@color/white" android:clickable="false" android:longClickable="false" android:textSize="16sp" android:text="@string/clients" /> </LinearLayout> <ImageView android:id="@+id/imageAddClient" android:layout_width="45dp" android:layout_height="45dp" android:layout_gravity="end" android:src="@drawable/ic_add" android:padding="15dp" android:tint="@color/white" /> </androidx.appcompat.widget.Toolbar> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@id/toolbar" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:layout_marginTop="8dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:orientation="horizontal" android:padding="5dp" android:background="@drawable/report_container_bg" android:weightSum="1" > <ImageView android:layout_width="0dp" android:layout_weight=".15" android:layout_height="40dp" android:tint="@color/colorPrimary" android:src="@drawable/ic_search" android:padding="8dp" /> <EditText android:id="@+id/edSearch" android:layout_width="0dp" android:layout_weight=".75" android:layout_height="match_parent" android:background="@color/white" android:paddingLeft="8dp" android:paddingRight="8dp" android:hint="@string/search" android:textColorHint="@color/gray4" android:textColor="@color/black" android:textSize="14sp" android:singleLine="true" android:imeOptions="actionSearch" /> <ImageView android:id="@+id/imageDelete" android:layout_width="0dp" android:layout_weight=".1" android:layout_height="40dp" android:tint="@color/colorPrimary" android:src="@drawable/ic_close" android:padding="10dp" android:visibility="gone" /> </LinearLayout> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/ll" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="10dp" > <androidx.recyclerview.widget.RecyclerView android:id="@+id/recView" android:layout_width="match_parent" android:layout_height="match_parent" > </androidx.recyclerview.widget.RecyclerView> <ProgressBar android:id="@+id/progBar" android:layout_width="35dp" android:layout_height="35dp" android:layout_gravity="center" /> <LinearLayout android:id="@+id/llNoClient" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical" android:gravity="center" android:visibility="gone" > <ImageView android:layout_width="80dp" android:layout_height="80dp" android:src="@drawable/man" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:textColor="@color/black" android:textSize="18sp" android:text="@string/no_clients_to_display" /> </LinearLayout> </FrameLayout> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
# 现在,在 SQL 和 NoSQL 之间做出选择比以往任何时候都容易 > 原文:<https://itnext.io/choosing-between-sql-and-nosql-is-now-easier-than-ever-9d467628630c?source=collection_archive---------6-----------------------> ## TL;DR:除非 ACID 合规性是一个关键问题(你在金融、电子商务或政府部门),否则选择 NoSQL。 [ACID](https://en.wikipedia.org/wiki/ACID_(computer_science)) (原子性、一致性、隔离性、持久性)旨在即使在出错、断电等情况下也能保证有效性。 **首先**,让我们吞下青蛙。为什么 NoSQL 在酸性方面不如美国? NoSQL 数据库牺牲了 ACID 合规性来换取灵活性和处理速度。您可以为了 ACID 而实现定制工作,但这取决于您自己。 **第二个**,NoSQL 是许多数据库(如键值存储、文档存储和图形)的通用分类。我将主要参考本文中的文档存储,它是最常用的,并且与这个比较相关。 如今,当像 MongoDB 这样的 NoSQL 实现具有 [join 查询](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/)、[random select](https://docs.mongodb.com/manual/reference/operator/aggregation/sample/)、 [transactions](https://docs.mongodb.com/manual/reference/method/Session/) 以及其他不久前还是 SQL 的明显优势的特性时,它会让你质疑使用它的必要性。 NoSQL 还保留了它的优点,如更高的性能、更灵活(无模式)、更容易扩展、更环保(因此更便宜),以及*可能*更简单。 我们的决定应该更令人舒服,有时甚至不需要动脑筋。 ## 一个警告 就像在每一个松散的技术中一样,你必须成为优秀的开发人员,并设计和使用好它,否则它会对你不利。 ## 但是 随着差异变得模糊,虽然性能、灵活性和规模可能不是主要问题,但其他原因可能会打破这种关系。比如说——像 [Node.js 的 Sequelize](http://docs.sequelizejs.com/) 这样优秀的 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) 。 一只小狗: ![](img/dbf1e46a0de72bf918d57a87280cc0a5.png) 查尔斯·德鲁维奥·🇵🇭🇨🇦在 [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) 上拍摄的照片 如果您觉得这篇文章有帮助,请点击👏按钮。欢迎在下面评论或给我发电子邮件到 orenykb@gmail.com。
""" This script provides a diagnostic overview ML model. Diagnostic features consists of : 1. execution time for training 2. provides model prediction 3. Dataset value analysis 4. Environment correctness author: Ondrej Ploteny <ondrej.ploteny@thermofisher.com> Nov 2023 """ import pickle import subprocess import sys import pandas as pd import timeit import os import json import logging logging.basicConfig(stream=sys.stdout, level=logging.INFO) # Load config.json and get environment variables with open('config.json', 'r') as f: config = json.load(f) dataset_csv_path = os.path.join(config['output_folder_path']) test_data_path = os.path.join(config['test_data_path']) prod_deployment_path = os.path.join(config['prod_deployment_path']) def model_predictions(data_to_predict: pd.DataFrame): """ Function to get model predictions read the deployed model and a test dataset, calculate predictions return value should be a list containing all predictions :param data_to_predict: pd.DataFrame :return: """ model_path = os.path.join(prod_deployment_path, 'trainedmodel.pkl') model = pickle.load(open(model_path, 'rb')) predictions = model.predict(data_to_predict) assert len(data_to_predict) == len(predictions) return predictions.tolist() def dataframe_summary(): """ Function to get summary statistics calculate summary statistics here return value should be a list containing all summary statistics :return: """ dataset_path = os.path.join(dataset_csv_path, 'finaldata.csv') data_df = pd.read_csv(dataset_path) data_df = data_df.drop(['exited'], axis=1) data_df = data_df.select_dtypes(include='number') numeric_values = data_df.select_dtypes(include='number') result_dict = numeric_values.agg(['mean', 'median', 'std']) result_list = [ {'column': col, 'mean': result_dict[col][0], 'median': result_dict[col][1], 'std_dev': result_dict[col][2]} for col in result_dict.columns ] return result_list def _measure_subprocess_execution_time(command): """ Measure the execution time of a subprocess. :param command: :return: """ start_time = timeit.default_timer() _ = subprocess.run(command, capture_output=True) duration = timeit.default_timer() - start_time return duration def execution_time(): """ Function to get timings calculate timing of training.py and ingestion.py :return: a list of 2 timing values in seconds """ command_list = [ ['python', 'training.py'], ['python', 'ingestion.py'] ] timing_list = list(map(_measure_subprocess_execution_time, command_list)) return timing_list def missing_data(): """ Calculate percentage of missing values per each column of dataset :return dictionary, keys are column names, values are percentages """ dataset_path = os.path.join(dataset_csv_path, 'finaldata.csv') data = pd.read_csv(dataset_path) missing_percentage = (data.isna().mean() * 100).round(2).to_dict() return missing_percentage def outdated_packages_list(): """ Function to check dependencies :return: list of dictionaries - column name, current version, latest version """ pip_outdated = [sys.executable, '-m', 'pip', 'list', '--outdated', '--format=json'] outdated_packages = subprocess.check_output(pip_outdated).decode('utf-8') return outdated_packages if __name__ == '__main__': logging.info("STEP: diagnostics, begin") test_dataset_path = os.path.join(test_data_path, 'testdata.csv') test_df = pd.read_csv(test_dataset_path) X_df = test_df.drop(['corporation', 'exited'], axis=1) preds = model_predictions(data_to_predict=X_df) logging.info(f"STEP: diagnostics, predictions: {str(preds)}") statistics = dataframe_summary() logging.info(f"STEP: diagnostics, dataframe statistics: {str(statistics)}") t = execution_time() logging.info(f"STEP: diagnostics, execution time: {str(t)}") missing = missing_data() logging.info(f"STEP: diagnostics, missing percentage: {str(missing)}") outdated_list = outdated_packages_list() logging.info(f"STEP: diagnostics, outdated packages: {str(outdated_list)}") logging.info("STEP: diagnostics, done")
@extends('layouts.admin.admin') @section('title') Admin - Dashboard @endsection @section('header') <div class="flex justify-between items-center"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> Welcome {{ $user }} </h2> <a href="{{ route('post.create') }}" class=" text-lg text-blue-600 leading-tight cursor-pointer hover:text-blue-800">Create New Post</a> </div> @endsection @section('main') <div class="py-8"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="relative overflow-x-auto"> <table class="p-4 md:p-0 w-full text-sm text-left text-gray-500 dark:text-gray-400"> <thead class=" text-xs text-gray-700 uppercase bg-gray-50 text-center "> <tr> <th scope="col" class="px-1 py-2 md:px-6 md:py-4">No.</th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4">Title</th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4 hidden md:table-cell"> Category</th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4">Author</th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4 hidden md:table-cell"> Image </th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4 hidden md:table-cell"> Time </th> <th scope="col" class="px-1 py-2 md:px-6 md:py-4">Action</th> </tr> </thead> <tbody> <tbody> @foreach ($posts as $post) <tr class="text-center bg-white border-b text-gray-900 cursor-pointer"> <th scope="row" class="px-6 py-4 "> {{ $loop->iteration }} </th> <td class="text-xs md:text-base px-2 py-2 md:px-6 md:py-4"> {{Str::limit($post->title, 46) }} </td> <td class="px-2 py-2 md:px-6 md:py-4 hidden md:table-cell"> {{ $post->category->title }} </td> <td class="px-2 py-2 md:px-6 md:py-4"> {{ $post->post_author->username }} </td> <td class="px-2 py-2 md:px-6 md:py-4 hidden md:table-cell"> <img src="{{ asset('/storage/posts/' . $post->image) }}" alt="{{Str::limit($post->title, 10) }}" width="75px"> </td> <td class="px-2 py-2 md:px-6 md:py-4 hidden md:table-cell"> {{ $post->created_at->diffForHumans() }} </td> <td class="text-center px-2 py-2 md:px-6 md:py-4 flex flex-col gap-y-2 xl:flex-row xl:gap-x-2 xl:gap-y-0 "> <a href="{{ route('post.edit', $post->slug) }}" class="bg-yellow-400 py-2 px-4 md:py-3 md:px-6 rounded-lg hover:font-semibold">Edit</a> <a href="{{ route('post.show', $post->slug) }}" class="bg-blue-400 py-2 px-4 md:py-3 md:px-6 rounded-lg hover:font-semibold">Detail</a> <form onsubmit="return confirm('Are you sure delete this post ?');" action="{{ route('post.destroy', $post) }}" method="POST"> @csrf @method('DELETE') <button type="submit" class="bg-red-500 w-full py-2 px-4 md:py-3 md:px-6 rounded-lg hover:font-semibold">Delete</button> </form> </td> </tr> @endforeach </tbody> </tbody> </table> </div> </div> </div> </div> @endsection
import { Avatar, Space, Typography } from 'antd'; import React, { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { Link } from 'react-router-dom'; import orderApi from '../../../../../api/orderApi'; import ManageOrderTable from '../../../components/ManageOrderTable'; const { Text } = Typography; function ManageRentedOrderUserPage(props) { const userId = useSelector((state) => state.users.id); const [page, setPage] = useState(1); const [rentedOrder, setRentedOrder] = useState([]); useEffect(() => { if (!userId) return; const getMyOrderByStatus = async () => { const response = await orderApi.getMyOrder({ userId: userId, statusName: 'RENTED', page: page, }); setRentedOrder((prev) => [...prev, ...response]); }; getMyOrderByStatus(); }, [userId, page]); const handlePageChange = () => { setPage(page + 1); }; const buttonGroup = () => { return <div></div>; }; const userTitleTable = (order) => { return ( <Link to={`/profile/${order.orderItems[0]?.Product.User.firebaseId}`}> <Space size={20}> <Avatar src={order.orderItems[0]?.Product.User.photoURL} /> <Text strong>{order.orderItems[0]?.Product.User.username}</Text> </Space> </Link> ); }; return ( <> <ManageOrderTable dataSource={rentedOrder} buttonGroup={buttonGroup} handlePageChange={handlePageChange} userTitleTable={userTitleTable} tag='RENTED' tagColor='orange' /> </> ); } export default ManageRentedOrderUserPage;
<?php namespace App\Services; use App\Enums\TypeEnums; use App\Models\Incoming; use App\Models\Item; use App\Models\Plate; use Barryvdh\DomPDF\Facade\Pdf; use Illuminate\Support\Facades\DB; class IncomingService { public $incoming; public $plates; public function __construct(Incoming $incoming) { $this->incoming = $incoming; $this->plates = Plate::where('incoming_id', $incoming->id) ->OrderBy('origin', 'desc') ->OrderBy('delivery_zip', 'asc') ->OrderBy('customer_key', 'asc') ->OrderBy('reference', 'asc') ->get(); } public function makeLabelKbc() { $plates = $this->plates; $pdf = Pdf::loadView('pdf/labelKbc', compact('plates'))->setpaper( 'a4', 'landscape', ); return $pdf->download('lable.pdf'); } public function makeLabelBelfius() { $plates = $this->plates; $customer = $this->incoming->customer; $pdf = Pdf::loadView('pdf/labelBelfius', compact('plates', 'customer'))->setPaper( 'a4', 'landscape', ); return $pdf->download('label.pdf'); } public function makeBpostFile(bool $needFirstLine = true) { if ($needFirstLine) { $content[] = [ 'ProductId', 'Name', 'Contact Name', 'Contact Phone', 'Street', 'Street Number', 'Box Number', 'Postal Code', 'City', 'Country', 'Sender Name', 'Sender Contact Name', 'Sender Street', 'Sender Street Number', 'Sender Box Number', 'Sender Postal Code', 'Sender City', 'Weight', 'Customer Reference', 'Cost Center', 'Free Message', 'COD Amount', 'COD Account', 'Signature', 'Insurance', 'Automatic Second Presentation', 'Before 11am', 'Info Reminder', 'Info Reminder Language', 'Info Reminter Type', 'Info Reminder Contact Data', 'Info Next Day', 'Info Next Day language', 'Info Next Day Type', 'Info Next day Contact Data', 'Info Distributed', 'Info Distributed Language', 'Info Distributed Type', 'Info Distributed Contact Data', 'bic cod', ]; } else { $content = []; } if (count($this->incoming->customer->labels) > 0) { foreach ($this->incoming->customer->labels as $label) { $content[] = [ 'TXP24H', $label->delivery_contact, '', '', $label->delivery_street, $label->delivery_number, $label->delivery_box, $label->delivery_zip, $label->delivery_city, 'BE', 'OTM-Shop', '', 'Potaardestraat', '42', '', '1082', 'Brussel', '', '', '999786', '', '', '', 'N', 'N', 'N', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ]; } } if ($this->incoming->customer->is_delivery_grouped) { $quantity_max_grouped = env('OTM_PRODUCTIONS_QUANTITY_MAX_BOX'); $groupes = DB::table('plates') ->select('customer_key') ->groupBy('customer_key') ->where('incoming_id', $this->incoming->id) ->whereNotNull('customer_key') ->OrderBy('origin', 'desc') ->OrderBy('delivery_zip', 'asc') ->OrderBy('customer_key', 'asc') ->OrderBy('reference', 'asc') ->get(); foreach ($groupes as $group) { $plates = Plate::where('incoming_id', $this->incoming->id) ->where('customer_key', $group->customer_key) ->count(); $lines = (int) ($plates / $quantity_max_grouped); if ($lines === 0) { $lines = 1; } $location = Plate::where('incoming_id', $this->incoming->id) ->where('customer_key', $group->customer_key) ->first(); for ($i = 1; $i <= $lines; $i++) { if ($location->datas) { $cod = null; if (isset($location->datas['price'])) { $cod = $location->datas['price']; } $content[] = [ 'TXP24H', $location->datas['destination_name'], '', '', $location->datas['destination_street'], $location->datas['destination_house_number'], $location->datas['destination_bus'], $location->datas['destination_postal_code'], $location->datas['destination_city'], 'BE', 'OTM-Shop', '', 'Potaardestraat', '42', '', '1082', 'Brussel', '', '', '999786', '', $cod, (int) $cod > 0 ? 'BE29096898971264' : '', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', '', '', '', '', '', '', '', '', '', '', '', '', '', (int) $cod > 0 ? 'GKCCBEBB' : '', ]; $i++; } } } $plates = Plate::where('incoming_id', $this->incoming->id) ->OrderBy('origin', 'desc') ->OrderBy('delivery_zip', 'asc') ->OrderBy('customer_key', 'asc') ->OrderBy('reference', 'asc') ->whereNull('customer_key') ->get(); $i = 1; foreach ($plates as $plate) { if ($plate->datas) { $message = $i.'*** / '.$plate->reference; $otherItems = Plate::where('reference', $plate->reference) ->whereNotIn( 'type', array_column(TypeEnums::cases(), 'name'), ) ->get(); if ($otherItems) { foreach ($otherItems as $otherItem) { $item = Item::where( 'reference_customer', $plate->datas['plate_type'], )->first(); if ($item) { $message .= ' / 1 '.strtoupper($item->reference_otm); } } } $cod = null; if (isset($plate->datas['price'])) { $cod = $plate->datas['price']; } $content[] = [ 'TXP24H', $plate->datas['destination_name'], '', '', $plate->datas['destination_street'], $plate->datas['destination_house_number'], $plate->datas['destination_bus'], $plate->datas['destination_postal_code'], $plate->datas['destination_city'], 'BE', 'OTM-Shop', '', 'Potaardestraat', '42', '', '1082', 'Brussel', '', '', '999786', $message, $cod, (int) $cod > 0 ? 'BE29096898971264' : '', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', '', '', '', '', '', '', '', '', '', '', '', '', '', (int) $cod > 0 ? 'GKCCBEBB' : '', ]; $i++; } } } else { $plates = Plate::where('incoming_id', $this->incoming->id) ->OrderBy('origin', 'desc') ->OrderBy('delivery_zip', 'asc') ->OrderBy('customer_key', 'asc') ->OrderBy('reference', 'asc') ->get(); $i = 1; foreach ($plates as $plate) { if ($plate->datas) { $message = $i.'*** / '.$plate->reference; $otherItems = Plate::where('reference', $plate->reference) ->whereNotIn( 'type', array_column(TypeEnums::cases(), 'name'), ) ->get(); if ($otherItems) { foreach ($otherItems as $otherItem) { $item = Item::where( 'reference_customer', $plate->datas['plate_type'], )->first(); if ($item) { $message .= ' / 1 '.strtoupper($item->reference_otm); } } } $cod = null; if (isset($plate->datas['price'])) { $cod = $plate->datas['price']; } $content[] = [ 'TXP24H', $plate->datas['destination_name'], '', '', $plate->datas['destination_street'], $plate->datas['destination_house_number'], $plate->datas['destination_bus'], $plate->datas['destination_postal_code'], $plate->datas['destination_city'], 'BE', 'OTM-Shop', '', 'Potaardestraat', '42', '', '1082', 'Brussel', '', '', '999786', $message, $cod, (int) $cod > 0 ? 'BE29096898971264' : '', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', (int) $cod > 0 ? '' : 'N', '', '', '', '', '', '', '', '', '', '', '', '', '', (int) $cod > 0 ? 'GKCCBEBB' : '', ]; $i++; } } } return $this->array2csv($content); } public function array2csv( $data, $delimiter = ',', $enclosure = '"', $escape_char = '\\', ) { $f = fopen('php://memory', 'r+'); foreach ($data as $item) { fputcsv($f, $item, $delimiter, $enclosure, $escape_char); } rewind($f); return stream_get_contents($f); } }
# Type Casting Converter o tipo de dado valor em outro tipo. Converter uma variável do tipo double para uma variável do tipo int. Observe o exemplo abaixo: **Código:**` ``` public class Typecasting { public static void main(String[] args) { double nota = 9.6; System.out.println("tipo double: " + nota); System.out.println("tipo int: " + (int) nota); } } ``` **Saída de execução:** ![](images/typecasting-output.png) # Upcasting Quando realizamos um typecasting à instância de uma subclasse, convertendo a instância para o tipo de sua superclasse. Observe o exemplo abaixo: **Código:** ``` class Veiculo { public void freiar() { System.out.println("Acionando recursos de atrito"); } } class Carro extends Veiculo{ public void freiar() { System.out.println("Pisando no freio do carro"); } public void diminuirVelocidade(){ System.out.println("Retirando o pe do acelerador"); } } public class Upcasting { public static void main(String[] args) { //Upcasting implicito: Veiculo hb20 = new Carro(); //Mesmo que Veiculo hb20 = (Veiculo) new Carro(); } } ``` No exemplo acima, mesmo Carro() possuindo o método diminuirVelocidade(), o método não poderá ser chamado pela instância, uma vez que o upcasting ocorreu e que o tipo de variável da instância hb20 foi convertida do tipo Carro para o tipo Veiculo. Além de detalhes como tamanho de ocupação do valor de uma variável na memória, um tipo de variável também é responsável por definir as operações específicas associadas a uma instância, tendo em vista que cada classe tem seu conjunto de métodos conhecidos e implementados. Sendo asism, depois do upcasting, hb20 agora é do tipo Veiculo e a classe Veiculo() não tem nenhum método diminuirVelocidade() implementado. Log, o método não poderá ser chamado pelo objeto hb20, mesmo ele sendo uma instância de Carro(). Se a classe Veiculo() tivesse um método com a mesma assinatura, então, quando o método fosse chamado pela instancia cuja variavel é do tipo Veiculo mas o valor é um objeto da classe Carro(), ocorreria um override, e a implementação do método diminuirVelocidade() presente na classe Carro() iria sobrescrever a implementação na classe Veiculo(). Mas como Veiculo não possui esse método, e o typecasting ocorreu para a variável, mesmo que ela tenha como valor um objeto da classe Carro() que possui o método, o método não pode ser invocado, tendo em vista que a variável é do tipo Veiculo, ou seja, a classe Veiculo(), desconhece esse método. # Downcasting Quando realizamos um typecasting à instância de uma superclasse, convertendo a instância para o tipo de sua subclasse. Seguindo a mesma lógica explicada no tópico de upcasting, temos que caso um objeto de uma subclasse seja instânciado e atribuido a uma variável com o tipo de sua superclasse, e essa superclasse não possua a assinatura de algum método da subclasse, esse método não poderá ser utilizado pelo objeto instanciado. Sendo assim, o uso do downcasting poderá ser uma solução útil. Observe o exemplo abaixo: **Código:** ``` class Veiculo { String chassi; public void freiar() { System.out.println("Acionando recursos de atrito"); } } class Carro extends Veiculo{ public void acelerar() { System.out.println("Pisando no acelerador"); } } public class Downcasting { public static void main(String[] args) { Veiculo celta = new Carro(); celta.chassi = "123"; //Downcasting para utilizar o método acelerar() Carro hb20 = (Carro) celta; hb20.acelerar(); System.out.println("\nchassi hb20: " + hb20.chassi + "\n"); //No downcasting a nova variável possui um tipo diferente, porém faz referência ao mesmo objeto celta.chassi = "321"; System.out.println("\nchassi hb20: " + hb20.chassi + "\n"); System.out.println("celta == hb20 --> " + celta.equals(hb20)); } } ``` **Saída de execução:** ![](images/downcasting-output.png) Observe que a criação da nova instância "hb20" utilizando o downcasting na instância "celta" possibilitou o uso da função acelerar implementado na classe Carro(). Outra observação relevante, é que o downcasting possibilitou que a nova variável (hb20), de tipo Carro e não Veiculo, fizesse referência ao mesmo objeto (instanciado pela classe Veiculo()), o que dependendo do contexto e necessidade do programador, pode ser um recurso extremamente útil. Isso significa que o desenvolvedor poderá empregar comportamentos específicos de uma determinada classe ao objeto de outra classe que não reconheça esse método sem precisar criar novas instâncias, tornando o processo mais simples e econômico para a memória.
#include <algorithm> #include <cassert> #include <chrono> #include <filesystem> #include <fstream> #include <iostream> #include <map> #include <span> #include <string> #include <vector> std::pair<bool, bool> DupCount(std::string_view line) { std::map<char, int> counter; std::for_each(line.begin(), line.end(), [&](char c) { counter[c]++; }); bool has_two = false; bool has_three = false; for (const auto& [_, count] : counter) { if (count == 2) { has_two = true; } if (count == 3) { has_three = true; } } return std::make_pair(has_two, has_three); } std::string FindDiffByOne(std::span<const std::string> inputs) { for (int i = 0; i < inputs.size(); ++i) { for (int j = i + 1; j < inputs.size(); ++j) { assert(inputs[i].size() == inputs[j].size()); int diff = 0; int diff_index = -1; for (int s = 0; s < inputs[i].size(); ++s) { if (inputs[i][s] != inputs[j][s]) { diff_index = s; ++diff; } if (diff >= 2) { break; } } if (diff == 1) { std::cout << inputs[i] << " && " << inputs[j] << std::endl; return inputs[i].substr(0, diff_index) + inputs[i].substr(diff_index + 1); } } } return ""; } // Program entry point. // Reads infile and parses the text. int main() { std::vector<std::string> input; while (true) { std::string line; std::cin >> line; if (line.empty()) { break; } input.push_back(line); } int twos = 0; int threes = 0; for (std::string_view line : input) { std::pair<bool, bool> res = DupCount(line); if (res.first) { ++twos; } if (res.second) { ++threes; } } std::cout << twos * threes << std::endl; std::cout << FindDiffByOne(input) << std::endl; return 0; }
# 프리온보딩 2주차 과제 ## 🌐 배포 주소 ### https://my-pre-onboard-12th-2-8.vercel.app/ ## ⚙ 로컬 실행 방법 1. 프로젝트 내려받기 `git clone https://github.com/jypman/my-pre-onboard-12th-2.git ./` 2. 패키지 설치: `npm install` 3. 애플리케이션 실행: `npm start` 4. 테스트 코드 실행 `npm test` ## 🙋‍about me | 박진영 | |------------------------------------------------------------------------------------------------| | <img src="https://avatars.githubusercontent.com/u/69949824?v=4.png" width="300" height="300"/> | | [닉네임 : jypman](https://github.com/jypman)| ## 💻 과제 요구사항 https://lean-mahogany-686.notion.site/Week-2-a28eb717312a434498ea431d2ff8fc17 ## 📁 프로젝트 디렉토리 구조 ``` 📂src ├── App.tsx ├── 📂api │   ├── config.ts (api의 base url, end point 관리) │   ├── http.ts (axios instance, 요청 에러 핸들링 관리) │   └── issues.ts (github issue 관련 리소스 요청 로직 관리) ├── 📂components (공용 UI 컴포넌트 관리) │   ├── Ads.tsx │   ├── Header.tsx │   ├── Loading.tsx │   ├── MarkDown.tsx │   └── PageLayoyt.tsx ├── 📂hooks │   └── useInfinityScroll.tsx ├── index.css ├── index.tsx ├── logo.svg ├── 📂pages (각 페이지를 렌더링하는 컴포넌트 관리) │   ├── DetailIssue.tsx (이슈 상세정보 페이지) │   ├── Home.tsx (홈 페이지) │   ├── 📂Issues (이슈 목록 페이지) │   │   ├── IssueItem.tsx │   │   ├── IssueItemWrapper.tsx │   │   └── Issues.tsx │   ├── NotFound.tsx (404 페이지) │   └── Routes.tsx (페이지 라우팅 관리) ├── 📂providers (서버 상태값과 업데이트 함수를 react context api를 통해 제공하는 파일 관리) │   ├── DetailIssueProvider.tsx │   └── IssueListProvider.tsx ├── react-app-env.d.ts ├── 📂reducers (서버 상태값 업데이트 액션의 타입과 그에 따른 업데이트 로직을 관리) │   ├── detailIssueReducer.ts │   └── issueListReducer.ts ├── reportWebVitals.ts ├── setupTests.ts ├── 📂tests │   ├── DetailIssue.test.tsx │   └── Issues.test.tsx └── utils.ts ``` ## 😁이 부분에 대해 고민해봤어요! - **서버 요청 공통로직 개선** - <span style="color:green;font-weight:bold">why?</span> - 매 서버 요청 로직마다 base url, authorization header를 주입해줘야 하는 리소스 발생 - 추후 서버 요청 로직이 수정될 경우 해당 함수를 탐색하여 일일이 수정해야 하는 리소스 발생 - <span style="color:green;font-weight:bold">how?</span> - axios instance 생성 - axios로 서버 요청 시 공통으로 적용되는 로직을 instance에 추가 - 매 요청마다 해당 공통로직이 적용되어 유지보수 용이 ([해당 파일로 이동](./src/api/http.ts)) - **무한 스크롤 구현** - <span style="color:green;font-weight:bold">how?</span> - javascript browser api 중 intersection observer로 구현 - 해당 구현 기능은 추후 다른 페이지에서도 사용 가능함으로 커스텀 훅으로 분리하여 재사용성 고려 - <span style="color:green;font-weight:bold">why?</span> - scroll 이벤트를 통해 스크롤이 특정 페이지 하단에 도달할 경우 api를 호출하는 방법도 가능 - 하지만 스크롤 이벤트로 구현할 경우 리플로우에 의해 좋지 않은 렌더링 성능 이슈가 있다는 것을 구글링을 통해 발견 - intersection observer의 경우 관찰 대상이 되는 요소가 뷰포트에 교차되었을 때 특정 로직이 실행되어 브라우저의 퍼포먼스 측면에서 이점 ([참고 사이트](https://tech.kakaoenterprise.com/149)) - **view(JSX)와 로직 관심사 분리** - <span style="color:green;font-weight:bold">why?</span> - 하나의 모듈을 수정하는 목적을 하나로 제한하기 위함 - 모듈 수정 시 수정 목적을 파악하기 용이 - 이를 통해 유지보수 용이 - <span style="color:green;font-weight:bold">how?</span> - view는 Issues.tsx, DetailIssue.tsx에서 관리 - 상태값과 상태값 업데이트 함수는 context api를 사용한 Providers 디렉토리의 ***Provider.tsx에서 제공 - ***Provider.tsx의 자식 컴포넌트에 위치한 컴포넌트는 <br/> ***Provider.tsx에서 제공하는 커스텀훅을 import하여 상태값과 함수 사용가능 - 만약 ***Provider.tsx의 자식이 아닌 컴포넌트가 ***Provider.tsx의 커스텀 훅을 사용할 경우 <br/>"<span style="color:red;font-weight:bold">[커스텀훅명] should be used within [provider명]</span>"<br/> 에러를 던져 실수를 방지하여 개발자 경험 개선 ([해당 디렉토리로 이동](./src/providers/)) - 서버 상태값 업데이트 액션의 타입과 그에 따른 업데이트 상세 로직은 리듀서에서 관리 ([해당 디렉토리로 이동](./src/reducers/)) - **이슈 상세정보 페이지 내 마크다운 렌더링** - <span style="color:green;font-weight:bold">how?</span> - react-markdown 라이브러리 사용 - 마크다운 문법을 포함한 string을 라이브러리에서 제공하는 컴포넌트의 props로 받아 마크다운 문법을 해석하여 간편하게 렌더링해주는 라이브러리 - <span style="color:green;font-weight:bold">why?</span> - 서버에서 이슈 관련 콘텐츠를 마크다운 문법을 포함한 스트링 값으로 응답 - 해당 응답 값을 효과적으로 렌더링하고자 해당 라이브러리 선택 - **컴포넌트 스타일링** - <span style="color:green;font-weight:bold">how?</span> - styled-components 라이브러리 사용 - <span style="color:green;font-weight:bold">why?</span> - 컴포넌트 개발할 때마다 css파일을 따로 생성하지 않아도 되는 이점 - css className 네이밍 중복 이슈 방지 - props에 따라 스타일을 유연하게 변경할 수 있는 이점 - css-in-js를 지원하는 라이브러리 중에서 해당 라이브러리가 다운로드 수도 높고 상대적으로 오래 유지보수 되어 안정감이 있다고 생각하여 styled-components 채택 - **테스트코드 추가** - <span style="color:green;font-weight:bold">why?</span> - 구현한 기능이 의도된대로 동작하는지 빠른 피드백이 가능 - 해당 기능 정상작동의 확신 갖기 위함 - <span style="color:green;font-weight:bold">how?</span> - jest 및 React Testing Library로 진행 - 필수 구현 사항을 중점적으로 테스트 케이스 추가 ## 🛠사용한 라이브러리 <div> 영역|목록| :--------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:| **Frontend** | <img src="https://img.shields.io/badge/react-61DAFB?style=for-the-badge&logo=react&logoColor=black"> <img alt="Static Badge" src="https://img.shields.io/badge/Axios-%235A29E4?style=for-the-badge&logo=axios&logoColor=white"> <img alt="Static Badge" src="https://img.shields.io/badge/react%20markdown-%23000000?style=for-the-badge&logo=markdown&logoColor=white"> <img alt="Static Badge" src="https://img.shields.io/badge/Jest-%23C21325?style=for-the-badge&logo=Jest&logoColor=white"> <img alt="Static Badge" src="https://img.shields.io/badge/Testing%20Library-%23E33332?style=for-the-badge&logo=Testing%20Library&logoColor=white"> <img src="https://img.shields.io/badge/styledcomponents-DB7093.svg?&style=for-the-badge&logo=styledcomponents&logoColor=white"> <img src="https://img.shields.io/badge/React Router-CA4245.svg?&style=for-the-badge&logo=reactrouter&logoColor=white"> </div>
package com.thinkdevs.noteapp.database; import java.util.List; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; @Dao public interface NoteDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertNote(NoteEntity noteEntity); @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(List<NoteEntity> noteEntity); @Delete void deleteNotes(NoteEntity noteEntity); //retrieve single node @Query("SELECT * FROM notes WHERE id=:id") NoteEntity getNotesById(int id); @Query("SELECT * FROM notes ORDER BY date DESC") LiveData<List<NoteEntity>> getAll(); @Query("DELETE FROM notes") int deleteAll(); @Query("SELECT COUNT(*) FROM notes") int getCount(); }
<template> <div aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <button aria-label="Previous" class="page-link" @click="handlePrevPage"> <span aria-hidden="true">&laquo;</span> </button> </li> <li class="page-item" :key="idx" v-for="(n, idx) in pages"> <button :class="['page-link', { 'active': currentPage === n }]" @click="handlePageClick(n)"> {{ n }} </button> </li> <li class="page-item"> <button aria-label="Next" class="page-link" @click="handleNextPage"> <span aria-hidden="true">&raquo;</span> </button> </li> </ul> </div> </template> <script> export default { data() { return { currentPage: 1, }; }, emits: ["onClick"], methods: { handlePageClick(page) { this.currentPage = page; this.$emit("onClick", page); }, handleNextPage() { if (this.currentPage < this.pages) { this.handlePageClick(this.currentPage + 1); } }, handlePrevPage() { if (this.currentPage > 1) { this.handlePageClick(this.currentPage - 1); } }, }, props: ["pages", "page"], } </script> <style scoped> .page-link { color: var(--color-primary); } .page-link.active { background-color: var(--color-primary); color: white; } </style>
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Illuminate\Queue\SerializesModels; class JobAppliedForUser extends Mailable { use Queueable, SerializesModels; public $jobItem; public $user; /** * Create a new message instance. */ public function __construct($jobItem, $user) { $this->jobItem = $jobItem; $this->user = $user; } /** * Get the message envelope. */ public function envelope(): Envelope { return new Envelope( subject: 'You have successfully applied for '.$this->jobItem->title, ); } /** * Get the message content definition. */ public function content(): Content { return new Content( view: 'emails.job-applied-for-user', ); } /** * Get the attachments for the message. * * @return array<int, \Illuminate\Mail\Mailables\Attachment> */ public function attachments(): array { return []; } }
import React, { useState } from "react"; import "./CounterApp.css"; // Import your CSS file for styling function CounterApp() { const [count, setCount] = useState(0); const handlePlus = () => { setCount(count + 1); }; const handleMinus = () => { setCount(count - 1); }; const handleReset = () => { setCount(0); }; return ( <div className="App"> <div className="counter-box"> <p className="counter">Count: {count}</p> <div className="buttons"> <button className="button" onClick={handleMinus}> - </button> <button className="button" onClick={handleReset}> RESET </button> <button className="button" onClick={handlePlus}> + </button> </div> </div> </div> ); } export default CounterApp;
# Robot Framework Page Object Model Demo ## Robot Framework Introduction [Robot Framework](http://robotframework.org) is a generic open source automation framework for acceptance testing, acceptance test driven development (ATDD), and robotic process automation (RPA). It has simple plain text syntax and it can be extended easily with libraries implemented using Python or Java. Robot Framework is operating system and application independent. The core framework is implemented using [Python](http://python.org), supports both Python 2 and Python 3, and runs also on [Jython](http://jython.org) (JVM), [IronPython](http://ironpython.net) (.NET) and [PyPy](http://pypy.org). The framework has a rich ecosystem around it consisting of various generic libraries and tools that are developed as separate projects. For more information about Robot Framework and the ecosystem, see http://robotframework.org. [GitHub](https://github.com/robotframework/robotframework) [PyPI](https://pypi.python.org/pypi/robotframework) [Maven central](http://search.maven.org/#search%7Cga%7C1%7Ca%3Arobotframework) ## Installation 1. Download and Install [Python](https://www.python.org/downloads/ "Python"). 2. Check Python installation `python3 -V` 3. Install [pip](https://pip.pypa.io/ "pip"). `pip3 -V` 4. Download and install Intellij [Intellij](https://www.jetbrains.com/pycharm/download/). 5. Install Plugin [Hyper Robot Code Support](https://plugins.jetbrains.com/plugin/16382-hyper-robotframework-support) extension from Intellij's Marketplace 6. Install Robot Framework. `pip3 install robotframework` 7. Install Selenium Library. `pip3 install robotframework-seleniumlibrary` 8. Install Browser Drivers `pip3 install webdrivermanager` ## Example Here, I have developed sample test cases for a sample web site [Demoblaze](https://demoblaze.com/). This project is developed to demonstrate Web UI automation using Robot Framework and Selenium Library. Here, there are 3 variables `${SMALL_RETRY_COUNT}`, `${MEDIUM_RETRY_COUNT}` and `${LARGE_RETRY_COUNT}` for retrying the keywords when they are failing. Each variable has assigned with the number of retries. Automation engineers are advised to use `${SMALL_RETRY_COUNT}` as the default number of retries for the keywords. If there are big delays in some scenarios, you can use other variables `${MEDIUM_RETRY_COUNT}` and `${LARGE_RETRY_COUNT}`. You can find the examples for this in `object-repository/page-objects` directory. Test cases are in `test-cases` directory and covers login functionality. ## File organization ``` |- ui-automation/ // Home folder for robot selenium UI automation project |- configs/ApplicationVariables.robot // Application common variables file |- configs/BrowserDetails.robot // Test execution browser configurations |- configs/EnvDetails.robot // Test execution environment configurations |- configs/SeleniumConfigs.robot // Selenium configurations |- object-repository/locators/*.robot // UI locators of the application |- object-repository/page-objects/CommonPo.robot // Common keywords for the application |- object-repository/page-objects/*.robot // Page object keywords of the application |- test-cases/..../*.robot // Test cases of the application |- results // Test results will be saving here |- .gitignore // Excluded the unnecessary files in the repo |- README.md // This file ``` ## Usage Starting from Robot Framework 3.0, tests are executed from the command line using the ``robot`` script or by executing the ``robot`` module directly like ``python -m robot`` or ``jython -m robot``. The basic usage is giving a path to a test (or task) file or directory as an argument with possible command line options before the path python3 -m robot -v ENV:DEMO -i Smoke -d path/to/results path/to/tests/ python3 -m robot -v ENV:DEMO -i Smoke -d ui-automation/results ui-automation/test-cases/LoginTest.robot "***-v***" refers to the variables. To replace a declared value within the code, you can specify a variable name and value. "***-i***" refers to the tags. To run only a selected group of tests, you may specify a tag name. "***-d***" refers to the test results. The location to save the test results can be specified here. Additionally, there is ``rebot`` tool for combining results and otherwise post-processing outputs rebot --name Example output1.xml output2.xml Run ``robot --help`` and ``rebot --help`` for more information about the command line usage. For a complete reference manual see [Robot Framework User Guide](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html "Robot Framework User Guide").
package types import ( "encoding/json" "fmt" "time" cmn "my-tendermint/tendermint/libs/common" "my-tendermint/tendermint/types" ) //----------------------------------------------------------------------------- // RoundStepType enum type // RoundStepType enumerates the state of the consensus state machine type RoundStepType uint8 // These must be numeric, ordered. // RoundStepType /** 共识的步骤类型 【H,R】 H 为 block height; R 为 Round TODO 注意: 在Tendermint算法中,如果遇到对同一特定区块的同意及否决信息同时超过2/3的情况, 需要启用【外部的维护机制】去核查是否存在超过1/3的验证节点伪造签名或者投出双重选票 */ const ( /** TODO 新的高度阶段 【H+1】 步骤: 将于提交信息转移至 【最近】(last) 的提交信息, 并增加block height。 结果: 等待一定超时时间,让落后的节点 提交区块, 然后进入 (下一个)【提议阶段】【H+1,0】 */ // 处于等到CommitTime + timeoutCommit 的阶段 RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit /** TODO 新一轮的开始阶段 【R+1】 */ // 设置新轮并转到RoundStepPropose RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose /** TODO ############################### TODO 提议阶段 【H,R】 步骤: 指定提议者提议一个块 结果: 1、进入与投票阶段 a、计数器1超时 b、如果共识节点收到提议且达到POLC 阶段所需的预投票 2、普通退出情况 TODO ------------------------------- */ /** 发起提案,并广播提案 */ RoundStepPropose = RoundStepType(0x03) // Did propose, gossip proposal /** TODO ############################### TODO 预投票阶段 【H,R】 步骤: 每个验证人都要广播自己的预选投票。 若在提议阶段提议的block是有效的, 那么该验证节点统一该区块。 如果block无效或者验证人在超时时间内未及时收到提议, 则透出 <nil> 表示否决。 结果: 1、进入与预提交阶段 a、收到超过 2/3 的(任意)预投票,但后来计数器2超时。 b、对特定的块 同意/否决的预投票,超过 2/3 2、普通退出情况 TODO ------------------------------- */ /** 发起 prevote,并广播 prevote */ RoundStepPrevote = RoundStepType(0x04) // Did prevote, gossip prevotes /** 等待接收 x > 2/3 的 prevote (一个等待超时阶段) */ RoundStepPrevoteWait = RoundStepType(0x05) // Did receive any +2/3 prevotes, start timeout /** TODO ############################### TODO 预提交阶段 【H,R】 步骤: 每个验证人都要广播自己的预提交 投票。 如果验证人在【H,R】的POLC 回合同意该 block, 那么该验证人将广播 (表示同意该区块的)预提交信息。 否则,如果该验证人 否决 或者 为见证 POLC 回合, 则将广播包含 <nil> 的预提交信息。 结果: 1、进入与 提议阶段 【H,R+1】阶段 a、收到超过 2/3 的(任意)预 提交,但后来计数器3超时。 b、对特定的块 <nil>的预提交,超过 2/3 2、普通退出情况 TODO ------------------------------- */ /** 发起 precommit,并广播 precommit */ RoundStepPrecommit = RoundStepType(0x06) // Did precommit, gossip precommits /** 等待接收 x > 2/3 的 precommit (一个等待超时阶段) */ RoundStepPrecommitWait = RoundStepType(0x07) // Did receive any +2/3 precommits, start timeout /** TODO ############################### TODO 提交阶段 (最终提交阶段) 【H】 步骤: 设置提交时间为当前时间。 结果: 一旦区块被接收,则进入新的高度阶段 【H+1】 TODO ------------------------------- /** 最终的 commit 阶段 */ RoundStepCommit = RoundStepType(0x08) // Entered commit state machine // NOTE: RoundStepNewHeight acts as RoundStepCommitWait. // NOTE: Update IsValid method if you change this! ) // IsValid returns true if the step is valid, false if unknown/undefined. func (rs RoundStepType) IsValid() bool { return uint8(rs) >= 0x01 && uint8(rs) <= 0x08 } // String returns a string func (rs RoundStepType) String() string { switch rs { case RoundStepNewHeight: return "RoundStepNewHeight" case RoundStepNewRound: return "RoundStepNewRound" case RoundStepPropose: return "RoundStepPropose" case RoundStepPrevote: return "RoundStepPrevote" case RoundStepPrevoteWait: return "RoundStepPrevoteWait" case RoundStepPrecommit: return "RoundStepPrecommit" case RoundStepPrecommitWait: return "RoundStepPrecommitWait" case RoundStepCommit: return "RoundStepCommit" default: return "RoundStepUnknown" // Cannot panic. } } //----------------------------------------------------------------------------- // RoundState defines the internal consensus state. // NOTE: Not thread safe. Should only be manipulated by functions downstream // of the cs.receiveRoutine /** TODO 重要 [轮次state] RoundState定义了内部共识状态。 注意:不是线程安全的。 只应由下游功能操纵 cs.receiveRoutine */ type RoundState struct { // 需要打包的最新块高 Height int64 `json:"height"` // Height we are working on // 共识的轮次 Round int `json:"round"` // 现在处于共识的 第几步 (发起提议? prevote? precommit? commit?) Step RoundStepType `json:"step"` // 共识开始时间? StartTime time.Time `json:"start_time"` // 找到+2/3预先提交Block for Block的主观时间 // 真正 commit的时间 CommitTime time.Time `json:"commit_time"` // Subjective time when +2/3 precommits for Block at Round were found // 当前共识时的 验证人集合 Validators *types.ValidatorSet `json:"validators"` // 当前共识的 提案信息 Proposal *types.Proposal `json:"proposal"` // 被提案的 block ProposalBlock *types.Block `json:"proposal_block"` // TODO 暂时不知道干嘛的 ProposalBlockParts *types.PartSet `json:"proposal_block_parts"` // 锁定的轮次 LockedRound int `json:"locked_round"` // 锁定的 block (是不是上一个块啊) LockedBlock *types.Block `json:"locked_block"` // 不知道干嘛的 LockedBlockParts *types.PartSet `json:"locked_block_parts"` // 最后已知的POL轮次为非零有效块。 ValidRound int `json:"valid_round"` // Last known round with POL for non-nil valid block. // 上面提到的最后一个POL块。 ValidBlock *types.Block `json:"valid_block"` // Last known block of POL mentioned above. ValidBlockParts *types.PartSet `json:"valid_block_parts"` // Last known block parts of POL metnioned above. // 当前共识的所有 prevote Votes *HeightVoteSet `json:"votes"` // commit的轮次? CommitRound int `json:"commit_round"` // // 上一个 precommit的 voteSet ? LastCommit *types.VoteSet `json:"last_commit"` // Last precommits at Height-1 // 当前共识的轮次中的所有验证人 LastValidators *types.ValidatorSet `json:"last_validators"` // 是否触发超时 precommit ? TriggeredTimeoutPrecommit bool `json:"triggered_timeout_precommit"` } // Compressed version of the RoundState for use in RPC type RoundStateSimple struct { HeightRoundStep string `json:"height/round/step"` StartTime time.Time `json:"start_time"` ProposalBlockHash cmn.HexBytes `json:"proposal_block_hash"` LockedBlockHash cmn.HexBytes `json:"locked_block_hash"` ValidBlockHash cmn.HexBytes `json:"valid_block_hash"` Votes json.RawMessage `json:"height_vote_set"` } // Compress the RoundState to RoundStateSimple func (rs *RoundState) RoundStateSimple() RoundStateSimple { votesJSON, err := rs.Votes.MarshalJSON() if err != nil { panic(err) } return RoundStateSimple{ HeightRoundStep: fmt.Sprintf("%d/%d/%d", rs.Height, rs.Round, rs.Step), StartTime: rs.StartTime, ProposalBlockHash: rs.ProposalBlock.Hash(), LockedBlockHash: rs.LockedBlock.Hash(), ValidBlockHash: rs.ValidBlock.Hash(), Votes: votesJSON, } } // NewRoundEvent returns the RoundState with proposer information as an event. func (rs *RoundState) NewRoundEvent() types.EventDataNewRound { addr := rs.Validators.GetProposer().Address idx, _ := rs.Validators.GetByAddress(addr) return types.EventDataNewRound{ Height: rs.Height, Round: rs.Round, Step: rs.Step.String(), Proposer: types.ValidatorInfo{ Address: addr, Index: idx, }, } } // CompleteProposalEvent returns information about a proposed block as an event. func (rs *RoundState) CompleteProposalEvent() types.EventDataCompleteProposal { // We must construct BlockID from ProposalBlock and ProposalBlockParts // cs.Proposal is not guaranteed to be set when this function is called blockId := types.BlockID{ Hash: rs.ProposalBlock.Hash(), PartsHeader: rs.ProposalBlockParts.Header(), } return types.EventDataCompleteProposal{ Height: rs.Height, Round: rs.Round, Step: rs.Step.String(), BlockID: blockId, } } // RoundStateEvent returns the H/R/S of the RoundState as an event. func (rs *RoundState) RoundStateEvent() types.EventDataRoundState { return types.EventDataRoundState{ Height: rs.Height, Round: rs.Round, Step: rs.Step.String(), } } // String returns a string func (rs *RoundState) String() string { return rs.StringIndented("") } // StringIndented returns a string func (rs *RoundState) StringIndented(indent string) string { return fmt.Sprintf(`RoundState{ %s H:%v R:%v S:%v %s StartTime: %v %s CommitTime: %v %s Validators: %v %s Proposal: %v %s ProposalBlock: %v %v %s LockedRound: %v %s LockedBlock: %v %v %s ValidRound: %v %s ValidBlock: %v %v %s Votes: %v %s LastCommit: %v %s LastValidators:%v %s}`, indent, rs.Height, rs.Round, rs.Step, indent, rs.StartTime, indent, rs.CommitTime, indent, rs.Validators.StringIndented(indent+" "), indent, rs.Proposal, indent, rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort(), indent, rs.LockedRound, indent, rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort(), indent, rs.ValidRound, indent, rs.ValidBlockParts.StringShort(), rs.ValidBlock.StringShort(), indent, rs.Votes.StringIndented(indent+" "), indent, rs.LastCommit.StringShort(), indent, rs.LastValidators.StringIndented(indent+" "), indent) } // StringShort returns a string func (rs *RoundState) StringShort() string { return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`, rs.Height, rs.Round, rs.Step, rs.StartTime) } //----------------------------------------------------------- // These methods are for Protobuf Compatibility // Size returns the size of the amino encoding, in bytes. func (rs *RoundStateSimple) Size() int { bs, _ := rs.Marshal() return len(bs) } // Marshal returns the amino encoding. func (rs *RoundStateSimple) Marshal() ([]byte, error) { return cdc.MarshalBinaryBare(rs) } // MarshalTo calls Marshal and copies to the given buffer. func (rs *RoundStateSimple) MarshalTo(data []byte) (int, error) { bs, err := rs.Marshal() if err != nil { return -1, err } return copy(data, bs), nil } // Unmarshal deserializes from amino encoded form. func (rs *RoundStateSimple) Unmarshal(bs []byte) error { return cdc.UnmarshalBinaryBare(bs, rs) }
import './App.css'; import React, { useState, useEffect } from 'react'; import Sidebar from './components/Sidebar'; import Editor from './components/Editor'; import Split from 'react-split'; import 'react-mde/lib/styles/css/react-mde-all.css'; import { nanoid } from 'nanoid'; export default function App() { const [notes, setNotes] = useState(() => JSON.parse(localStorage.getItem('notes')) || []); const [currentNoteId, setCurrentNoteId] = useState((notes[0] && notes[0].id) || ''); useEffect(() => { localStorage.setItem('notes', JSON.stringify(notes)); }, [notes]); function createNewNote() { const newNote = { id: nanoid(), body: '# This Is a Title', }; setNotes(prevNotes => [newNote, ...prevNotes]); setCurrentNoteId(newNote.id); } function updateNote(text) { setNotes(oldNotes => { return oldNotes.map(note => { if (note.id === currentNoteId) { return { ...note, body: text }; } return note; }); }); } function deleteNote(event, noteId) { event.stopPropagation(); setNotes(oldNotes => oldNotes.filter(note => note.id !== noteId)); } function findCurrentNote() { return ( notes.find(note => { return note.id === currentNoteId; }) || notes[0] ); } return ( <main> {notes.length > 0 ? ( <Split sizes={[30, 70]} direction='horizontal' className='split'> <Sidebar notes={notes} currentNote={findCurrentNote(notes.id)} setCurrentNoteId={setCurrentNoteId} newNote={createNewNote} deleteNote={deleteNote} /> {currentNoteId && notes.length > 0 && ( <Editor currentNote={findCurrentNote(notes.id)} updateNote={updateNote} /> )} </Split> ) : ( <div className='no-notes'> <h1>You have no notes</h1> <button className='first-note' onClick={createNewNote}> Create one now </button> </div> )} </main> ); }
import 'package:flutter/material.dart'; import '../item.dart'; class ExpansionPanelRadioEx extends StatefulWidget { const ExpansionPanelRadioEx({Key? key}) : super(key: key); @override State<ExpansionPanelRadioEx> createState() => _ExpansionPanelRadioExState(); } class _ExpansionPanelRadioExState extends State<ExpansionPanelRadioEx> { final List<Item> _data = generateItems(8); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('ExpansionPanelRadioEx'), ), body: SingleChildScrollView( child: Container( child: _buildPanel(), ), ), ); } Widget _buildPanel() { return ExpansionPanelList.radio( initialOpenPanelValue: 3, children: _data.map<ExpansionPanelRadio>((Item item) { return ExpansionPanelRadio( value: item.id, headerBuilder: (BuildContext context, bool isExpanded) { return ListTile( title: Text(item.headerValue), ); }, body: ListTile( title: Text(item.expandedValue), ) ); }).toList(), ); } }
package exception.handler; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.LinkedHashSet; import java.util.Set; public class UnprocessableEntity extends ApiError{ private record ValidationError(String property, String message) { } private final Set<ValidationError> validationErrors = new LinkedHashSet<>(); public UnprocessableEntity(final int status, final String message, final String error) { super(error, message, status); } public void addValidationError(final String property, final String message) { this.validationErrors.add(new ValidationError(property, message)); } @JsonIgnore public String getValidationErrorsMessage() { return validationErrors.stream() .map(v -> "[property:" + v.property + "][message:" + v.message + "]") .reduce("", String::concat); } }
import {useEffect, useState} from "react"; import {subMonths} from "date-fns"; import {collection, DocumentData, getDocs, onSnapshot, query, Timestamp, where} from "firebase/firestore"; import {firebaseDatabase} from "~/domain/firebase"; export function useWeightData(timeRange: "daily" | "weekly" | "monthly" = "daily") { const [weightData, setWeightData] = useState<DocumentData[]>([]); useEffect(() => { const now = new Date(); const initialQuery = query( collection(firebaseDatabase, "weights"), where("created_at", ">=", Timestamp.fromDate(subMonths(now, 1))), where("created_at", "<=", Timestamp.fromDate(now)) ); getDocs(initialQuery).then((snapshot) => { const initialData = snapshot.docs.map((doc) => doc.data()); initialData.forEach((item) => { item.created_at = item.created_at.toDate(); }); setWeightData(initialData); }); // Listen for updates in the "weights" collection const unsubscribe = onSnapshot(collection(firebaseDatabase, "weights"), (snapshot) => { snapshot.docChanges() .filter((change) => change.type === "added") .forEach((change) => { const item = change.doc.data(); item.created_at = item.created_at.toDate(); setWeightData((prev) => { if (prev.some((prevItem) => prevItem.created_at.getTime() === item.created_at.getTime())) { return prev; } else { return [...prev, item]; } }); }); }, (error) => { console.log("Error listening for changes:", error); } ); return unsubscribe(); }, []); return weightData; }
import json import os import numpy as np import torch from torch.utils.data import Dataset from .language_utils import word_to_indices, VOCAB_SIZE, letter_to_index def read_data(train_data_dir, test_data_dir): """parses data in given train and test data directories assumes: - the data in the input directories are .json files with keys 'users' and 'user_data' - the set of train set users is the same as the set of test set users Return: clients: list of client ids groups: list of group ids; empty list if none found train_data: dictionary of train data test_data: dictionary of test data """ clients = [] groups = [] train_data = {} test_data = {} train_files = os.listdir(train_data_dir) train_files = [f for f in train_files if f.endswith(".json")] for f in train_files: file_path = os.path.join(train_data_dir, f) with open(file_path, "r") as inf: cdata = json.load(inf) clients.extend(cdata["users"]) if "hierarchies" in cdata: groups.extend(cdata["hierarchies"]) train_data.update(cdata["user_data"]) test_files = os.listdir(test_data_dir) test_files = [f for f in test_files if f.endswith(".json")] for f in test_files: file_path = os.path.join(test_data_dir, f) with open(file_path, "r") as inf: cdata = json.load(inf) test_data.update(cdata["user_data"]) clients = list(sorted(train_data.keys())) return clients, groups, train_data, test_data def process_x(raw_x_batch): x_batch = [word_to_indices(word) for word in raw_x_batch] return x_batch def process_y(raw_y_batch): y_batch = [letter_to_index(c) for c in raw_y_batch] return y_batch def batch_data(data, batch_size): """ data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client) returns x, y, which are both numpy array of length: batch_size """ data_x = data["x"] data_y = data["y"] # randomly shuffle data np.random.seed(100) rng_state = np.random.get_state() np.random.shuffle(data_x) np.random.set_state(rng_state) np.random.shuffle(data_y) # loop through mini-batches batch_data = list() for i in range(0, len(data_x), batch_size): batched_x = data_x[i : i + batch_size] batched_y = data_y[i : i + batch_size] batched_x = torch.from_numpy(np.asarray(process_x(batched_x))) batched_y = torch.from_numpy(np.asarray(process_y(batched_y))) batch_data.append((batched_x, batched_y)) return batch_data def load_partition_data_shakespeare(batch_size,dataset_dir): train_path = dataset_dir+"/train" test_path = dataset_dir+"/test" users, groups, train_data, test_data = read_data(train_path, test_path) if len(groups) == 0: groups = [None for _ in users] train_data_num = 0 test_data_num = 0 train_data_local_dict = dict() test_data_local_dict = dict() train_data_local_num_dict = dict() train_data_global = list() test_data_global = list() client_idx = 0 for u, g in zip(users, groups): user_train_data_num = len(train_data[u]["x"]) user_test_data_num = len(test_data[u]["x"]) train_data_num += user_train_data_num test_data_num += user_test_data_num train_data_local_num_dict[client_idx] = user_train_data_num # transform to batches train_batch = batch_data(train_data[u], batch_size) test_batch = batch_data(test_data[u], batch_size) # index using client index train_data_local_dict[client_idx] = train_batch test_data_local_dict[client_idx] = test_batch train_data_global += train_batch test_data_global += test_batch client_idx += 1 client_num = client_idx output_dim = VOCAB_SIZE return ( client_num, train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, output_dim, ) class shakespeare_loader(Dataset): def __init__(self,single_client_data): self.batch_num = len(single_client_data) self.sample_num = 0 self.x = [] self.y = [] for batch_idx in range(self.batch_num): batch = single_client_data[batch_idx] self.x.append(batch[0]) self.y.append(batch[1]) self.sample_num += len(batch[0]) def __len__(self): return self.sample_num def __getitem__(self,index): return (self.x[index],self.y[index]) def get_shakespeare_dataloader(batch_size,dataset_dir): ( client_num, train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, output_dim, ) = load_partition_data_shakespeare(batch_size,dataset_dir) train_loaders = [] test_loaders = [] test_data_global = shakespeare_loader(test_data_global) for loader_idx in range(client_num): train_loaders.append(shakespeare_loader(train_data_local_dict[loader_idx])) test_loaders.append(shakespeare_loader(test_data_local_dict[loader_idx])) return ( client_num, train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_loaders, test_loaders, output_dim, )
import React, { useEffect, useState } from 'react' import ReactDOM from 'react-dom' import './options.css' // Material UI Component import {Box, Button, Card, CardContent, Grid, Switch, TextField, Typography} from '@mui/material'; // Utils import { setStoredOptions, LocalStorageOptions, getStoredOptions } from '../utils/storage'; type FormState = 'ready' | 'saving'; const App: React.FC<{}> = () => { const [options, setOptions] = useState<LocalStorageOptions | null>(null); const [formState, setFormState] = useState<FormState>('ready'); useEffect(() => { getStoredOptions().then((options) => setOptions(options)); }, []); const handleHomeCityOptions = (homeCity: string) => { setOptions({ ...options, homeCity }) }; const handleAutoOverlayChange = (hasAutoOverlay: boolean) => { setOptions({ ...options, hasAutoOverlay }); }; const handleSaveButtonClick = () => { setFormState("saving"); setStoredOptions(options).then(() => { setTimeout(() => { setFormState("ready"); }, 1000); }); }; if(!options) { return null; } const isFieldsDisabled = formState === 'saving'; return ( <Box mx="10%" my="2%"> <Card> <CardContent> <Grid container direction='column' spacing={4}> <Grid item> <Typography variant='h4'>Weather Extention Options</Typography> </Grid> <Grid item> <Typography variant='body1'>Home City Name</Typography> <TextField fullWidth variant='standard' label='City' placeholder='Enter a home city' value={options.homeCity} onChange={(e) => handleHomeCityOptions(e.target.value)} /> </Grid> <Grid item> <Typography variant='body1'>Auto toggle overlay on webpage load</Typography> <Switch color='primary' checked={options.hasAutoOverlay} onChange={(e, checked) => handleAutoOverlayChange(checked)} disabled={isFieldsDisabled} /> </Grid> <Grid item> <Button variant='contained' color='success' onClick={handleSaveButtonClick} disabled={isFieldsDisabled}> {formState === "ready" ? "Save" : "Saving . . ."} </Button> </Grid> </Grid> </CardContent> </Card> </Box> ) } const root = document.createElement('div') document.body.appendChild(root) ReactDOM.render(<App />, root)
<script> import {errorState} from "../../store/SiteStore"; import { onMount } from "svelte"; import {push , querystring} from "svelte-spa-router"; import qs from 'qs'; import SectionLayout from '../../components/layout/SectionLayout.svelte' import FileUpload from "../../components/utils/FileUpload.svelte"; import Error from "../../components/Error.svelte"; let Mode = "create"; let questions = [ {id: 1, text: `육류`}, {id: 2, text: `해산물`}, {id: 3, text: `야채`}, {id: 3, text: `과일`} ]; let formData = { productCoverImages: [], productMainImages: [], title: "", description: "", selected: questions[0].text, price: "" }; const getData = async (id) => { const res = await firebase.firestore().collection("products").doc(decodeURI(id)).get(); // console.log(res.data()) formData = res.data() } onMount(() => { // console.log($querystring) const query = qs.parse($querystring); // console.log(query) if (query.id) { getData(query.id) Mode = 'modify' } }) const handleSubmit = async () => { if (formData.productCoverImages.length !== 1) { $errorState = { open: true, errorMessage: "커버이미지를 등록해주세요." }; return false; } if (formData.title === "") { $errorState = { open: true, errorMessage: "상품 이름을 입력해주세요." }; return false; } if (formData.description === "") { $errorState = { open: true, errorMessage: "상품 설명을 입력해주세요." }; return false; } if (formData.price === "") { $errorState = { open: true, errorMessage: "상품 가격을 입력해주세요." }; return false; } if (formData.productMainImages.length !== 1) { $errorState = { open: true, errorMessage: "메인이미지를 등록해주세요." }; return false; } const today = new Date(); let dd = today.getDate(); let mm = today.getMonth() + 1; //January is 0! const yyyy = today.getFullYear(); if (dd < 10) { dd = "0" + dd; } if (mm < 10) { mm = "0" + mm; } let date, createdAt, _name; if (Mode === "create") { date = yyyy + "-" + mm + "-" + dd; createdAt = today; _name = yyyy + mm + dd; } else { date = formData.date; createdAt = formData.createdAt; _name = formData._name; } const modifiedAt = today; formData.date = date; formData.createdAt = createdAt; formData.modifiedAt = modifiedAt; formData._name = _name; if (Mode === 'create') { const RandomNumber = Math.random().toString(36).substr(2, 11); formData.id = `product${RandomNumber}${_name}`; } // console.log(formData); try { await firebase.firestore().collection("products").doc(formData.id).set(formData); push("/upload-product-list"); } catch (e) { console.log(e); } // const formData = new FormData(); // Currently empty // console.log(formData); }; </script> <style> textarea { height: 150px; resize: none; } </style> <SectionLayout Title="상품 업로드" subTitle="상품 업로드 페이지입니다."> <form on:submit|preventDefault={handleSubmit}> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <span class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="name"> 커버 이미지 </span> <FileUpload section="product" maxitem="1" bind:imageLists={formData.productCoverImages}/> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="name"> 상품 이름 </label> <input class="appearance-none block w-full bg-gray-200 text-gray-700 border-2 border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" id="name" type="text" placeholder="" bind:value={formData.title}/> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="description"> 상품 간단 설명 </label> <textarea class="appearance-none block w-full bg-gray-200 text-gray-700 border-2 border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-purple-500 " id="description" type="text" placeholder="" maxlength="200" bind:value={formData.description}/> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="category"> 상품 카테고리 </label> <select name="category" id="category" bind:value={formData.selected} class="block appearance-none w-full bg-gray-200 border-2 border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tightfocus:outline-none focus:bg-white focus:border-purple-500"> {#each questions as question} <option value={question}>{question.text}</option> {/each} </select> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="price"> 상품 가격 </label> <input class="appearance-none block w-full bg-gray-200 text-gray-700 border-2 border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" id="price" type="number" placeholder="" bind:value={formData.price}/> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <span class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="name"> 상품 상세이미지 </span> <FileUpload section="product" maxitem="1" fullWidth bind:imageLists={formData.productMainImages}/> </div> </div> <button type="submit" class="bg-purple-500 hover:bg-purple-400 rounded px-4 py-2 text-white focus:shadow-outline focus:outline-none"> 업로드 </button> </form> </SectionLayout> <Error backcolor="red"/>
const fs = require('fs') const path = require('path') const transform = require('./convert-svg-to-omi') const folderPath = 'dist' if (!fs.existsSync(folderPath)) { // 文件夹不存在,创建文件夹 fs.mkdirSync(folderPath) } const svgDir = 'src/_icons/svg' const iconDir = 'dist' const indexFile = 'dist/index.js' const data = fs.readFileSync('src/style.js', 'utf8') fs.writeFileSync('dist/style.js', data, 'utf8') const jsonData = fs.readFileSync('package.json', 'utf8') fs.writeFileSync('dist/package.json', jsonData, 'utf8') const readmeData = fs.readFileSync('README.md', 'utf8') fs.writeFileSync('dist/README.md', readmeData, 'utf8') // 读取 SVG 目录 fs.readdir(svgDir, (err, files) => { if (err) { console.error('Error reading SVG directory:', err) return } let exports = '' // 遍历 SVG 文件 files.forEach((file) => { if (path.extname(file) === '.svg') { const iconName = path.basename(file, '.svg') exports += `export { Icon${removeDashAndCapitalize( iconName )} } from './${iconName}'\n` } }) // 将所有 SVG 内容写入 index.ts 文件 fs.writeFileSync(indexFile, exports) }) // 确保 icons 目录存在 if (!fs.existsSync(iconDir)) { fs.mkdirSync(iconDir) } // 读取 SVG 目录 fs.readdir(svgDir, (err, files) => { if (err) { console.error('Error reading SVG directory:', err) return } let html = '' // 遍历 SVG 文件 files.forEach((file) => { if (path.extname(file) === '.svg') { const iconName = path.basename(file, '.svg') const iconPath = path.join(iconDir, `${iconName}.js`) // 读取 SVG 文件内容 const svgContent = fs.readFileSync(path.join(svgDir, file), 'utf-8') // 创建 Omi icon 元素 const iconComponent = `import { h, define, WeElement, classNames } from 'omi' import { iconStyle } from './style.js' export class Icon${removeDashAndCapitalize(iconName)} extends WeElement { static css = iconStyle static defaultProps = { size: '1em', style: { fill: '#000' }, } static propTypes = { size: [String, Number], style: Object, class: String, } render(props) { const iconClassName = classNames('t-icon', props.class, { ['t-size-s']: props.size === 'small', ['t-size-m']: props.size === 'medium', ['t-size-l']: props.size === 'large', }) const flag = props.size === 'small' || props.size === 'medium' || props.size === 'large' const iconStyle = { ...props.style, fontSize: props.size, } return ${transform(transformSvgContent(svgContent))} } } define('t-icon-${iconName}', Icon${removeDashAndCapitalize(iconName)}) ` // 将 Omi icon 元素写入文件 fs.writeFileSync(iconPath, iconComponent) html += ` <li class="t-icons-view__wrapper"> ${svgContent} <div class="t-icons-view__name">${iconName}</div> <div class="t-icons-view__actions"><svg width="1em" height="1em" style="font-size: 20px; color: var(--text-secondary);"> <use href="#t-icon-file-copy"></use> </svg> <div class="t-icons-view__actions-divider"></div><svg width="1em" height="1em" style="font-size: 20px; color: var(--text-secondary);"> <use href="#t-icon-file-icon"></use> </svg> </div> </li>` } }) fs.writeFileSync('index.html', html) }) function transformSvgContent(svgContent) { svgContent= svgContent.replace(/fill="black"/g, 'fill="currentColor"') return svgContent.replace( /<svg width="\d{2}" height="\d{2}"/, `<svg class={iconClassName} width={flag ? '24' : props.size} height={flag ? '24' : props.size} style={iconStyle}` ) } function removeDashAndCapitalize(str) { const words = str.split('-') const capitalizedWords = words.map((word) => { const firstLetter = word.charAt(0).toUpperCase() const restOfWord = word.slice(1) return firstLetter + restOfWord }) return capitalizedWords.join('') }
# Optionals TypeScript doesn't technically have "optional" types. Instead, users must create union types that incorporate either `null` or `undefined`: ```typescript const x: User | null = { name: 'Bill Gates' }; // Error: x is possibly 'null' console.log(x.name); ``` Rust, on the other hand, has an official `Option` type. In fact, Rust's approach to optionals aligns very closely with that of [Swift](https://developer.apple.com/documentation/swift/optional). In Rust, a variable of type `Option<T>` means that the variable is either: - **`None`**: a safe way of representing `null`, or an "empty" value - **`Some<T>`**: a wrapper around the value (of type `T`) However – how do you know if a variable is `Some` or `None`? In TypeScript, you might use some form of [type narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html). In Rust, we have a full set of built-in keywords that make working with optionals a breeze. ## Matching Although the [`match` keyword](../logic-flow/match.md) can function as a kind of `switch` statement, it also can be used to infer the value of optional types. Take for example the following code: ```rust fn my_func(op: Option<i32>) { match op { None => { println!("No value!") }, Some(value) => { println!("Contained value {}!", op) }, } } ``` ## Conditionals In TypeScript, ensuring a type is not null is pretty straightforward: ```typescript if (x !== null) { console.log(x.name); // TSC knows that `x` is not null } ``` However, seeing we have two separate types representing `null` and not-`null` in Rust, how do we write a similar `if` statement? Fortunately, Rust gives us the `if let` keyword: ```rust if let x = Some(user) { println!("{}", user.name); } ``` Of course, checking for `None` also works just like you'd expect: ```rust if x == None { println!("Value is none!"); } ``` ## Additional Reading - [Rust by Example: Option](https://doc.rust-lang.org/rust-by-example/std/option.html?highlight=option#option)
import { Test, TestingModule } from '@nestjs/testing'; import { PaymentService } from '../payment.service'; import { Repository } from 'typeorm'; import { PaymentEntity } from '../entities/payment.entity'; import { getRepositoryToken } from '@nestjs/typeorm'; import { paymentMock } from '../__mocks__/payment.mock'; import { createOrderCreditCardMock, createOrderPixMock, } from '../../order/__mocks__/createOrder.mock'; import { productMock } from '../../product/__mocks__/product.mock'; import { cartMock } from '../../cart/__mocks__/cart.mock'; import { paymentCreditCardMock } from '../__mocks__/paymentCreditCard.mock'; import { paymentPixMock } from '../__mocks__/paymentPix.mock'; import { PaymentPixEntity } from '../entities/payment-pix.entity'; import { PaymentCreditCardEntity } from '../entities/payment-credit-card.entity'; import { BadRequestException } from '@nestjs/common'; import { addressMock } from '../../address/__mocks__/address.mock'; import { cartProductMock } from '../../cart-product/__mocks__/cart-product.mock'; import { PaymentType } from '../../payment-status/enums/payment-type.enum'; describe('PaymentService', () => { let service: PaymentService; let paymentRepository: Repository<PaymentEntity>; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ PaymentService, { provide: getRepositoryToken(PaymentEntity), useValue: { find: jest.fn().mockResolvedValue([paymentMock]), save: jest.fn().mockResolvedValue(paymentMock), }, }, ], }).compile(); service = module.get<PaymentService>(PaymentService); paymentRepository = module.get<Repository<PaymentEntity>>( getRepositoryToken(PaymentEntity), ); }); it('should be defined', () => { expect(service).toBeDefined(); expect(paymentRepository).toBeDefined(); }); it('should return payment Pix after save in database', async () => { const spy = jest.spyOn(paymentRepository, 'save'); const payment = await service.createPayment( createOrderPixMock, [productMock], cartMock, ); const savePayment = spy.mock.calls[0][0] as PaymentPixEntity; expect(payment).toEqual(paymentMock); expect(savePayment.code).toEqual(paymentPixMock.code); }); it('should return payment Credit Card after save in database', async () => { const spy = jest.spyOn(paymentRepository, 'save'); const payment = await service.createPayment( createOrderCreditCardMock, [productMock], cartMock, ); const savePayment = spy.mock.calls[0][0] as PaymentCreditCardEntity; expect(payment).toEqual(paymentMock); expect(savePayment.amountPayments).toEqual( paymentCreditCardMock.amountPayments, ); }); it('should return error in exception in payment', async () => { expect( service.createPayment( { addressId: addressMock.id }, [productMock], cartMock, ), ).rejects.toThrowError(BadRequestException); }); it('should return final price 0 in cartProduct undefined', async () => { const spy = jest.spyOn(paymentRepository, 'save'); await service.createPayment( createOrderCreditCardMock, [productMock], cartMock, ); const savePayment = spy.mock.calls[0][0] as PaymentCreditCardEntity; expect(savePayment.finalPrice).toEqual(0); }); it('should return final price 500 in cartProduct send', async () => { const spy = jest.spyOn(paymentRepository, 'save'); await service.createPayment(createOrderCreditCardMock, [productMock], { ...cartMock, cartProduct: [cartProductMock], }); const savePayment = spy.mock.calls[0][0] as PaymentCreditCardEntity; expect(savePayment.finalPrice).toEqual(500); }); it('should return all data in save payment', async () => { const spy = jest.spyOn(paymentRepository, 'save'); await service.createPayment(createOrderCreditCardMock, [productMock], { ...cartMock, cartProduct: [cartProductMock], }); const savePayment = spy.mock.calls[0][0] as PaymentCreditCardEntity; const paymentCreditCart: PaymentCreditCardEntity = new PaymentCreditCardEntity( PaymentType.Done, 500, 0, 500, createOrderCreditCardMock, ); expect(savePayment).toEqual(paymentCreditCart); }); });
import React, { useState } from "react"; import { Story, Meta } from "@storybook/react/types-6-0"; import { Modal, Props } from "../components/Modal"; import { Button } from "../components/Button"; import { Form } from "../components/Form"; import { FormFieldsType } from "../model"; export default { title: "Modal", component: Modal, } as Meta; const Template: Story<Props> = (args) => { const [open, setOpen] = useState<boolean>(false); return ( <> <Button onClick={() => setOpen(true)}>Open Modal</Button> <Modal {...args} open={open} onClose={() => setOpen(false)} /> </> ); }; export const ModalStory = Template.bind({}); ModalStory.args = { title: "Modal example", }; const ModalFormTemplate: Story<Props> = (args) => { const [open, setOpen] = useState<boolean>(false); const [value, setValue] = useState<any>({ test: "", check: true, num: 420.69, myObject: { value: { customValue: 342 }, id: "2321", label: "Custom object", }, dateOfBirth: null, }); const fields: FormFieldsType<any> = [ { label: "Test text field", type: "text", name: "test", placeholder: "please input a text", }, { label: "Test checkbox field", type: "bool", name: "check", }, { label: "Test num field", type: "number", name: "num", placeholder: "Please enter a number", }, { label: "Date of Birth", type: "date", name: "dateOfBirth", placeholder: "date of birth", }, { label: "Test select field", type: "select", name: "myObject", options: [ { value: { customValue: 42 }, id: "42", label: "42" }, { value: { customValue: 43 }, id: "4354", label: "Test" }, { value: { customValue: 342 }, id: "2321", label: "Custom object" }, ], }, ]; return ( <> <Button onClick={() => setOpen(true)}>Open Modal</Button> <Modal {...args} open={open} onClose={() => setOpen(false)}> <Form fields={fields} onChange={setValue} value={value} /> </Modal> </> ); }; export const ModalFormStory = ModalFormTemplate.bind({}); ModalFormStory.args = { title: "Modal with form", };
import { useFetchQuery, useRouterQuery } from "@/hooks"; import { Avatar, Button, message, Modal, Select, TableProps, Tag } from "antd"; import dayjs from "dayjs"; import { AntDesignOutlined, DeleteOutlined, EyeOutlined } from "@ant-design/icons"; import { IAnswerCategories } from "@/modules/answer-category/model/answer-categories.model.ts"; import { httpClient } from "@/utils"; import { useState } from "react"; import { Typography } from 'antd'; import { priceFormat } from "@/utils/price-format"; const { Option } = Select; const { Paragraph, } = Typography; interface DataType { key: string; name: string; age: number; address: string; tags: string[]; } const useAllUserProps = () => { const {GetRouterQuery, SetRouterQuery} = useRouterQuery(); const [open, setOpen] = useState(false); const [values, setValues] = useState<IAnswerCategories>(); const {data, isLoading, refetch} = useFetchQuery({ url: 'user' }); const onAdd = () => { setOpen(true); setValues(undefined) } const handleDelete = (id: number) => { Modal.confirm({ title: 'Are you sure you want to delete this user?', icon: <DeleteOutlined />, okText: 'Yes', okType: 'danger', cancelText: 'No', onOk: async () => { try { await httpClient.delete(`user/${id}`); message.success('User deleted successfully'); setOpen(false); refetch(); } catch (error) { message.error('Failed to delete user'); }finally { setOpen(false); } }, }); }; const columns: TableProps<DataType>['columns'] = [ { title: 'id', dataIndex: 'id', key: 'id', render: (data)=> { return <Paragraph copyable className='font-bold'>{data}</Paragraph> } }, { title: 'User Image', dataIndex: 'image', key: 'image', render: () => { return <Avatar size="large" icon={<AntDesignOutlined />} /> } }, { title: 'User name', dataIndex: 'name', key: 'name', }, { title: 'Phone', dataIndex: 'phone', key: 'phone', }, { title: 'Balance', dataIndex: 'balance', key: 'balance', render: (data)=> { return <Tag color='green'>{priceFormat(data)} som</Tag> } }, { title: 'Phone', dataIndex: 'phone', key: 'phone', }, { title: 'Booked Count', dataIndex: 'bookedCount', key: 'bookedCount', }, { title: 'User Banned', dataIndex: '', key: 'isBanned', render: (data)=> { const handleChange = async (value: boolean | string) => { try { if(value){ await httpClient.put(`user/ban/${data?.id}`); message.success('User banned') }else{ await httpClient.put(`user/deban/${data?.id}`) message.success('User debanned') } refetch() }catch (err) { console.log(err) } }; return ( <Select defaultValue={data?.isBanned ? "Banned" : "Not banned"} style={{ width: 120, }} onChange={handleChange}> <Option value={true}>Banned</Option> <Option value={false}>Not Banned</Option> </Select> ); } }, { title: 'Status', key: 'status', render: (data) => { return ( <div> <Tag color={data?.isActive ? 'green' : 'red'}>{data?.isActive ? 'Active' : "No Active"}</Tag> </div> ) } }, { title: 'Created Date', dataIndex: 'createdAt', key: 'createdAt', render: (date) => { return dayjs(date).format('YYYY-MM-DD, HH:mm') } }, { title: 'Updated Date', dataIndex: 'updatedAt', key: 'updatedAt', render: (date) => { return date ? dayjs(date).format('YYYY-MM-DD, HH:mm') : 'Not updated yet' } }, { title: 'Actions', key: 'actions', render: (data) => { return ( <div> <div className='flex items-center gap-2'> {/*<CustomDropdown*/} {/* onClickEdit={() =>{}}*/} {/* onClickDelete={() => {}}*/} {/* onClickInfo={() => {}}*/} {/*/>*/} <Button onClick={() => {}} icon={<EyeOutlined/>}>See rides histroy</Button> <Button onClick={() => handleDelete(data?.id)} danger icon={<DeleteOutlined/>}>Delete</Button> </div> </div> ) } }, ]; return { data, isLoading, GetRouterQuery, SetRouterQuery, columns, refetch, open, setOpen, values, setValues, onAdd, handleDelete, } } export default useAllUserProps;
-- BBDD libreria -- 1. Number of records in the table "libros". SELECT count(*) AS records FROM libros; -- 2. Number of books published by "Planeta". SELECT sum(cantidad) AS 'editorial Planeta' FROM libros WHERE editorial = 'Planeta'; -- 3. Number of books of the writer "Borges" (also if he is coauthor). SELECT count(*) AS 'books of "Borges"' FROM libros WHERE autor LIKE '%Borges%'; -- 4. Number of books that have a price. SELECT count(*) AS 'books with price' FROM libros WHERE precio IS NOT NULL; -- 5. Number of books we have available. SELECT sum(cantidad) AS 'books available' FROM libros WHERE cantidad > 0; -- 6. Price of the most expensive book. SELECT max(precio) AS 'most expensive book' FROM libros; -- 7. Query of books sorted by price in descending. SELECT * FROM libros ORDER BY precio DESC; -- 8. Cheaper price of the book of "Rowling". SELECT min(precio) AS 'Cheaper book of JK Rowling' FROM libros WHERE autor LIKE 'J.K. Rowling'; -- 9. Query of books of "Rowling" sorted by price in ascending. SELECT * FROM libros WHERE autor LIKE 'J.K. Rowling' ORDER BY precio ASC; -- 10. Average price of books on "PHP". SELECT avg(precio) AS 'Average price' FROM libros WHERE titulo LIKE '%PHP%'; -- 11. Number of books published by every editorial. SELECT editorial, count(*) AS 'Number of books' FROM libros GROUP BY editorial; -- 12. Number of books published by editorials that have more than 2 books. SELECT editorial, count(*) AS 'Number of books' FROM libros GROUP BY editorial HAVING count(*) > 2; -- 13. Price average of books published by every editorial. SELECT editorial, avg(precio) AS 'Average price' FROM libros GROUP BY editorial; -- 14. Price average of the books published by every editorial whose average is greater than 25 euros. SELECT editorial, avg(precio) AS 'Average price' FROM libros GROUP BY editorial HAVING avg(precio) > 25; -- 15. Number of books published by every editorial except from “Planeta” (2 different SQL commands) -- WHERE SELECT editorial, count(*) AS 'Number of books' FROM libros WHERE editorial != 'Planeta' GROUP BY editorial; -- HAVING SELECT editorial, count(*) AS 'Number of books' FROM libros GROUP BY editorial HAVING editorial != 'Planeta'; -- 16. Number of books published by every editorial except from “Planeta” and without counting those books with no price. SELECT editorial, count(*) AS 'Number of books' FROM libros WHERE editorial != 'Planeta' AND precio IS NOT NULL GROUP BY editorial; -- 17. Price average of books published by the editorials with more than 2 books. SELECT editorial, avg(precio) AS 'Average price' FROM libros GROUP BY editorial HAVING count(*) > 2; -- 18. Price of the most expensive book published by every editorial (only books of 30 or more euros). SELECT editorial, max(precio) AS 'most expensive book' FROM libros WHERE precio >= 30 GROUP BY editorial;
import { INestApplication } from '@nestjs/common'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import * as path from 'path'; import { ApiModule } from './app/api/api.module'; const PACKAGE_FILE_PATH = path.join(__dirname, '../package.json'); export async function bootstrapSwagger(app: INestApplication): Promise<void> { // eslint-disable-next-line @typescript-eslint/no-var-requires const currentPackage = require(PACKAGE_FILE_PATH); const appName = currentPackage.name .replace('-', ' ') .split(' ') .map((word: string) => word.charAt(0).toUpperCase() + word.substring(1)) .join(' '); const config = new DocumentBuilder() .setTitle(appName) .setDescription(`${currentPackage.description} ${getSwaggerDescription()}`) .setVersion(process.env.APP_VERSION || currentPackage.version) .setLicense(currentPackage.license, currentPackage.licenseUrl) .setExternalDoc(currentPackage.homepage, currentPackage.homepage) .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config, { include: [ApiModule], }); SwaggerModule.setup('/swagger', app, document, { customfavIcon: '/static/favicon.ico', customSiteTitle: appName, }); } export function getSwaggerDescription(): string { return ` <p> <a href="https://codecov.io/gh/Ealenn/dofus-together"><img src="https://img.shields.io/codecov/c/github/ealenn/dofus-together?style=for-the-badge&amp;logo=codecov" alt="Codecov"></a> <a href="https://www.codefactor.io/repository/github/ealenn/dofus-together"><img src="https://img.shields.io/codefactor/grade/github/ealenn/dofus-together?style=for-the-badge" alt="CodeFactor Grade"></a> <a href="https://github.com/Ealenn/dofus-together/stargazers"><img src="https://img.shields.io/github/stars/Ealenn/dofus-together?style=for-the-badge&amp;logo=github" alt="GitHub stars"></a> <a href="https://github.com/Ealenn/dofus-together/issues"><img src="https://img.shields.io/github/issues/Ealenn/dofus-together?style=for-the-badge&amp;logo=github" alt="GitHub issues"></a> </p> `; }
<?php use App\Models\Menu; use App\Models\tablle; use App\Models\User; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('reservations', function (Blueprint $table) { $table->id(); $table->string('full_name'); $table->string('email'); $table->string('tel_number'); $table->date('res_date'); $table->time('res_heure'); $table->foreignIdFor(tablle::class, 'tablle_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate(); $table->foreignIdFor(Menu::class, 'menu_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate(); $table->foreignIdFor(User::class, 'user_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate(); $table->integer('nombre_de_personnes'); $table->text('demandes_speciales')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('reservations'); } };
/* Copyright (C) 2017 Coos Baakman This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <string> #include <list> #include <stdio.h> #include <cstring> #include "exception.h" #include "shader.h" void GetShaderTypeName(GLenum type, char *pOut) { switch (type) { case GL_VERTEX_SHADER: strcpy(pOut, "vertex"); break; case GL_FRAGMENT_SHADER: strcpy(pOut, "fragment"); break; case GL_GEOMETRY_SHADER: strcpy(pOut, "geometry"); break; case GL_TESS_CONTROL_SHADER: strcpy(pOut, "tessellation control"); break; case GL_TESS_EVALUATION_SHADER: strcpy(pOut, "tessellation evaluation"); break; default: strcpy(pOut, ""); }; } GLuint CreateShader(const std::string& source, GLenum type) { char typeName[100]; GetShaderTypeName(type, typeName); if (!typeName[0]) { throw FormatableException("Unknown shader type: %.4X", type); } GLint result; int logLength; GLuint shader = glCreateShader(type); // Compile const char *src_ptr = source.c_str(); glShaderSource(shader, 1, &src_ptr, NULL); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (result != GL_TRUE) { // Error occurred, get compile log: glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); char *errorString = new char[logLength + 1]; glGetShaderInfoLog(shader, logLength, NULL, errorString); FormatableException e("Error compiling %s shader: %s", typeName, errorString); delete [] errorString; glDeleteShader(shader); throw e; } return shader; } GLuint CreateShaderProgram(const std::list <GLuint>& shaders); GLuint CreateShaderProgram(const GLuint s1) { std::list <GLuint> shaders; shaders.push_back(s1); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram (const GLuint s1, const GLuint s2) { std::list <GLuint> shaders; shaders.push_back(s1); shaders.push_back(s2); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram(const GLuint s1, const GLuint s2, const GLuint s3) { std::list <GLuint> shaders; shaders.push_back(s1); shaders.push_back(s2); shaders.push_back(s3); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram(const GLuint s1, const GLuint s2, const GLuint s3, const GLuint s4) { std::list <GLuint> shaders; shaders.push_back(s1); shaders.push_back(s2); shaders.push_back(s3); shaders.push_back(s4); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram(const GLuint s1, const GLuint s2, const GLuint s3, const GLuint s4, const GLuint s5) { std::list <GLuint> shaders; shaders.push_back(s1); shaders.push_back(s2); shaders.push_back(s3); shaders.push_back(s4); shaders.push_back(s5); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram(const GLuint s1, const GLuint s2, const GLuint s3, const GLuint s4, const GLuint s5, const GLuint s6) { std::list <GLuint> shaders; shaders.push_back(s1); shaders.push_back(s2); shaders.push_back(s3); shaders.push_back(s4); shaders.push_back(s5); shaders.push_back(s6); return CreateShaderProgram(shaders); } GLuint CreateShaderProgram(const std::list <GLuint>& shaders) { GLint result = GL_FALSE; int logLength; GLuint program = 0; // Combine the compiled shaders into a program: program = glCreateProgram(); for (auto shader : shaders) glAttachShader(program, shader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &result); if (result != GL_TRUE) { // Error occurred, get log: glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); char *errorString = new char[logLength]; glGetProgramInfoLog(program, logLength, NULL, errorString); FormatableException e("Error linking shader program: %s", errorString); delete [] errorString; glDeleteProgram(program); throw e; } return program; } GLuint CreateShaderProgram(GLenum type1, const std::string& source1) { GLuint sh1 = CreateShader(source1, type1); if (!sh1) { glDeleteShader(sh1); return 0; } GLuint program = CreateShaderProgram(sh1); // schedule to delete when program is deleted glDeleteShader(sh1); return program; } GLuint CreateShaderProgram(GLenum type1, const std::string& source1, GLenum type2, const std::string& source2) { GLuint sh1 = CreateShader(source1, type1), sh2 = CreateShader(source2, type2); if (!(sh1 && sh2)) { glDeleteShader(sh1); glDeleteShader(sh2); return 0; } GLuint program = CreateShaderProgram(sh1, sh2); // schedule to delete when program is deleted glDeleteShader(sh1); glDeleteShader(sh2); return program; } GLuint CreateShaderProgram(GLenum type1, const std::string& source1, GLenum type2, const std::string& source2, GLenum type3, const std::string& source3) { GLuint sh1 = CreateShader(source1, type1), sh2 = CreateShader(source2, type2), sh3 = CreateShader(source3, type3); if (!(sh1 && sh2 && sh3)) { glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); return 0; } GLuint program = CreateShaderProgram(sh1, sh2, sh3); // schedule to delete when program is deleted glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); return program; } GLuint CreateShaderProgram(GLenum type1, const std::string& source1, GLenum type2, const std::string& source2, GLenum type3, const std::string& source3, GLenum type4, const std::string& source4) { GLuint sh1 = CreateShader(source1, type1), sh2 = CreateShader(source2, type2), sh3 = CreateShader(source3, type3), sh4 = CreateShader(source4, type4); if (!(sh1 && sh2 && sh3 && sh4)) { glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); glDeleteShader(sh4); return 0; } GLuint program = CreateShaderProgram(sh1, sh2, sh3, sh4); // schedule to delete when program is deleted glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); glDeleteShader(sh4); return program; } GLuint CreateShaderProgram(GLenum type1, const std::string& source1, GLenum type2, const std::string& source2, GLenum type3, const std::string& source3, GLenum type4, const std::string& source4, GLenum type5, const std::string& source5) { GLuint sh1 = CreateShader(source1, type1), sh2 = CreateShader(source2, type2), sh3 = CreateShader(source3, type3), sh4 = CreateShader(source4, type4), sh5 = CreateShader(source5, type5); if (!(sh1 && sh2 && sh3 && sh4 && sh5)) { glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); glDeleteShader(sh4); glDeleteShader(sh5); return 0; } GLuint program = CreateShaderProgram(sh1, sh2, sh3, sh4, sh5); // schedule to delete when program is deleted glDeleteShader(sh1); glDeleteShader(sh2); glDeleteShader(sh3); glDeleteShader(sh4); glDeleteShader(sh5); return program; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> /************************ box-sizing原理 ************************/ /* html, body { height: 100%; padding: 0; margin: 0; } .wrap { width: 100px; height: 100%; box-sizing: border-box; padding-top: 100px; } .a { height: 100px; margin-top: -100px; background-color: #0b8bd4; } .b { height: 100%; background-color: #d4311a; } */ /*************************** position原理 *******************************/ /* html, body { margin: 0; padding: 0; height: 100%; } .wrap { position: relative; width: 100px; height: 100%; } .a { height: 100px; background-color: #0b8bd4; } .b { position: absolute; top: 100px; bottom: 0; left: 0; width: 100px; background-color: #d4311a; } */ /*************************** flex原理 *******************************/ html, body { margin: 0; padding: 0; height: 100%; } .wrap { display:flex; flex-direction: column; width: 100px; height: 100%; } .a { height: 100px; background-color: #0b8bd4; } .b { flex:1; background-color: #d4311a; } </style> </head> <body> <!-- <div> 有一个高度自适应的div,里面有两个div,一个高度100px,希望另一个填满剩下的高度。 </div> --> <div class="wrap"> <div class="a"></div> <div class="b"></div> </div> </body> </html>
const request = require('supertest') const app = require('../app') const URL_ACTORS = '/actors' const actor = { firstName: "ronald", lastName: "reagan", nationality: "UES", image: "https://es.wikipedia.org/wiki/Ronald_Reagan#/media/Archivo:Official_Portrait_of_President_Reagan_1981.jpg", birthday:"19500924" } let actorId; test("Post -> 'URL_ACTORS', should return to be status code 201 and res.body to be defined and res.body.name = actor.name", async() => { const res = await request(app) .post(URL_ACTORS) .send(actor) actorId = res.body.id expect(res.statusCode).toBe(201) expect(res.body).toBeDefined() expect(res.body.firstName).toBe(actor.firstName) }) test("GetAll -> 'URL_ACTORS', should to be status code 200 and res.body to be defined and res.body.length = 1", async() => { const res = await request(app) .get(URL_ACTORS) expect(res.statusCode).toBe(200) expect(res.body).toBeDefined() expect(res.body).toHaveLength(1) }) test("GetOne -> 'URL_ACTORS', should to be status code 200 and res.body to be defined and res.body.name = actor.name", async() => { const res = await request(app) .get(`${URL_ACTORS}/${actorId}`) expect(res.statusCode).toBe(200) expect(res.body).toBeDefined() expect(res.body.firstName).toBe(actor.firstName) }) test("Put -> 'URL_ACTORS/:id', should return status code 200, res.body to be defined and res.body.name = 'rayoMacken' ", async() => { const res = await request(app) .put(`${URL_ACTORS}/${actorId}`) .send({ firstName: 'rayoMacken'}) //console.log(res.body) expect(res.statusCode).toBe(200) expect(res.body).toBeDefined() expect(res.body.firstName).toBe('rayoMacken') }) test("Delete -> 'URL_ACTORS/:id', should return status code 204", async() => { const res = await request(app) .delete(`${URL_ACTORS}/${actorId}`) expect(res.statusCode).toBe(204) })
const ApiError = require('../error/ApiErrors'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { User } = require('../models/models'); const generateJwt = (last_name, id, email) => { return jwt.sign( { last_name: last_name, id: id, email: email }, process.env.SECRET_KEY, { expiresIn: '24h' }); } class UserController { async registraion(req, res, next) { const { last_name, email, password } = req.body; if (!last_name || !email || !password) { return next(ApiError.badRequst('Неккоректный email или пароль')); } const candidate = await User.findOne({ where: { email } }); if (candidate) { return next(ApiError.internal('Пользователь с таким email уже существует')); } const hashPassword = await bcrypt.hash(password, 5); const user = await User.create({ last_name, email, password: hashPassword }); const jwt_token = generateJwt(user.last_name, user.id, user.email); return res.json({ jwt_token }); } async login(req, res, next) { const { email, password } = req.body; if (!email || !password) { return next(ApiError.badRequst('Неккоректный email или пароль')); } const user = await User.findOne({ where: { email } }); if (!user) { return next(ApiError.internal("Пользователь с таким логином не найден")) } let comparePassword = bcrypt.compareSync(password, user.password); if (!comparePassword) { return next(ApiError.internal("Указан неверный логин или пароль")); } const token = generateJwt(user.last_name, user.id, user.email); return res.json({ token }); } async check(req, res, next) { const token = generateJwt(req.user.last_name, req.user.id, req.user.email); return res.json({ token }); } async update(req, res, next) { try { const { id, ...updateParams } = req.body; const updatedObject = await User.update( updateParams, { where: { id: id } } ); if (updatedObject[0] === 0 || !id) { return next(ApiError.badRequst('Объект не найден')); } const token = generateJwt(updateParams.last_name, id, updateParams.email); return res.json({ token }); } catch (error) { console.error('Error updating object:', error); return next(ApiError.internal('Объект не найден')); } } async getOne(req, res) { const { id } = req.params; const apartment = await User.findOne({ where: { id }, } ); return res.json(apartment); } } module.exports = new UserController();
//normalmente ao mechermos com typescript vamos nos deparar com uma pasta "public" e uma pasta "src" //para a pasta public vai o html e o javascript , para a pasta src vai o codigo typescript. //para GERAR o codigo JAVASCRIPT do codigo TYPESCRIPT, damos o comando no terminal assim "tsc o nome da pasta e o nome do arquivo e o comando --outDir no final.. ficando assim : // tsc src/3_script.ts --outDir public //agora vamos corrigir alguns erros, no caso o typescript está avisando no arquivo 3_script que o n1,n2 podem ocasionar erros. //entao VAMOS no n1 colocamos dois pontos ":" e o type que queremos para esse parâmetro. // (n1 : number, n2 : number) //no nosso caso, eu ja formatei esse elemento com o parseint. mas se caso ele nao estivesse formatado poderiamos colocar o "+" antes da variavel numero1.value ficando +numero1.value. //agora temos o ultimo para resolver, no res. // e forma padrao, esse valor deveria ser uma string, porém nao está como string, entao nós podemos resolver adicionando pontotoString(), ficando assim //res.innerHTML = calcular(numero1.value , numero2.value).toString(); //e para testar precisamos sempre converte-lo.
# Task Reverse order of elements in array ## I => O ``` [1] => [1] [1, 2] => [2, 1] [1, 2, 3] => [3, 2, 1] [1, 2, 3, 4] => [4, 3, 2, 1] ``` ### Real life approach Assuming elements in array are pieces of paper arranged in a line from left to right 1. Swap leftmost piece with rightmost piece 2. Swap second leftmost piece with rightmost piece 3. Repeat until all pieces are swapped or 1. Move the piece on the right to a new line 2. Move the piece on the right of the old line to the right of the piece on the new line 3. Continue until all pieces on the old line are in the new one
#pragma once #include <string> using namespace std; class videoGame { private: string gameName; double gameCost; int itemNum; int stock; public: videoGame(); videoGame(string n, double cost, int num, int snum); //setters void setName(string n) { gameName = n; } void setCost(double cost) { gameCost = cost; } void setItemNum(int num) { itemNum = num; } void setStock(int snum) { stock = snum; } //getters string getName() { return gameName; } double getCost() { return gameCost; } int getItemNum() { return itemNum; } int getStock() { return stock; } };
let myLibrary = []; let newBookButton = document.querySelector(".new-button"); let dialog = document.querySelector("dialog"); let closeDialog = document.querySelector(".close-dialog"); let form = document.querySelector("form"); let title = document.querySelector("#title"); let author = document.querySelector("#author"); let pages = document.querySelector("#pages"); let read = document.querySelector("#read"); let table = document.querySelector(".table-container"); function Book(title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; this.info = function() { return `${this.title} by ${this.author}, ${this.pages}, ${this.read}`; } } function addBookToLibrary(title, author, pages, read) { let book = new Book(title, author, pages, read); myLibrary.push(book); } function displayBooks(library) { for (let i = 0; i < library.length; i++) { console.log(library[i].info); } } newBookButton.addEventListener("click", () => { dialog.showModal(); }); form.addEventListener("submit", (event) => { event.preventDefault(); addBookToLibrary(title.value, author.value, pages.value, read.value); dialog.close(); table.innerHTML = generateTable(myLibrary); }) function generateTable(library) { let table = "<table>"; let i = 0; library.forEach(book => { table += `<tr class="${i}"><td>${book.title}</td><td>${book.author}</td><td>${book.pages}</td><td><button onclick="toggleRead(this)" class="read">${book.read}</button></td><td><button onclick="deleteBook(this)">Delete Book</button></td></tr>`; i++; }); table += "</table>"; return table; } function toggleRead(book) { if (book.innerHTML === "Read") { book.innerHTML = "Not Read"; } else { book.innerHTML = "Read"; } let row = book.parentNode.parentNode; myLibrary[row.className].read = book.innerHTML; } function deleteBook(book) { let row = book.parentNode.parentNode; myLibrary.splice(row.className, 1); table.innerHTML = generateTable(myLibrary); }
#ifndef __ILIGHTNODE_H_INCLUDE__ #define __ILIGHTNODE_H_INCLUDE__ #include "ISceneNode.h" #include "ISceneManager.h" enum E_LIGHT_TYPE { ELT_POINT, ELT_DIRECTIONAL, ELT_SPOT }; /* D3DLIGHTTYPE Type; D3DCOLORVALUE Diffuse; D3DCOLORVALUE Specular; D3DCOLORVALUE Ambient; D3DVECTOR Position; D3DVECTOR Direction; float Range; float Falloff; float Attenuation0; float Attenuation1; float Attenuation2; float Theta; float Phi; */ struct SLightData { XMFLOAT4 Diffuse; XMFLOAT4 Specular; XMFLOAT4 Ambient; XMFLOAT3 Position; f32 Range; XMFLOAT3 Direction; f32 Falloff; XMFLOAT3 Attenuations; f32 Theta; }; class ILightNode : public ISceneNode { public: ILightNode(ISceneNode* parent, ISceneManager* smgr, const XMFLOAT3& position = XMFLOAT3(0, 0, 0)) :ISceneNode(parent, smgr, position, XMFLOAT3(0, 0, 0), XMFLOAT3(1.0f, 1.0f, 1.0f)) { } virtual void setId(u32 id) = 0; virtual u32 getId() const = 0; virtual void setType(E_LIGHT_TYPE type) = 0; virtual E_LIGHT_TYPE getType() const = 0; virtual void setLightData(const SLightData& lightData) = 0; virtual const SLightData& getLightData() const = 0; virtual void setDiffuse(const XMFLOAT4& diffuse) = 0; virtual XMFLOAT4 getDiffuse() const = 0; virtual void setSpecular(const XMFLOAT4& specular) = 0; virtual XMFLOAT4 getSpecular() const = 0; virtual void setAmbient(const XMFLOAT4& ambient) = 0; virtual XMFLOAT4 getAmbient() const = 0; virtual void setAttenuation(f32 a0, f32 a1, f32 a2) = 0; virtual XMFLOAT3 getAttenuation() const = 0; virtual void setDirection(const XMFLOAT3& direction) = 0; virtual XMFLOAT3 getDirection() const = 0; virtual void setRange(f32 range) = 0; virtual f32 getRange() const = 0; virtual void setFalloff(f32 falloff) = 0; virtual f32 getFalloff() const = 0; virtual void setTheta(f32 theta) = 0; virtual f32 getTheta() const = 0; }; #endif
import { render, screen } from "@testing-library/react" import UserEvent from "@testing-library/user-event" import PwaEnabler from "." import { setServiceNavigator, spyAsIPad, spyAsAndroid, spyOnReferrer, } from "../../../__mocks__/windowMock" describe("PwaEnabler", () => { const renderComponent = (onCancel = jest.fn()) => render(<PwaEnabler onCancel={onCancel} />) it("should render correctly with PWA disabled", () => { renderComponent() expect(screen.getByText("Progressive Web App")).toBeInTheDocument() expect(screen.getByText("Disabled")).toBeInTheDocument() }) it("should render correctly with PWA disabled", async () => { const closeFn = jest.fn() renderComponent(closeFn) await UserEvent.click(screen.getByText("[ESC]")) expect(closeFn).toHaveBeenCalled() }) describe("TWA enabled", () => { it("should inform if app is TWA enabled", () => { spyOnReferrer("android-app://com.walcron.web") renderComponent() expect( screen.getByText("Trusted Web Application is detected, pwa is ENABLED.") ) }) }) describe("With Service Navigator", () => { //Note setServiceNavigator must ran last as once setup it affects entire test suite. beforeAll(() => { setServiceNavigator() }) it("should render correctly with PWA enabled once loaded when installed", async () => { renderComponent() expect(screen.getByText("Progressive Web App")).toBeInTheDocument() expect(screen.getByText("Disabled")).toBeInTheDocument() expect(await screen.findByText("Installed")).toBeInTheDocument() }) it("should be able to toggle PWA to disabled when service is installed", async () => { renderComponent() expect(await screen.findByText("Installed")).toBeInTheDocument() await UserEvent.click(screen.getByText("Installed")) expect(await screen.findByText("Processing")).toBeInTheDocument() expect( await screen.findByText("Disabled", undefined, { timeout: 2000, interval: 500, }) ).toBeInTheDocument() await UserEvent.click(screen.getByText("Disabled")) expect(await screen.findByText("Processing")).toBeInTheDocument() expect( await screen.findByText("Installed", undefined, { timeout: 2000, interval: 500, }) ).toBeInTheDocument() }) it("should show special message for safari users when installed", async () => { spyAsIPad() renderComponent() expect(await screen.findByText("Installed")).toBeInTheDocument() expect( screen.getByText("For Safari mobile users, follow these steps.") ).toBeInTheDocument() }) it("should show a button for android download for android users when installed", async () => { spyAsAndroid() renderComponent() expect(await screen.findByText("Installed")).toBeInTheDocument() expect(screen.getByText("Playstore Download")).toBeInTheDocument() }) }) })
import { Notify } from 'notiflix/build/notiflix-notify-aio'; const form = document.querySelector('form.form'); const options = { position: 'center-bottom', distance: '15px', borderRadius: '15px', timeout: 10000, clickToClose: true, cssAnimationStyle: 'from-right', }; form.addEventListener('submit', onSubmitForm); function onSubmitForm(e) { e.preventDefault(); let delay = Number(e.currentTarget.delay.value); const step = Number(e.currentTarget.step.value); const amount = Number(e.currentTarget.amount.value); for (let position = 1; position <= amount; position += 1) { createPromise(position, delay) .then(({ position, delay }) => { setTimeout(() => { Notify.success(`✅ Fulfilled promise ${position} in ${delay}ms`, options); }, delay); }) .catch(({ position, delay }) => { setTimeout(() => { Notify.failure(`❌ Rejected promise ${position} in ${delay}ms`, options); }, delay); }); delay += step; } } function createPromise(position, delay) { const shouldResolve = Math.random() > 0.3; const objectPromise = { position, delay }; return new Promise((resolve, reject) => { if (shouldResolve) { resolve(objectPromise); } reject(objectPromise); }); }
package com.atguigu.gmall0401.cart.service.impl; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.fastjson.JSON; import com.atguigu.gmall0401.bean.CartInfo; import com.atguigu.gmall0401.bean.SkuInfo; import com.atguigu.gmall0401.cart.mapper.CartInfoMapper; import com.atguigu.gmall0401.service.CartService; import com.atguigu.gmall0401.service.ManageService; import com.atguigu.gmall0401.util.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; import redis.clients.jedis.Jedis; import java.util.*; @Service public class CartServiceImpl implements CartService { @Autowired RedisUtil redisUtil; @Autowired CartInfoMapper cartInfoMapper; @Reference ManageService manageService;//远程调用,查信息-查价格 @Override public CartInfo addCart(String userId, String skuId, Integer num) { // 为了防止 更新购物车前 缓存过期 loadCartCacheIfNotExists( userId) ; // 加数据库 // 尝试取出已有的数据 如果有 把数量更新 update 如果没有insert CartInfo cartInfoQuery=new CartInfo(); cartInfoQuery.setSkuId(skuId); cartInfoQuery.setUserId(userId); CartInfo cartInfoExists=null; cartInfoExists = cartInfoMapper.selectOne(cartInfoQuery); SkuInfo skuInfo = manageService.getSkuInfo(skuId);//利用manageService查sku信息 if(cartInfoExists!=null){ cartInfoExists.setSkuName(skuInfo.getSkuName());//设置最新名称 cartInfoExists.setCartPrice(skuInfo.getPrice());//设置最新的价格 cartInfoExists.setSkuNum(cartInfoExists.getSkuNum()+num);//设置最新数量=传过来的数量+新增数量 cartInfoExists.setImgUrl(skuInfo.getSkuDefaultImg());//设置图片 cartInfoMapper.updateByPrimaryKeySelective(cartInfoExists);//selective可以不加 } //没查到加入的物品 else{ CartInfo cartInfo = new CartInfo(); cartInfo.setSkuId(skuId); cartInfo.setUserId(userId); cartInfo.setSkuNum(num); cartInfo.setImgUrl(skuInfo.getSkuDefaultImg()); cartInfo.setSkuName(skuInfo.getSkuName()); cartInfo.setCartPrice(skuInfo.getPrice()); cartInfo.setSkuPrice(skuInfo.getPrice()); cartInfoMapper.insertSelective(cartInfo); cartInfoExists=cartInfo; } loadCartCache(userId); return cartInfoExists; } @Override public List<CartInfo> cartList(String userId) { /*先查缓存 type: stringiest,zset,list,hash 选择: 购物车:1一对多关系 2可以改其中一个对象,某一条购物车信息修改 用string:怎么改某一条购物信息:json串反序列回来,改值,再改成json串 结果:性能不好 set,zset,list:都可以散着存。问题:不能直接找到需要改的值 用hash 原因:外面有大key,里面有小key,修改效率好 把key变成userid+skuid, value放购物车信息 问题:key太多 Key: cart:101:info Field skid Value cartInfoJson 如果购物车中已有该sku,增加个数,如果没有新增一条 */ Jedis jedis = redisUtil.getJedis(); String cartKey="cart:"+userId+":info"; //key: cart:101:info /* hgetALL: skuid -1:n-cartinfo, 但是不需要skuid hash: key -1:n-field+value,只需要value. 使用jedis.hvals */ //得到Json串 List<String> cartJsonList = jedis.hvals(cartKey); List<CartInfo> cartList=new ArrayList<>(); //将Json串变成具体的object if(cartJsonList!=null&&cartJsonList.size()>0){ //缓存命中 for (String cartJson : cartJsonList) { CartInfo cartInfo = JSON.parseObject(cartJson, CartInfo.class); cartList.add(cartInfo); } /* 购物车有顺序,新买的放在上面 怎么判断时间——id号越大,越新——id号大的放在上面 */ cartList.sort(new Comparator<CartInfo>() { @Override public int compare(CartInfo o1, CartInfo o2) { return o2.getId().compareTo(o1.getId()); } }); return cartList; }else { //缓存未命中 //缓存没有查数据库 ,同时加载到缓存中 return loadCartCache(userId); } } /** * 合并购物车 * @param userIdDest * @param userIdOrig * @return */ @Override public List<CartInfo> mergeCartList(String userIdDest, String userIdOrig) { //1 先做合并 cartInfoMapper.mergeCartList(userIdDest,userIdOrig); // 2 合并后把临时购物车删除 CartInfo cartInfo = new CartInfo(); cartInfo.setUserId(userIdOrig);//userIdOrig临时的id cartInfoMapper.delete(cartInfo);///删除的是第二个购物车,临时的 Jedis jedis = redisUtil.getJedis(); jedis.del("cart:"+userIdOrig+":info"); jedis.close(); // 3 重新读取数据 加载缓存 List<CartInfo> cartInfoList = loadCartCache(userIdDest); return cartInfoList; } /** * 缓存没有查数据库 ,同时加载到缓存中 * @param userId * @return */ public List<CartInfo> loadCartCache(String userId){ // 读取数据库 List<CartInfo> cartInfoList = cartInfoMapper.selectCartListWithSkuPrice(userId); /* 加载到缓存中 为了方便插入redis 把list --> map 把skuinfo 和cartinfo关联,需要join操作 建立大sql */ if(cartInfoList!=null&&cartInfoList.size()>0) { Map<String, String> cartMap = new HashMap<>(); for (CartInfo cartInfo : cartInfoList) { cartMap.put(cartInfo.getSkuId(), JSON.toJSONString(cartInfo)); } Jedis jedis = redisUtil.getJedis(); String cartKey = "cart:" + userId + ":info"; jedis.del(cartKey); jedis.hmset(cartKey, cartMap); // hash jedis.expire(cartKey, 60 * 60 * 24);//过期时间 jedis.close(); } return cartInfoList; } public void loadCartCacheIfNotExists(String userId){ String cartkey="cart:"+userId+":info"; Jedis jedis = redisUtil.getJedis(); Long ttl = jedis.ttl(cartkey); int ttlInt = ttl.intValue(); jedis.expire(cartkey,ttlInt+10); Boolean exists = jedis.exists(cartkey); jedis.close(); if( !exists){ loadCartCache( userId); } } @Override public void checkCart(String userId, String skuId, String isChecked) { loadCartCacheIfNotExists(userId);// 检查一下缓存是否存在 避免因为缓存失效造成 缓存和数据库不一致 /* isCheck 数据位置: key-field(skuid)-value(属于json串)组成:字段isCheck 改isCheck步骤 找到Json串——反序成对象——改对象的值——序列化——写回Json串 isCheck数据 值保存在缓存中 先取缓存 cartkey:来自loadCartCache 得到jedis */ //保存标志 String cartKey = "cart:" + userId + ":info"; Jedis jedis = redisUtil.getJedis(); //得到一条数据的json串 String cartInfoJson = jedis.hget(cartKey, skuId); //反序成对象 CartInfo cartInfo = JSON.parseObject(cartInfoJson, CartInfo.class); //改ischecked值 cartInfo.setIsChecked(isChecked); //序列化 String cartInfoJsonNew = JSON.toJSONString(cartInfo); //写回Json jedis.hset(cartKey,skuId,cartInfoJsonNew); // 为了订单结账 把所有勾中的商品单独 在存放到一个checked购物车中 String cartCheckedKey = "cart:" + userId + ":checked"; if(isChecked.equals("1")){ //勾中加入到待结账购物车中, 取消勾中从待结账购物车中删除 jedis.hset(cartCheckedKey,skuId,cartInfoJsonNew); jedis.expire(cartCheckedKey,60*60); }else{ jedis.hdel(cartCheckedKey,skuId); } jedis.close(); } @Override public List<CartInfo> getCheckedCartList(String userId) { /* 读Hash 结构:key -1:n-field 1:1 value 读取value列表:hvals */ String cartCheckedKey = "cart:" + userId + ":checked"; Jedis jedis = redisUtil.getJedis(); List<String> checkedCartList = jedis.hvals(cartCheckedKey); List<CartInfo> cartInfoList=new ArrayList<>(); for (String cartInfoJson : checkedCartList) { CartInfo cartInfo = JSON.parseObject(cartInfoJson, CartInfo.class); cartInfoList.add(cartInfo); } jedis.close(); return cartInfoList; } }
package com.paradise.hellth.data.repository import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ValueEventListener import com.paradise.hellth.util.model.HealthRecord import com.paradise.hellth.util.model.RunningRecord import com.paradise.hellth.data.source.remote.FireBaseDatabase.HealthDB import com.paradise.hellth.data.source.remote.FireBaseDatabase.RunningDB import com.paradise.hellth.data.source.remote.FireBaseDatabase.WorkoutDB import com.paradise.hellth.data.source.remote.FireBaseDatabase.userDatabase import com.paradise.hellth.data.NetworkResult import com.prolificinteractive.materialcalendarview.CalendarDay import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await class RecordRepository { // 모든 무산소 운동 정보 가져오기 fun getALLHealthData(): Flow<NetworkResult<ArrayList<HealthRecord>>> { return callbackFlow { trySend(NetworkResult.Loading()) val listener = HealthDB.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data = ArrayList<HealthRecord>() for (i in dataSnapshot.children) { for (j in i.children) { data.add(j.getValue(HealthRecord::class.java)!!) } } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message)) cancel() } }) awaitClose { HealthDB.removeEventListener(listener) } } } // 모든 무산소 운동 날짜 정보 가져오기 fun getHealthScheduleData(): Flow<NetworkResult<ArrayList<CalendarDay>>> { return callbackFlow { trySend(NetworkResult.Loading()) // Add a listener to the user node val listener = HealthDB.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val days = ArrayList<CalendarDay>() for (i in dataSnapshot.children) { val year = i.key!!.substring(0, 4).toInt() val month = i.key!!.substring(4, 6).toInt() val day = i.key!!.substring(6).toInt() days.add(CalendarDay.from(year, month, day)) } trySend(NetworkResult.Success(days)) } override fun onCancelled(error: DatabaseError) { // Cancel the flow on error trySend(NetworkResult.Error(error.message)) cancel() } }) // Return the listener to be used to cancel the flow awaitClose { HealthDB.removeEventListener(listener) } } } fun getDayHealthData(day: String): Flow<NetworkResult<ArrayList<Pair<String, HealthRecord>>>> { return callbackFlow { trySend(NetworkResult.Loading()) HealthDB.child(day).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var data = ArrayList<Pair<String, HealthRecord>>() if (snapshot.exists()) { for (i in snapshot.children) { data.add(Pair(i.key!!, i.getValue(HealthRecord::class.java)!!)) } } else { data = emptyArray<Pair<String, HealthRecord>>().toCollection(ArrayList()) } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message)) cancel() } }) awaitClose {} } } // 무산소 운동 특정 날짜에 정보 넣기 fun setHealthDataResult(day: String, data: HealthRecord): Flow<NetworkResult<Boolean>> { return callbackFlow { trySend(NetworkResult.Loading()) HealthDB.child(day).push().setValue(data).addOnCompleteListener { trySend(NetworkResult.Success(true)) }.addOnFailureListener { trySend(NetworkResult.Error(it.message.toString())) } awaitClose {} } } // 무산소 운동 특정 날짜에 정보 넣기 fun removeHealthDataResult(day: String, key: String): Flow<NetworkResult<Boolean>> { return callbackFlow { trySend(NetworkResult.Loading()) HealthDB.child(day).child(key).removeValue().addOnCompleteListener { trySend(NetworkResult.Success(true)) }.addOnFailureListener { trySend(NetworkResult.Error(it.message.toString())) } awaitClose {} } } fun getDayRunningData(day: String): Flow<NetworkResult<ArrayList<Pair<String, RunningRecord>>>> { return callbackFlow { trySend(NetworkResult.Loading()) RunningDB.child(day).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val data = ArrayList<Pair<String, RunningRecord>>() for (i in snapshot.children) { data.add(Pair(i.key!!, i.getValue(RunningRecord::class.java)!!)) } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) awaitClose { } } } fun getRunningScheduleData(): Flow<NetworkResult<ArrayList<CalendarDay>>> { return callbackFlow { trySend(NetworkResult.Loading()) // Add a listener to the user node val listener = RunningDB.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val days = ArrayList<CalendarDay>() for (i in dataSnapshot.children) { val year = i.key!!.substring(0, 4).toInt() val month = i.key!!.substring(4, 6).toInt() val day = i.key!!.substring(6).toInt() days.add(CalendarDay.from(year, month, day)) } trySend(NetworkResult.Success(days)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) // Return the listener to be used to cancel the flow awaitClose { RunningDB.removeEventListener(listener) } } } fun getALLRunningData(): Flow<NetworkResult<ArrayList<RunningRecord>>> { return callbackFlow { trySend(NetworkResult.Loading()) // Add a listener to the user node val listener = RunningDB.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data = ArrayList<RunningRecord>() for (i in dataSnapshot.children) { for (j in i.children) { data.add(j.getValue(RunningRecord::class.java)!!) } } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) // Return the listener to be used to cancel the flow awaitClose { RunningDB.removeEventListener(listener) } } } fun getALLRunningReferenceData(): Flow<NetworkResult<ArrayList<RunningRecord>>> { return callbackFlow { trySend(NetworkResult.Loading()) // Add a listener to the user node RunningDB.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data = ArrayList<RunningRecord>() for (i in dataSnapshot.children) { for (j in i.children) { val temp = j.getValue(RunningRecord::class.java) as RunningRecord if (temp.reference != null && temp.reference!!.isNotEmpty()) data.add( temp ) } } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) // Return the listener to be used to cancel the flow awaitClose { } } } suspend fun setRunningDataResult(day: String, data: RunningRecord): String { val values = mutableMapOf<String, Any>() val key = RunningDB.child(day).push().key // push() 메서드로 고유한 식별자를 생성하고, key 변수에 저장 values["/running/$day/$key"] = data // healthData는 입력할 데이터 객체 values["/workout/$day/runningKey"] = true try { // await() 함수로 Task 객체를 suspend 함수로 변환 userDatabase.updateChildren(values).await() // 작업이 성공하면 성공 메시지 출력 return ("Data updated successfully") } catch (e: Exception) { // 작업이 실패하면 예외를 잡아서 오류 메시지 출력 return ("Data update failed: ${e.message}") } } fun removeRunningDataResult(day: String, key: String): Flow<NetworkResult<Boolean>> { return callbackFlow { trySend(NetworkResult.Loading()) RunningDB.child(day).child(key).removeValue().addOnCompleteListener { trySend(NetworkResult.Success(true)) }.addOnFailureListener { trySend(NetworkResult.Error(it.message.toString())) } awaitClose {} } } fun getALLWorkoutData(): Flow<NetworkResult<List<Triple<CalendarDay, Boolean?, Boolean?>>>> { return callbackFlow { trySend(NetworkResult.Loading()) WorkoutDB.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val workoutList = dataSnapshot.children.mapNotNull { val year = it.key!!.substring(0, 4).toInt() val month = it.key!!.substring(4, 6).toInt() val day = it.key!!.substring(6).toInt() Triple( CalendarDay.from(year, month, day), it.child("runningKey").getValue(Boolean::class.java), it.child("healthKey").getValue(Boolean::class.java) ) } trySend(NetworkResult.Success(workoutList)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) awaitClose { } } } fun getDayWorkoutData(day: String): Flow<NetworkResult<ArrayList<Boolean?>>> { return callbackFlow { trySend(NetworkResult.Loading()) WorkoutDB.child(day).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val data = ArrayList<Boolean?>() for (i in snapshot.children) { data.add(i.getValue(Boolean::class.java)) } trySend(NetworkResult.Success(data)) } override fun onCancelled(error: DatabaseError) { trySend(NetworkResult.Error(error.message.toString())) cancel() } }) awaitClose { } } } // 모든 무산소 운동 정보 가져오기 fun updateWorkoutDataInHealth() { HealthDB.addChildEventListener(object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) { WorkoutDB.child(dataSnapshot.key.toString()).child("healthKey").setValue(true) } override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) { } override fun onChildRemoved(dataSnapshot: DataSnapshot) { WorkoutDB.child(dataSnapshot.key.toString()).child("healthKey").setValue(false) } override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {} override fun onCancelled(error: DatabaseError) { } }) } fun updateWorkoutDataInRunning() { RunningDB.addChildEventListener(object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) { WorkoutDB.child(dataSnapshot.key.toString()).child("runningKey").setValue(true) } override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) { } override fun onChildRemoved(dataSnapshot: DataSnapshot) { WorkoutDB.child(dataSnapshot.key.toString()).child("runningKey").setValue(false) } override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {} override fun onCancelled(error: DatabaseError) { } }) } }
// Copyright (C) 2023 Light, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use ethers::{ types::{Address, H256}, utils::hex, }; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; use serde_with::serde_as; use std::convert::TryFrom; #[derive(Clone, PartialEq)] pub struct Signature(pub Vec<u8>); /// The struct representation of a wallet signer /// Derived from: https://github.com/0xsequence/go-sequence/blob/eabca0c348b5d87dd943a551908c80f61c347899/config.go#L17 /// License: Apache-2.0 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Signer { #[serde(skip_serializing_if = "Option::is_none")] pub weight: Option<u8>, pub leaf: SignatureLeaf, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct SignerNode { #[serde(skip_serializing_if = "Option::is_none")] pub signer: Option<Signer>, #[serde(skip_serializing_if = "Option::is_none")] pub left: Option<Box<SignerNode>>, #[serde(skip_serializing_if = "Option::is_none")] pub right: Option<Box<SignerNode>>, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(tag = "type", content = "content")] pub enum SignatureLeaf { ECDSASignature(ECDSASignatureLeaf), AddressSignature(AddressSignatureLeaf), DynamicSignature(DynamicSignatureLeaf), NodeSignature(NodeLeaf), BranchSignature(BranchLeaf), SubdigestSignature(SubdigestLeaf), NestedSignature(NestedLeaf), } /// The enum representation of a signature leaf type /// Derived from: https://github.com/0xsequence/wallet-contracts/blob/e0c5382636a88b4db4bcf0a70623355d7cd30fb4/contracts/modules/commons/submodules/auth/SequenceBaseSig.sol#L102 /// License: Apache-2.0 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[repr(u8)] pub enum SignatureLeafType { ECDSASignature = 0, Address = 1, DynamicSignature = 2, Node = 3, Branch = 4, Subdigest = 5, Nested = 6, } /// The struct representation of an ECDSA signature leaf type /// Derived from: https://github.com/0xsequence/wallet-contracts/blob/e0c5382636a88b4db4bcf0a70623355d7cd30fb4/contracts/utils/SignatureValidator.sol#L83 /// License: Apache-2.0 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[repr(u8)] pub enum ECDSASignatureType { ECDSASignatureTypeEIP712 = 1, ECDSASignatureTypeEthSign = 2, } /// The constant length of an ECDSA signature /// The actual length of the signature is 65 bytes /// Internally, the original length is + 1 byte for the signature type pub const ECDSA_SIGNATURE_LENGTH: usize = 65; pub const ERC1271_MAGICVALUE_BYTES32: [u8; 4] = [22, 38, 186, 126]; #[derive(Clone, PartialEq)] pub struct ECDSASignature(pub [u8; ECDSA_SIGNATURE_LENGTH]); #[serde_as] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct ECDSASignatureLeaf { pub address: Address, pub signature_type: ECDSASignatureType, pub signature: ECDSASignature, } impl From<&ECDSASignatureLeaf> for Vec<u8> { fn from(item: &ECDSASignatureLeaf) -> Self { // Concatenate the signature and signature type let mut signature = item.clone().signature.0.to_vec(); // Insert type at end signature.push(item.clone().signature_type as u8); signature } } #[serde_as] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AddressSignatureLeaf { pub address: Address, } impl From<&AddressSignatureLeaf> for Vec<u8> { fn from(item: &AddressSignatureLeaf) -> Self { item.clone().address.0.to_vec() } } /// The struct representation of a Dynamic signature leaf type #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[repr(u8)] pub enum DynamicSignatureType { DynamicSignatureTypeEIP712 = 1, DynamicSignatureTypeEthSign = 2, DynamicSignatureTypeEIP1271 = 3, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct DynamicSignatureLeaf { pub address: Address, pub signature_type: DynamicSignatureType, pub signature: Signature, pub size: u32, } impl From<&DynamicSignatureLeaf> for Vec<u8> { fn from(item: &DynamicSignatureLeaf) -> Self { // Push the address let mut signature = item.clone().address.0.to_vec(); // Push the size (Vec<u8>) to the end of the signature // Not that the size is a solidity uint24, but we use u32 here, so we need to truncate // the first byte let mut size = item.clone().size.to_be_bytes().to_vec(); size.remove(0); signature.extend_from_slice(&size); // Concatenate the signature and signature type signature.extend_from_slice(&item.clone().signature.0.to_vec()); // Insert type at end signature.push(item.clone().signature_type as u8); signature } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct NodeLeaf { pub hash: H256, } impl From<&NodeLeaf> for Vec<u8> { fn from(item: &NodeLeaf) -> Self { item.clone().hash.0.to_vec() } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct BranchLeaf { pub size: u32, } impl From<&BranchLeaf> for Vec<u8> { fn from(item: &BranchLeaf) -> Self { // Push the size (Vec<u8>) to the end of the signature // Not that the size is a solidity uint24, but we use u32 here, so we need to truncate // the first byte let mut size = item.clone().size.to_be_bytes().to_vec(); size.remove(0); size } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct SubdigestLeaf { pub hash: H256, } impl From<&SubdigestLeaf> for Vec<u8> { fn from(item: &SubdigestLeaf) -> Self { item.clone().hash.0.to_vec() } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct NestedLeaf { pub internal_threshold: u16, pub external_weight: u8, pub internal_root: H256, pub size: u32, } impl From<&NestedLeaf> for Vec<u8> { fn from(item: &NestedLeaf) -> Self { // Concatenate the signature and signature type let mut signature = vec![item.clone().external_weight]; // Push the internal threshold (Vec<u8>) to the end of the signature signature.extend_from_slice(&item.clone().internal_threshold.to_be_bytes()); // Push the size (Vec<u8>) to the end of the signature // Not that the size is a solidity uint24, but we use u32 here, so we need to truncate // the first byte let mut size = item.clone().size.to_be_bytes().to_vec(); size.remove(0); signature.extend_from_slice(&size); signature } } impl Signature { pub fn len(&self) -> usize { let Signature(inner) = self; inner.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn as_slice(&self) -> &[u8] { let Signature(inner) = self; inner.as_slice() } } impl std::fmt::Debug for Signature { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "0x{}", hex::encode(self.as_slice())) } } impl From<Vec<u8>> for Signature { fn from(bytes: Vec<u8>) -> Self { Signature(bytes) } } impl std::fmt::Debug for ECDSASignature { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "0x{}", hex::encode(self.0)) } } impl From<[u8; ECDSA_SIGNATURE_LENGTH]> for ECDSASignature { fn from(item: [u8; ECDSA_SIGNATURE_LENGTH]) -> Self { ECDSASignature(item) } } impl TryFrom<Vec<u8>> for ECDSASignature { type Error = &'static str; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { if bytes.len() != ECDSA_SIGNATURE_LENGTH { return Err("Invalid length for ECDSASignature"); } let mut array = [0u8; ECDSA_SIGNATURE_LENGTH]; for (place, element) in array.iter_mut().zip(bytes.iter()) { *place = *element; } Ok(ECDSASignature(array)) } } impl Serialize for ECDSASignature { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let hex_string = format!("0x{}", hex::encode(self.0)); serializer.serialize_str(&hex_string) } } struct ECDSASignatureVisitor; impl<'de> Visitor<'de> for ECDSASignatureVisitor { type Value = ECDSASignature; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string starts with 0x followed by 260 hexadecimal characters") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { if !value.starts_with("0x") { return Err(E::custom("Expected string to start with '0x'")); } let bytes = hex::decode(&value[2..]).map_err(de::Error::custom)?; if bytes.len() != ECDSA_SIGNATURE_LENGTH { return Err(E::custom("Expected 65 bytes")); } let mut array = [0u8; ECDSA_SIGNATURE_LENGTH]; array.copy_from_slice(&bytes); Ok(ECDSASignature(array)) } } impl<'de> Deserialize<'de> for ECDSASignature { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_str(ECDSASignatureVisitor) } } struct SignatureVisitor; impl<'de> Visitor<'de> for SignatureVisitor { type Value = Signature; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string starts with 0x followed by hexadecimal characters") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { if !value.starts_with("0x") { return Err(E::custom("Expected string to start with '0x'")); } let bytes = hex::decode(&value[2..]).map_err(de::Error::custom)?; Ok(Signature(bytes)) } } impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_str(SignatureVisitor) } } impl Serialize for Signature { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let hex_string = format!("0x{}", hex::encode(self.0.as_slice())); serializer.serialize_str(&hex_string) } }
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; interface CustomNextRequest extends NextRequest { user?: any; } // This function can be marked `async` if using `await` inside export async function middleware(request: CustomNextRequest) { const { pathname, origin } = request.nextUrl; // Specify the routes you want the middleware to be applied to const protectedRoutes = ['/dashboard', '/authentication/login', '/authentication/register']; if (pathname.endsWith('/')) { return NextResponse.redirect(`${origin}/dashboard`); } if (!protectedRoutes.includes(pathname)) { return NextResponse.next(); } try { const token = request.cookies.get('authToken')?.value; const res = await fetch(`${origin}/api/verifyToken/${token}`); if (res.status == 401 && pathname !== '/authentication/login' && pathname !== '/authentication/register') { return NextResponse.redirect(`${origin}/authentication/login`); } // Redirect to dashboard if authenticated but on login or register page if (res.status == 200 && (pathname === '/authentication/login' || pathname === '/authentication/register')) { return NextResponse.redirect(`${origin}/dashboard`); } return NextResponse.next(); } catch (error) { return NextResponse.redirect(`${origin}/authentication/login`); } }
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/button/image_button.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image_unittest_util.h" #include "ui/views/border.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/views_test_base.h" namespace { class Parent : public views::View { public: Parent() = default; Parent(const Parent&) = delete; Parent& operator=(const Parent&) = delete; void ChildPreferredSizeChanged(views::View* view) override { pref_size_changed_calls_++; } int pref_size_changed_calls() const { return pref_size_changed_calls_; } private: int pref_size_changed_calls_ = 0; }; } // namespace namespace views { using ImageButtonTest = ViewsTestBase; TEST_F(ImageButtonTest, FocusBehavior) { ImageButton button; EXPECT_EQ(PlatformStyle::kDefaultFocusBehavior, button.GetFocusBehavior()); } TEST_F(ImageButtonTest, Basics) { ImageButton button; // Our image to paint starts empty. EXPECT_TRUE(button.GetImageToPaint().isNull()); // Without an image, buttons are 16x14 by default. EXPECT_EQ(gfx::Size(16, 14), button.GetPreferredSize()); // The minimum image size should be applied even when there is no image. button.SetMinimumImageSize(gfx::Size(5, 15)); EXPECT_EQ(gfx::Size(5, 15), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(16, 15), button.GetPreferredSize()); // Set a normal image. gfx::ImageSkia normal_image = gfx::test::CreateImageSkia(10, 20); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(normal_image)); // Image uses normal image for painting. EXPECT_FALSE(button.GetImageToPaint().isNull()); EXPECT_EQ(10, button.GetImageToPaint().width()); EXPECT_EQ(20, button.GetImageToPaint().height()); // Preferred size is the normal button size. EXPECT_EQ(gfx::Size(10, 20), button.GetPreferredSize()); // Set a pushed image. gfx::ImageSkia pushed_image = gfx::test::CreateImageSkia(11, 21); button.SetImageModel(Button::STATE_PRESSED, ui::ImageModel::FromImageSkia(pushed_image)); // By convention, preferred size doesn't change, even though pushed image // is bigger. EXPECT_EQ(gfx::Size(10, 20), button.GetPreferredSize()); // We're still painting the normal image. EXPECT_FALSE(button.GetImageToPaint().isNull()); EXPECT_EQ(10, button.GetImageToPaint().width()); EXPECT_EQ(20, button.GetImageToPaint().height()); // The minimum image size should make the preferred size bigger. button.SetMinimumImageSize(gfx::Size(15, 5)); EXPECT_EQ(gfx::Size(15, 5), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(15, 20), button.GetPreferredSize()); button.SetMinimumImageSize(gfx::Size(15, 25)); EXPECT_EQ(gfx::Size(15, 25), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(15, 25), button.GetPreferredSize()); } TEST_F(ImageButtonTest, SetAndGetImage) { ImageButton button; // Images start as null. EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_HOVERED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); // Setting images works as expected. gfx::ImageSkia image1 = gfx::test::CreateImageSkia(10, 11); gfx::ImageSkia image2 = gfx::test::CreateImageSkia(20, 21); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(image1)); button.SetImageModel(Button::STATE_HOVERED, ui::ImageModel::FromImageSkia(image2)); EXPECT_TRUE( button.GetImage(Button::STATE_NORMAL).BackedBySameObjectAs(image1)); EXPECT_TRUE( button.GetImage(Button::STATE_HOVERED).BackedBySameObjectAs(image2)); EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); // ImageButton supports NULL image pointers. button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel()); EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); } TEST_F(ImageButtonTest, ImagePositionWithBorder) { ImageButton button; gfx::ImageSkia image = gfx::test::CreateImageSkia(20, 30); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(image)); // The image should be painted at the top-left corner. EXPECT_EQ(gfx::Point(), button.ComputeImagePaintPosition(image)); button.SetBorder(views::CreateEmptyBorder(gfx::Insets::TLBR(10, 5, 0, 0))); EXPECT_EQ(gfx::Point(5, 10), button.ComputeImagePaintPosition(image)); button.SetBorder(NullBorder()); button.SetBounds(0, 0, 50, 50); EXPECT_EQ(gfx::Point(), button.ComputeImagePaintPosition(image)); button.SetImageHorizontalAlignment(ImageButton::ALIGN_CENTER); button.SetImageVerticalAlignment(ImageButton::ALIGN_MIDDLE); EXPECT_EQ(gfx::Point(15, 10), button.ComputeImagePaintPosition(image)); button.SetBorder(views::CreateEmptyBorder(gfx::Insets::TLBR(10, 10, 0, 0))); EXPECT_EQ(gfx::Point(20, 15), button.ComputeImagePaintPosition(image)); // The entire button's size should take the border into account. EXPECT_EQ(gfx::Size(30, 40), button.GetPreferredSize()); // The border should be added on top of the minimum image size. button.SetMinimumImageSize(gfx::Size(30, 5)); EXPECT_EQ(gfx::Size(40, 40), button.GetPreferredSize()); } TEST_F(ImageButtonTest, LeftAlignedMirrored) { ImageButton button; gfx::ImageSkia image = gfx::test::CreateImageSkia(20, 30); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(image)); button.SetBounds(0, 0, 50, 30); button.SetImageVerticalAlignment(ImageButton::ALIGN_BOTTOM); button.SetDrawImageMirrored(true); // Because the coordinates are flipped, we should expect this to draw as if // it were ALIGN_RIGHT. EXPECT_EQ(gfx::Point(30, 0), button.ComputeImagePaintPosition(image)); } TEST_F(ImageButtonTest, RightAlignedMirrored) { ImageButton button; gfx::ImageSkia image = gfx::test::CreateImageSkia(20, 30); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(image)); button.SetBounds(0, 0, 50, 30); button.SetImageHorizontalAlignment(ImageButton::ALIGN_RIGHT); button.SetImageVerticalAlignment(ImageButton::ALIGN_BOTTOM); button.SetDrawImageMirrored(true); // Because the coordinates are flipped, we should expect this to draw as if // it were ALIGN_LEFT. EXPECT_EQ(gfx::Point(0, 0), button.ComputeImagePaintPosition(image)); } TEST_F(ImageButtonTest, PreferredSizeInvalidation) { Parent parent; ImageButton button; gfx::ImageSkia first_image = gfx::test::CreateImageSkia(20, 30); gfx::ImageSkia second_image = gfx::test::CreateImageSkia(/*size=*/50); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(first_image)); parent.AddChildView(&button); ASSERT_EQ(0, parent.pref_size_changed_calls()); button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(first_image)); EXPECT_EQ(0, parent.pref_size_changed_calls()); button.SetImageModel(Button::STATE_HOVERED, ui::ImageModel::FromImageSkia(second_image)); EXPECT_EQ(0, parent.pref_size_changed_calls()); // Changing normal state image size leads to a change in preferred size. button.SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(second_image)); EXPECT_EQ(1, parent.pref_size_changed_calls()); } } // namespace views
import { InputLabel } from "@/components/Elements/Texts/InputLabel"; import { yupResolver } from "@hookform/resolvers/yup"; import { SubmitHandler, useForm } from "react-hook-form"; // state import { RadioGroupForm } from "@/components/Elements/Forms/RadioGroupForm"; import { SelectForm } from "@/components/Elements/Forms/SelectForm"; import { TextFieldForm } from "@/components/Elements/Forms/TextFieldForm"; import { HStack, HStackStyler as HItem, } from "@/components/Elements/Layouts/Stack"; import { BuildingYearSelect } from "@/components/Models/Forms/BuildingYearSelectForm"; import { NextNavigaterButton } from "@/components/Models/Navigaters"; import { BuildingStructure, buildingStructureState, buildingYearState, landAreaState, LayoutType, layoutTypeState, livingAreaState, totalFloorState, } from "@/state/propertyState"; import { useRecoilState } from "recoil"; import * as yup from "yup"; type FormInput = { buildingYear: number | null; buildingStructure: BuildingStructure; livingArea: number | null; landArea: number | null; layoutType: LayoutType; locatedFloor: number | null; totalFloor: number | null; }; // バリデーションルール const schema = yup.object({ buildingYear: yup.string().required("必須です"), livingArea: yup.string().required("必須です"), landArea: yup.string().required("必須です"), }); type Props = { next: string; }; export const House: React.FC<Props> = ({ next }) => { // global state const [buildingYear, setBuildingYear] = useRecoilState(buildingYearState); const [buildingStructure, setBuildingStructure] = useRecoilState( buildingStructureState ); const [livingArea, setLivingArea] = useRecoilState(livingAreaState); const [landArea, setLandArea] = useRecoilState(landAreaState); const [layoutType, setLayoutType] = useRecoilState(layoutTypeState); const [totalFloor, setTotalFloor] = useRecoilState(totalFloorState); // react-hook-form const form = useForm<FormInput>({ mode: "onChange", // criteriaMode: "all", defaultValues: { buildingYear: buildingYear, buildingStructure: buildingStructure, livingArea: livingArea, landArea: landArea, layoutType: layoutType, totalFloor: totalFloor, }, resolver: yupResolver(schema), }); const { handleSubmit, formState: { isValid }, } = form; const onSubmit: SubmitHandler<FormInput> = (data) => { setBuildingYear(data.buildingYear); setBuildingStructure(data.buildingStructure); setLivingArea(data.livingArea); setLandArea(data.landArea); setLayoutType(data.layoutType); setTotalFloor(data.totalFloor); }; return ( <> <div> <InputLabel required label="建築年" /> <BuildingYearSelect form={form} name="buildingYear" /> </div> <div> <InputLabel label="建築構造" /> <RadioGroupForm form={form} name="buildingStructure" options={[ { label: "鉄筋系(鉄筋コンクリート)", value: "reinforced_concrete", }, { label: "鉄骨系(軽量鉄骨など)", value: "light_weight_steel", }, { label: "木造", value: "wood" }, { label: "その他", value: "" }, ]} /> </div> <HStack spacing={3}> <HItem> <InputLabel required label="居住面積" /> <TextFieldForm type="number" form={form} name="livingArea" placeholder="50" /> </HItem> <HItem> <InputLabel required label="土地面積" /> <TextFieldForm type="number" form={form} name="landArea" placeholder="100" /> </HItem> </HStack> <HStack spacing={3}> <HItem> <InputLabel label="間取り" /> <SelectForm form={form} name="layoutType" placeholder="未選択" options={[ { label: "未選択", value: "" }, { label: "ワンルーム", value: "ワンルーム" }, { label: "1K", value: "1K" }, { label: "1DK/LDK", value: "1DK/LDK" }, { label: "2K/DK/LDK", value: "2K/DK/LDK" }, { label: "3K/DK/LDK", value: "3K/DK/LDK" }, { label: "4K/DK/LDK", value: "4K/DK/LDK" }, { label: "5K以上", value: "5K以上" }, ]} /> </HItem> <HItem> <InputLabel label="建物の階数" /> <TextFieldForm type="number" form={form} name="totalFloor" placeholder="2" /> </HItem> </HStack> <NextNavigaterButton label="次へ" isValid={isValid} next={next} onClick={handleSubmit(onSubmit)} /> </> ); };
# SMS Spam Detection Project This project focuses on developing a machine learning model to accurately classify SMS messages as spam (unwanted messages) or ham (legitimate messages). The goal is to enhance user experience and security by effectively identifying and filtering out spam. ## Project Overview In this Jupyter Notebook, a model is developed to classify email messages into two categories: - **Legitimate Emails (commonly referred to as 'Ham')**: These are emails that the user has explicitly or implicitly indicated they wish to receive. They include personal communications, business correspondences, and subscribed newsletters. - **Spam Emails (commonly known as 'Spam')**: These are unsolicited emails often sent in bulk. They range from benign advertisements to malicious emails containing scams or malware. The goal is to accurately identify and filter out Spam emails to improve user experience and enhance security. ## Objectives - Perform exploratory data analysis. - Prepare the dataset through preprocessing and feature engineering. - Build a logistic regression model to classify messages. - Evaluate the model using accuracy, precision, recall, and F1-score. - Improve the model with cross-validation and parameter tuning. ## Project Structure 1. **Data Import and Initial Exploration** - Load the dataset - Inspect data types and missing values 2. **Data Cleaning** - Remove unnecessary columns - Handle missing values 3. **Exploratory Data Analysis** - Analyze the distribution of message lengths - Visualize the count of spam vs. ham messages 4. **Feature Engineering** - Apply TF-IDF Vectorization 5. **Model Training** - Split the data into training and testing sets - Train a Logistic Regression model 6. **Model Evaluation** - Evaluate the model's performance - Analyze the confusion matrix and classification report 7. **Model Improvement** - Perform cross-validation - Tune model parameters using Grid Search 8. **Feature Analysis** - Identify influential features for spam detection 9. **Error Analysis** - Examine false positives and false negatives
<script setup lang="ts"> import MobileSideBar from './MobileSideBar.vue' import { convertImgUrl } from '@/utils' import { useAppStore, useUserStore } from '@/store' const [appStore, userStore] = [useAppStore(), useUserStore()] const [router, route] = [useRouter(), useRoute()] // 菜单项 TODO: 直接从路由中加载? 似乎不可行 const menuOptions = [ { text: '首页', icon: 'mdi:home', path: '/', }, { text: '发现', icon: 'mdi:apple-safari', subMenu: [ { text: '归档', icon: 'mdi:archive', path: '/archives', }, { text: '分类', icon: 'mdi:menu', path: '/categories', }, { text: '标签', icon: 'mdi:tag', path: '/tags', }, ], }, { text: '娱乐', icon: 'mdi:gamepad-circle', subMenu: [ { text: '相册', icon: 'mdi:view-gallery', path: '/albums', }, ], }, { text: '友链', icon: 'mdi:vector-link', path: '/links', }, { text: '关于', icon: 'mdi:information-outline', path: '/about', }, { text: '留言', icon: 'mdi:forum', path: '/message', }, ] let navClass = $ref('nav') let barShow = $ref(true) // * 监听 y 效果比添加 scroll 监听器效果更好 // * 节流操作, 效果很好 const { y } = $(useWindowScroll()) // 通过 $() 解构 ref let preY = $ref(0) // 记录上一次的 y 滚动距离 watchThrottled($$(y), () => { if (Math.abs(preY - y) >= 50) { // 小幅度滚动不进行操作 barShow = (y < preY) navClass = (y > 60) ? 'nav-fixed' : 'nav' preY = y } }, { throttle: 100 }) function logout() { userStore.logout() if (route.name === 'User') // 如果在个人信息页登出则回到首页 router.push('/') window.$notification?.success({ title: '退出登录成功!', duration: 1500 }) } // const blogTitle = import.meta.env.VITE_APP_TITLE </script> <template> <!-- 移动端顶部导航栏 --> <Transition name="slide-fade" appear> <div v-if="barShow" :class="navClass" flex items-center justify-between fixed z-11 inset-x-0 top-0 h-60 px-16 py-10 lg:hidden > <!-- 左上角标题 --> <router-link to="/" text-18 font-bold cursor-pointer> {{ appStore.blogConfig.website_author }} </router-link> <!-- 右上角图标 --> <div flex items-center> <button mr-10 @click="appStore.setSearchFlag(true)"> <TheIcon icon="ic:round-search" :size="22" /> </button> <button @click="appStore.setCollapsed(true)"> <TheIcon icon="ic:sharp-menu" :size="22" /> </button> </div> </div> </Transition> <!-- 侧边栏 --> <MobileSideBar /> <!-- 电脑端顶部导航栏 --> <Transition name="slide-fade" appear> <div v-if="barShow" :class="navClass" fixed z-11 inset-x-0 top-0 h-60 hidden lg:block > <div h-full px-36 flex items-center justify-between > <!-- 左上角标题 --> <router-link to="/" text-18 font-bold cursor-pointer> {{ appStore.blogConfig.website_author }} </router-link> <!-- 右上角菜单 --> <div flex items-center text-6xl> <!-- 搜索 --> <div class="menus-item"> <a class="menu-btn" flex items-center @click="appStore.setSearchFlag(true)"> <TheIcon icon="mdi:magnify" :size="18" /> <span ml-4> 搜索 </span> </a> </div> <!-- 根据数组生成 --> <div v-for="item of menuOptions" :key="item.text" class="menus-item"> <!-- 不包含子菜单 --> <router-link v-if="!item.subMenu" :to="item.path" class="menu-btn" flex items-center> <TheIcon :icon="item.icon" :size="18" /> <span ml-4> {{ item.text }} </span> </router-link> <!-- 包含子菜单 --> <div v-else class="menu-btn"> <div flex items-center> <TheIcon :icon="item.icon" :size="18" /> <span mx-4> {{ item.text }} </span> <TheIcon icon="ep:arrow-down-bold" :size="18" /> </div> <ul class="menus-submenu"> <router-link v-for="sub of item.subMenu" :key="sub.text" :to="sub.path"> <div flex items-center> <TheIcon :icon="sub.icon" :size="18" /> <span ml-4> {{ sub.text }} </span> </div> </router-link> </ul> </div> </div> <!-- 登录 --> <div class="menus-item"> <a v-if="!userStore.userId" class="menu-btn" @click="appStore.setLoginFlag(true)"> <div flex items-center> <i-ph:user-bold text-18 mr-4 /> 登录 </div> </a> <template v-else> <n-avatar :size="28" :src="convertImgUrl(userStore.avatar)" round fallback-src="https://static.talkxj.com/avatar/user.png" /> <ul class="menus-submenu"> <router-link to="/user"> <div flex items-center> <i-mdi:account-circle text-18 mr-4 /> 个人中心 </div> </router-link> <a @click="logout"> <i-mdi:logout text-18 /> 退出登录 </a> </ul> </template> </div> </div> </div> </div> </Transition> </template> <style scoped lang="scss"> .nav { transition: all 0.8s; color: #fff; background: rgba(0, 0, 0, 0) !important; } .nav-fixed { transition: all 0.8s; color: #000; background: rgba(255, 255, 255, 0.8) !important; box-shadow: 0 5px 6px -5px rgba(133, 133, 133, 0.6); & .menu-btn:hover { color: #49b1f5 !important; } } .menus-item { position: relative; display: inline-block; margin: 0 0 0 3.8rem; a { transition: all 0.2s; } a::after { position: absolute; bottom: -5px; left: 0; z-index: -1; width: 0; height: 3px; background-color: #80c8f8; content: ""; transition: all 0.3s ease-in-out; } .menu-btn { &:hover::after { width: 100%; } } } .menus-item:hover .menus-submenu { display: block; } .menus-submenu { position: absolute; display: none; right: 0; width: max-content; margin-top: 8px; box-shadow: 0 5px 20px -4px rgba(0, 0, 0, 0.5); background-color: #fff; animation: submenu 0.3s 0.1s ease both; &::before { position: absolute; top: -8px; left: 0; width: 100%; height: 20px; content: ""; } a { line-height: 2; color: #4c4948 !important; text-shadow: none; display: block; padding: 6px 14px; } a:hover { background: #4ab1f4; } } @keyframes submenu { 0% { opacity: 0; filter: alpha(opacity=0); transform: translateY(10px); } 100% { opacity: 1; filter: none; transform: translateY(0); } } </style>
#ifndef SIDEWALK_H__ #define SIDEWALK_H__ #include "c4d.h" #include "lib_noise.h" /// Options for GetHardRndAngle() enum class RANDOMANGLE { GETALL = 0, ///< Get all kinds of random angles GET180 = 1 ///< Get only angles divideable by 180° } ENUM_END_LIST(RANDOMANGLE); /// This class builds a complete sidewalk from separate objects. class Sidewalk { MAXON_DISALLOW_COPY_AND_ASSIGN(Sidewalk); public: /// This struct holds all the parameters needed to build a complete sidewalk. struct Parameters { // General Parameters Vector elementSize; Int32 countX; Int32 countZ; Float shift; Int32 elementRndSeed; Float elementSelectBias; Float elementHoleBias; // Plates Parameters Float plateGap; Float plateFilletRad; Int32 plateFilletSubd; Bool plateUsePhong; Vector plateRndRot; Vector plateRndPos; Int32 plateRndSeed; BaseMaterial *plateMat; Bool plateMatPerPlate; Float plateMatScale; // Cobblestones Parameters Int32 cobbleCount; Float cobbleElevation; Int32 cobbleSubdiv; Float cobbleCrumple; Int32 cobbleCrumpleSeed; Int32 cobbleRotSeed; Float cobbleGap; Float cobbleFilletRad; Int32 cobbleFilletSubd; Bool cobbleUsePhong; Vector cobbleRndRot; Vector cobbleRndPos; Int32 cobbleRndSeed; BaseMaterial *cobbleMat; Bool cobbleMatPerStone; Float cobbleMatScale; // Dirt Plane Parameters Bool dirtPlaneEnabled; Int32 dirtPlaneSubd; Float dirtPlaneCrumple; Int32 dirtPlaneCrumpleSeed; Float dirtPlaneElevation; BaseMaterial *dirtPlaneMat; Float dirtPlaneMatScale; // Curbstone Parameters Bool curbEnabled; Vector curbSize; Int32 curbCount; Int32 curbSubd; Float curbCrumpleVal; Float curbFilletRad; Int32 curbFilletSubd; Float curbSizeVar; Int32 curbSizeSeed; Float curbElevation; BaseMaterial *curbMat; Float curbMatScale; Bool curbMatPerStone; // Component group names String sidewalkGroupName; String plateGroupName; String cobblestoneGroupName; String curbstoneGroupName; // Component names String plateName; String cobblestoneName; String dirtPlaneName; String curbstoneName; /// Default constructor Parameters() : countX(0), countZ(0), shift(0.0), elementRndSeed(0), elementSelectBias(0.0), elementHoleBias(0.0), plateGap(0.0), plateFilletRad(0.0), plateFilletSubd(0), plateUsePhong(false), plateRndRot(0.0), plateRndPos(0.0), plateRndSeed(0), plateMat(nullptr), plateMatPerPlate(false), plateMatScale(0.0), cobbleCount(0), cobbleElevation(0.0), cobbleSubdiv(0), cobbleCrumple(0.0), cobbleCrumpleSeed(0), cobbleRotSeed(0), cobbleGap(0.0), cobbleFilletRad(0.0), cobbleFilletSubd(0), cobbleUsePhong(false), cobbleRndSeed(0), cobbleMat(nullptr), cobbleMatPerStone(false), cobbleMatScale(0.0), dirtPlaneEnabled(false), dirtPlaneSubd(0), dirtPlaneCrumple(0.0), dirtPlaneCrumpleSeed(0), dirtPlaneElevation(0.0), dirtPlaneMat(nullptr), dirtPlaneMatScale(0.0), curbEnabled(false), curbCount(0), curbSubd(0), curbCrumpleVal(0.0), curbFilletRad(0.0), curbFilletSubd(0), curbSizeVar(0.0), curbSizeSeed(0), curbElevation(0.0), curbMat(nullptr), curbMatScale(0.0), curbMatPerStone(false) {} }; public: /// Build a complete sidewalk /// @return Pointer to the parent object of the sidewalk object hierarchy; or nullptr if an error occurred. Caller owns the pointed object. BaseObject *Build(BaseContainer *bc, BaseDocument *doc); private: /// Get all sidewalk parameters from a BaseContainer and copy them to _params void GetParametersFromContainer(const BaseContainer &bc, const BaseDocument &doc); // Get all object and group names from the string resource and copy them to _params void GetObjectNames(); /// Create a single plate /// @return Pointer to a new plate. Caller owns the pointed object. BaseObject *CreateSinglePlate(); /// Create a group of cobblestones (same size as a plate) /// @return Pointer to a new group of cobblestones. Caller owns the pointed object. BaseObject *CreateCobblestones(Random &rnd); /// Create the dirt plane /// @return Pointer to a new dirt plane. Caller owns the pointed object. BaseObject *CreateDirtPlane(Random &rnd); /// Create a curbstone /// @param[in,out] stoneSize The size for this curbstone. Assigned the final actual size value (changed by variation). /// @return Pointer to a new curbstone. Caller owns the pointed object. BaseObject *CreateSingleCurbstone(Vector &stoneSize, Random &sizeRnd, Random &crumpleRnd); /// Create a row of curbstones /// @return Pointer to a new row of curbstones. Caller owns the pointed object. BaseObject *CreateCurbstoneRow(Float totalSpace); /// Add a texture tag to op /// @param[in] op Pointer to the object that should receive the new texture tag /// @param[in] mat Pointer to the material that should be linked in the texture tag /// @param[in] matScale Scale value for the projection in the texture tag /// @return False if an error occurred and the tag could not be added; otherwise true static Bool AddTextureTag(BaseObject *op, BaseMaterial *mat, Float matScale); /// Add a phong tag to op /// @return False if an error occurred and the tag could not be added; otherwise true static Bool AddPhongTag(BaseObject *op, Bool angleLimit = true, Float angle = Rad(89.9)); private: Sidewalk::Parameters _params; BaseDocument *_doc; public: /// Default constructor Sidewalk() {} }; /// Make a generator object editable /// @return The editable object. Caller owns the pointed object. BaseObject *MakeEditable(BaseObject *op, BaseDocument *doc); /// Return the normal vector for a vertex of a polygon object /// Needs an initialized Neighbor class Vector GetVertexNormal(PolygonObject *op, Neighbor *neighbor, Int32 pointIndex); /// Crumple a geometry, using the vertex normals as displacement direction void CrumpleGeometry(PolygonObject *op, Float strength, Random &rnd); /// Returns 0°, 90°, 180° or 270° in radians Float GetHardRndAngle(Random &rnd, RANDOMANGLE mode); #endif //SIDEWALK_H__
// // src/App.js // import React, { useState } from "react"; // import "./App.css"; // import ImageGallery from "./ImageGallery"; // import OverlayText from "./OverlayText"; // function App() { // const [selectedImage, setSelectedImage] = useState(null); // const handleImageClick = (imageUrl) => { // setSelectedImage(imageUrl); // }; // return ( // <div className="App"> // <h1>Image Overlay App</h1> // <div className="container"> // <ImageGallery onImageClick={handleImageClick} /> // {selectedImage && <OverlayText imageUrl={selectedImage} />} // </div> // </div> // ); // } // export default App; // import React, { useState } from "react"; // import "./App.css"; // import ImageDisplay from "./ImageGallery"; // import TextInput from "./OverlayText"; // function App() { // const [imageUrl, setImageUrl] = useState(""); // const [textOverlays, setTextOverlays] = useState([]); // const addTextOverlay = (text) => { // setTextOverlays([...textOverlays, { text, id: Date.now() }]); // }; // return ( // <div className="App"> // <h1>Image Text Overlay</h1> // <ImageDisplay imageUrl={imageUrl} textOverlays={textOverlays} /> // <TextInput setImageUrl={setImageUrl} addTextOverlay={addTextOverlay} /> // </div> // ); // } // export default App; import React, { useState } from "react"; import "./App.css"; import ImageDisplay from "./ImageGallery"; import TextInput from "./OverlayText"; function App() { const [imageUrl, setImageUrl] = useState(""); const [textOverlays, setTextOverlays] = useState([]); const addTextOverlay = (text) => { setTextOverlays([ ...textOverlays, { text, id: Date.now(), width: 200, height: 50 }, ]); }; const updateTextOverlay = (id, updatedOverlay) => { setTextOverlays((prevOverlays) => prevOverlays.map((overlay) => overlay.id === id ? { ...overlay, ...updatedOverlay } : overlay ) ); }; return ( <div className="App"> <h1>Image Text Overlay</h1> <ImageDisplay imageUrl={imageUrl} textOverlays={textOverlays} updateTextOverlay={updateTextOverlay} /> <TextInput setImageUrl={setImageUrl} addTextOverlay={addTextOverlay} /> </div> ); } export default App;
package es.eduardo.gymtracker; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import es.eduardo.gymtracker.utils.Utils; /** * Activity to calculate and display the Body Mass Index (BMI) of the logged-in user. */ public class ImcActivity extends AppCompatActivity { // Firebase FirebaseFirestore db; FirebaseAuth mAuth; // UI elements TextView ageTxt, conditionTxt, imcTxt, suggestionTxt; Button nextButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_imc); db = FirebaseFirestore.getInstance(); mAuth = FirebaseAuth.getInstance(); ageTxt = findViewById(R.id.ageTxt); conditionTxt = findViewById(R.id.condition); imcTxt = findViewById(R.id.imcTxt); suggestionTxt = findViewById(R.id.suggestion); nextButton = findViewById(R.id.nextButton); calculateImc(); redirectActivity(); } /** * Calculates the Body Mass Index (BMI) of the user and updates the UI with the result. */ private void calculateImc() { if (mAuth.getCurrentUser() != null) { String email = mAuth.getCurrentUser().getEmail(); db.collection("users").document(email).get().addOnCompleteListener(task -> { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { // Retrieve user data double height = Double.parseDouble(document.getString("height")); double weight = Double.parseDouble(document.getString("weight")); int age = Integer.parseInt(document.getString("age")); // Convert height to meters double heightInM = height / 100; // Calculate BMI double imc = weight / Math.pow(heightInM, 2); // Save BMI to Firestore db.collection("users").document(email) .update("bmi", imc) .addOnSuccessListener(aVoid -> { // Display results ageTxt.setText(String.valueOf(age)); imcTxt.setText(String.format("%.2f", imc)); conditionTxt.setText(Utils.getCategory((float) imc, this)); suggestionTxt.setText(Utils.getSuggestions((float) imc, this)); }) .addOnFailureListener(e -> { Toast.makeText(ImcActivity.this, "Error saving BMI", Toast.LENGTH_SHORT).show(); }); } else { Toast.makeText(ImcActivity.this, "User document does not exist", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ImcActivity.this, "Error getting user document", Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(ImcActivity.this, "User not logged in", Toast.LENGTH_SHORT).show(); } } /** * Redirects to the MainActivity upon button click. */ private void redirectActivity() { nextButton.setOnClickListener(view -> { Intent intent = new Intent(ImcActivity.this, MainActivity.class); startActivity(intent); }); } }
import { Route } from "@angular/router"; import { AuthComponent } from "../../components/auth/auth.component"; import { Paths } from "../../shared/enums/path.enum"; export const routes: Route[] = [ { path: Paths.AUTH, component: AuthComponent, children: [ { path: Paths.SIGN_IN, loadComponent: () => import('../../components/auth/sign-in/sign-in.component').then(c => c.SignInComponent) }, { path: Paths.SIGN_UP, loadComponent: () => import('../../components/auth/sign-up/sign-up.component').then(c => c.SignUpComponent) }, { path: '', redirectTo: Paths.SIGN_IN, pathMatch: 'full' } ] }, { path: '**', redirectTo: Paths.AUTH, }, ];
package com.example.entity; import com.example.model.Order; import jakarta.persistence.*; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import java.time.LocalDateTime; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity @Table(name = "orders") public class OrderEntity extends BaseTimeEntity { @Id @Column(name = "orders_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "member_id", nullable = false) private Long memberId; @Column(name = "orders_code", unique = true, nullable = false, length = 50) private String ordersCode; @Builder public OrderEntity(Long id, Long memberId, String ordersCode, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.memberId = memberId; this.ordersCode = ordersCode; this.createdAt = createdAt; this.updatedAt = updatedAt; } public static OrderEntity toOrderEntity(Order order) { return OrderEntity.builder() .id(order.getId()) .memberId(order.getMemberId()) .ordersCode(order.getOrdersCode()) .createdAt(order.getCreatedAt()) .updatedAt(order.getUpdatedAt()) .build(); } public Order toOrder() { return Order.builder() .id(getId()) .memberId(getMemberId()) .ordersCode(getOrdersCode()) .createdAt(getCreatedAt()) .updatedAt(getUpdatedAt()) .build(); } }
import { Box, Typography, Stack } from "@mui/material"; import Aos from "aos"; import { useEffect } from "react"; const ExerciseVideos = ({ exerciseVideos, name }) => { useEffect(() => { Aos.init({ duration: 2000 }); }); return ( <Box data-aos="fade-up" sx={{ marginTop: { lg: "203px", xs: "20px" } }} p="20px" > <Typography sx={{ fontSize: { lg: "44px", xs: "25px" } }} fontWeight={700} color="#000" mb="33px" > Watch{" "} <span style={{ color: "#FF2625", textTransform: "capitalize" }}> {name} </span>{" "} exercise videos on Youtube </Typography> <Stack sx={{ flexDirection: { lg: "row" }, gap: { lg: "110px", xs: "0px" } }} justifyContent="flex-start" flexWrap="wrap" alignItems="center" > {exerciseVideos?.slice(0, 3)?.map((item, index) => ( <a key={index} className="exercise-video" href={`https://www.youtube.com/watch?v=${item.video.videoId}`} target="_blank" rel="noreferrer" > <img style={{ borderTopLeftRadius: "20px" }} src={item.video.thumbnails[0].url} alt={item.video.title} /> <Box> <Typography sx={{ fontSize: { lg: "28px", xs: "18px" } }} fontWeight={600} color="#000" > {item.video.title} </Typography> <Typography fontSize="14px" color="#000"> {item.video.channelName} </Typography> </Box> </a> ))} </Stack> </Box> ); }; export default ExerciseVideos;
#ifndef IMPIANTO_H #define IMPIANTO_H #include <vector> #include "data.h" #include "bombola.h" #include "veicolo.h" #include "funzioni.h" class Impianto //classe astratta { private: std::vector<Bombola*> serbatoi; public: virtual ~Impianto(); virtual Impianto *clona() const=0; virtual std::string getInfo() const =0; virtual std::string getNome() const =0; virtual bool idoneita(const Veicolo&) const=0; Impianto()=default; Impianto (const Impianto&); Impianto& operator =(const Impianto&); Bombola& operator[](unsigned int ); const Bombola& operator[](unsigned int )const; unsigned int nBombole() const; double capacita_impianto() const; void inserisciBombola(const Bombola&); void rimuoviBombola(unsigned int i); virtual void Salva(QXmlStreamWriter& x) const; static Impianto* LeggiImpiantoInstanziabile(QXmlStreamReader& x); bool AlertRevisione() const; static std::vector<Bombola*> Leggi(QXmlStreamReader& x); }; #endif // IMPIANTO_H
import { BadRequestException, Injectable } from '@nestjs/common'; import { IReservation } from './interfaces/IReservation'; import { ID } from 'src/types/CommonTypes'; import { ReservationDto } from './dto/reservation.dto'; import { ReservationSearchOptions } from './interfaces/IReservationSearchOptions'; import { Reservation } from './schemas/reservation.schema'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { getMskDate } from 'src/helpers/dateHelper'; @Injectable() export class ReservationsService implements IReservation { constructor( @InjectModel(Reservation.name) private reservationModel: Model<Reservation>, ) {} async addReservation(reservation: ReservationDto): Promise<Reservation> { const dateStartMsk = new Date(reservation.dateStart); const dateEndMsk = new Date(reservation.dateEnd); const dateNowMsk = getMskDate(); // проверки на корректность переданных дат const isDateStartFuture = dateStartMsk > dateNowMsk; const isDateEndFuture = dateEndMsk > dateNowMsk; const isDateStartBeforeDateEnd = dateStartMsk < dateEndMsk; const isNotDateStartSameDateEnd = dateStartMsk !== dateEndMsk; const roomReservations = await this.reservationModel .find({ roomId: reservation.roomId }) .lean(); // проверка что комнаты не заняты roomReservations.map((reservation) => { if ( (dateStartMsk >= reservation.dateStart && dateStartMsk <= reservation.dateEnd) || (dateEndMsk >= reservation.dateStart && dateEndMsk <= reservation.dateEnd) || (dateStartMsk <= reservation.dateStart && dateEndMsk >= reservation.dateEnd) ) { throw new BadRequestException('Даты заняты'); } }); if ( isDateStartFuture && isDateEndFuture && isDateStartBeforeDateEnd && isNotDateStartSameDateEnd ) { const newReservation = this.reservationModel.create(reservation); return newReservation; } else { throw new BadRequestException('Некорректные даты'); } } async removeReservation(id: ID): Promise<void> { await this.reservationModel.findByIdAndDelete(id); return; } getReservations(filter: ReservationSearchOptions): Promise<Reservation[]> { const { userId, dateStart, dateEnd } = filter; const query: any = {}; if (userId) query.userId = userId; if (dateStart) query.dateStart = { $gte: dateStart }; if (dateEnd) query.dateEnd = { $lte: dateEnd }; const reservations = this.reservationModel.find(query); return reservations; } }
from django.test import TestCase from ..models import LicenceVersion from ..factories import LicenceVersionFactory, LicenceFactory class LicenceVersionTests(TestCase): def test_create(self): obj = LicenceVersionFactory.create() qs = LicenceVersion.objects.filter(pk=obj.pk) self.assertTrue(qs.exists()) self.assertEqual(qs[0], obj) def test_delete(self): obj = LicenceVersionFactory.create() obj.delete() qs = LicenceVersion.objects.filter(pk=obj.pk) self.assertFalse(qs.exists()) def test_str(self): obj = LicenceVersionFactory.create() self.assertIn(obj.name, str(obj)) self.assertIn(obj.name, obj.label) def test_archive(self): obj = LicenceVersionFactory.create() licence = LicenceFactory.create(version=obj) obj.archive() obj.refresh_from_db() licence.refresh_from_db() self.assertFalse(obj.is_active()) self.assertFalse(licence.is_active()) def test_set_default(self): version1 = LicenceVersionFactory.create() version2 = LicenceVersionFactory.create() version1.set_default() version1.refresh_from_db() version2.refresh_from_db() self.assertTrue(version1.is_default) self.assertFalse(version2.is_default)
// listado de todas las oportunidades de practica que corresponden a los intereses del estudiante // ------------------------------------------------------------------------------------------------- import React from 'react'; import { Box, Heading, Text, Wrap, WrapItem, } from '@chakra-ui/react'; import { useNavigate } from 'react-router-dom'; import { useQuery } from 'react-query'; import CardOportunity from '../../components/Cards/CardOportunity'; import ROUTES from '../../routers/config/routes'; import InterestService from '../../networking/services/interest/InterestService'; const photo = 'https://www.tuasesordemoda.com/wp-content/uploads/2021/12/rostro-mujer-cuadrado.jpg'; export default function OportunidadesPracticas() { const { data: InterestJobOffer, } = useQuery(['getInterestJobOffer'], () => InterestService.getJobOfferInterest()); console.log(InterestJobOffer); const navigate = useNavigate(); return ( <Box> <Heading as="h1" fontFamily="Raleway" fontSize="4xl" fontWeight="extraBold">Oportunidades de Práctica</Heading> <Heading as="h2" fontFamily="Raleway" fontSize="2xl" fontWeight="extraBold" textAlign="center" margin="12px auto 0 auto"> Según tus intereses </Heading> <Text textAlign="center" margin="24px auto" maxWidth="800px"> Te recomendamos que previo a postularte, te tomes el tiempo de investigar el perfil de las empresas y conocer más sobre ellas. Esto va ayudar que tengas mayor información de tus opciones y te ayude a tomar una mejor decisión. </Text> <Wrap marginTop={6} spacing={4} justify="center"> {InterestJobOffer?.map((jobOffer) => ( <WrapItem w={{ sm: '100%', md: '40%' }} justifyContent="center"> <CardOportunity key={jobOffer.name_jobOffer} name={jobOffer.nameJobOffer.name} description={jobOffer.description.description} modality={jobOffer.modality.modality} quotas={jobOffer.quotas.quotas} workArea={jobOffer.nameWorkArea} nameCompany={jobOffer.nameCompany.company.name_company} photo={photo} onClick={() => [navigate(ROUTES.oportunidadPracticaPage)]} /> </WrapItem> ))} </Wrap> </Box> ); }
package dev.langchain4j.store.embedding.mongodb; import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import dev.langchain4j.data.segment.TextSegment; import dev.langchain4j.model.embedding.AllMiniLmL6V2QuantizedEmbeddingModel; import dev.langchain4j.model.embedding.EmbeddingModel; import dev.langchain4j.store.embedding.EmbeddingStore; import dev.langchain4j.store.embedding.EmbeddingStoreIT; import lombok.SneakyThrows; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.conversions.Bson; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import static java.lang.String.format; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; @EnabledIfEnvironmentVariable(named = "MONGODB_ATLAS_USERNAME", matches = ".+") class MongoDbEmbeddingStoreCloudIT extends EmbeddingStoreIT { private static final String DATABASE_NAME = "test_database"; private static final String COLLECTION_NAME = "test_collection"; private static final String INDEX_NAME = "default"; static MongoClient client; MongoDbEmbeddingStore embeddingStore = MongoDbEmbeddingStore.builder() .fromClient(client) .databaseName(DATABASE_NAME) .collectionName(COLLECTION_NAME) .indexName(INDEX_NAME) .build(); EmbeddingModel embeddingModel = new AllMiniLmL6V2QuantizedEmbeddingModel(); @BeforeAll static void beforeAll() { String username = System.getenv("MONGODB_ATLAS_USERNAME"); String password = System.getenv("MONGODB_ATLAS_PASSWORD"); String host = System.getenv("MONGODB_ATLAS_HOST"); String connectionString = format("mongodb+srv://%s:%s@%s/?retryWrites=true&w=majority", username, password, host); client = MongoClients.create(connectionString); } @AfterAll static void afterAll() { client.close(); } @Override protected EmbeddingStore<TextSegment> embeddingStore() { return embeddingStore; } @Override protected EmbeddingModel embeddingModel() { return embeddingModel; } @Override protected void clearStore() { CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder() .register(MongoDbDocument.class, MongoDbMatchedDocument.class) .build()); CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry); MongoCollection<MongoDbDocument> collection = client.getDatabase(DATABASE_NAME) .getCollection(COLLECTION_NAME, MongoDbDocument.class) .withCodecRegistry(codecRegistry); Bson filter = Filters.exists("embedding"); collection.deleteMany(filter); } @Override @SneakyThrows protected void awaitUntilPersisted() { Thread.sleep(2000); } }
<script lang="ts" setup> import { NAvatar, NBadge, NButton, NCard, NCol, NForm, NFormItem, NImage, NInput, NModal, NPagination, NPopover, NPopselect, NRow, NSlider, NStatistic, NSwitch, NTabPane, NTabs, useDialog, useMessage, } from 'naive-ui' import {computed, onBeforeMount, onMounted, reactive, ref} from 'vue' import {useAuthStoreWithout} from '@/store/modules/auth' import {useSignalR} from '@/views/chat/hooks/useSignalR' import SubmitFooter from '@/components/common/SubmitFooter/submitFooter.vue' import {HoverButton, SvgIcon} from '@/components/common' import type {SubmitDTO} from '@/api' import {GenerateGraph, MyImageList, ShareImage, ShareImageList} from '@/api' import {usePictureStore, useUserStore} from "@/store"; import PromptRecommend from "@/assets/recommend.json"; // 定义后端接口的地址 import {t} from '@/locales' const apiUrl = import.meta.env.VITE_GLOB_API_URL const authStore = useAuthStoreWithout() const modelTypeOptions: Array<{ label: string; value: number }> = [ {label: 'SD', value: 0}, ] const modelOptions: Array<{ label: string; value: string }> = [ {label: '二次元', value: '二次元'}, {label: '真人', value: '真人'}, ] const userStore = useUserStore() const pictureStore = usePictureStore() const selectedTab = ref('chap1') const showModal = ref(false) const loading = ref<boolean>(false) const dialog = useDialog() const page = ref(1) const pageSize = ref(10) const totalPage = ref(0) const ms = useMessage() // signalR const {waitingCount, connection, imgUrl, start} = useSignalR("") const formData = reactive<SubmitDTO>({ prompt: '', count: 1, size: 512, negativePrompt: authStore.imgKey ?? '', modelType: 0, connectionId: null, model: null, }) const submit = async () => { formData.connectionId = connection.value?.connectionId loading.value = true const {picture} = await GenerateGraph(formData) if (picture == "data:image/png;base64,") { ms.error("绘画失败") loading.value = false } else { ms.success("绘画成功") let list = pictureStore.pictureList list.push(picture) pictureStore.updatePictureList(list) userStore.refreshUserInfo() loading.value = false } } const PublicChange = async (imageRecordId: number, isPublic: boolean) => { const {data} = await ShareImage(imageRecordId, isPublic) if (data) ms.success('操作成功') } const loadPosts = async () => { let response console.log("+++++++++++loadPosts") switch (selectedTab.value) { case 'chap1': let list = pictureStore.pictureList response = {data: {items: list}} break } // 设置请求头 const {data} = response if (data.items != null) { imgUrl.value = data.items totalPage.value = Math.ceil(data.total / pageSize.value) } } const updatePage = (p: number) => { page.value = p loadPosts() } // 删除所有记录 function handleClear() { dialog.warning({ title: t('chat.clearDraw'), content: t('chat.clearDrawConfirm'), positiveText: t('common.yes'), negativeText: t('common.no'), onPositiveClick: () => { pictureStore.updatePictureList([]) loadPosts() }, }) } const buttonDisabled = computed(() => { return loading.value || !formData.prompt || formData.prompt.trim() === '' }) const changeBoolean = (imageUrl: any) => { if (imageUrl.islike == null) imageUrl.islike = true else imageUrl.islike = !imageUrl.islike } onMounted(() => { loadPosts() }) onBeforeMount(() => { // 在组件加载时调用 start 方法 start() }) </script> <template> <div class="h-full relative"> <NTabs v-model:value="selectedTab" type="segment"> <NTabPane name="chap1" tab="我的绘画"/> </NTabs> <div id="image-scroll-container" style=" overflow: auto; display: flex; flex-wrap: wrap; gap: 8px; " > <NCard v-for="(imageUrl, index) in imgUrl" :key="index" shadow="hover" style="margin-bottom: 10px;max-width: 300px;" hoverable> <template #cover> <NImage width="512" height="512" lazy :src="imageUrl" :intersection-observer-options="{ root: '#image-scroll-container', }" > <template #placeholder> <div style=" width: 100px; height: 100px; display: flex; align-items: center; justify-content: center; background-color: #0001; " > Loading </div> </template> </NImage> </template> </NCard> </div> <div v-if="totalPage > 0" class="pagination-wrap w-full" style="display: flex; justify-content: center; margin-top: 8px;"> <NPagination :page="page" :page-slot="5" :page-count="totalPage" @update:page="updatePage" /> </div> <div class="absolute bottom-0 w-full"> <SubmitFooter v-model="formData.prompt" placeholder="请输入图片描述词" :search-options="[]" :render-option="null" :button-disabled="buttonDisabled" :show-token="false" :counter="500" @submit="submit" > <NPopselect v-model:value="formData.modelType" :options="modelTypeOptions" trigger="click" :on-update:value="(value) => { formData.modelType = value;formData.count = 1 }" > <NButton>{{ modelTypeOptions.find(i => i.value === formData.modelType)?.label || '请选择模型' }}</NButton> </NPopselect> <HoverButton @click="handleClear"> <span class="text-xl text-[#4f555e] dark:text-white"> <SvgIcon icon="ri:delete-bin-line"/> </span> </HoverButton> <!-- <NPopselect--> <!-- v-model:value="formData.model" :options="modelOptions" trigger="click"--> <!-- :on-update:value="(value) => { formData.model = value;formData.count = 1 }"--> <!-- >--> <!-- <NButton>{{ modelOptions.find(i => i.value === formData.model)?.label || '请选择模型' }}</NButton>--> <!-- </NPopselect>--> <!-- <HoverButton @click="showModal = true">--> <!-- <span class="text-xl text-[#4f555e] dark:text-white">--> <!-- <NPopover trigger="hover">--> <!-- <template #trigger>--> <!-- <SvgIcon icon="ri:settings-4-line" />--> <!-- </template>--> <!-- <span>或许不想知道你的花园长得咋样</span>--> <!-- </NPopover>--> <!-- </span>--> <!-- </HoverButton>--> </SubmitFooter> </div> <NModal v-model:show="showModal" style="width: 90%; max-width: 600px;" preset="card"> <NForm label-placement="left" label-width="auto" require-mark-placement="right-hanging" > <NFormItem label="反向提示词" path="negativePrompt"> <NInput v-model:value="formData.negativePrompt"/> </NFormItem> <NFormItem label="生成图片数量"> <NSlider v-model:value="formData.count" :max="10" :min="1"/> </NFormItem> </NForm> </NModal> </div> </template>
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * 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 * * https://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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.eclipse.apoapsis.ortserver.dao.repositories import org.eclipse.apoapsis.ortserver.dao.blockingQuery import org.eclipse.apoapsis.ortserver.dao.entityQuery import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.PackageCurationProviderConfigDao import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationDao import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationsIssueResolutionsTable import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationsPackageConfigurationsTable import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationsRuleViolationResolutionsTable import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationsTable import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedConfigurationsVulnerabilityResolutionsTable import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedPackageCurationDao import org.eclipse.apoapsis.ortserver.dao.tables.resolvedconfiguration.ResolvedPackageCurationProviderDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.IssueResolutionDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.PackageConfigurationDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.PackageCurationDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.PackageCurationDataDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.RuleViolationResolutionDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.repository.VulnerabilityResolutionDao import org.eclipse.apoapsis.ortserver.dao.tables.runs.shared.IdentifierDao import org.eclipse.apoapsis.ortserver.model.repositories.ResolvedConfigurationRepository import org.eclipse.apoapsis.ortserver.model.resolvedconfiguration.ResolvedConfiguration import org.eclipse.apoapsis.ortserver.model.resolvedconfiguration.ResolvedPackageCurations import org.eclipse.apoapsis.ortserver.model.runs.repository.PackageConfiguration import org.eclipse.apoapsis.ortserver.model.runs.repository.Resolutions import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.insert class DaoResolvedConfigurationRepository(private val db: Database) : ResolvedConfigurationRepository { override fun get(id: Long): ResolvedConfiguration? = db.entityQuery { ResolvedConfigurationDao[id].mapToModel() } override fun getForOrtRun(ortRunId: Long): ResolvedConfiguration? = db.blockingQuery { ResolvedConfigurationDao.find { ResolvedConfigurationsTable.ortRunId eq ortRunId }.limit(1) .firstOrNull()?.mapToModel() } override fun addPackageConfigurations(ortRunId: Long, packageConfigurations: List<PackageConfiguration>) = db.blockingQuery { val resolvedConfiguration = ResolvedConfigurationDao.getOrPut(ortRunId) packageConfigurations.forEach { packageConfiguration -> val packageConfigurationDao = PackageConfigurationDao.getOrPut(packageConfiguration) ResolvedConfigurationsPackageConfigurationsTable.insert { it[resolvedConfigurationId] = resolvedConfiguration.id it[packageConfigurationId] = packageConfigurationDao.id } } } override fun addPackageCurations(ortRunId: Long, packageCurations: List<ResolvedPackageCurations>) = db.blockingQuery { val resolvedConfiguration = ResolvedConfigurationDao.getOrPut(ortRunId) val providerOffset = resolvedConfiguration.packageCurationProviders.count().toInt() packageCurations.forEachIndexed { index, resolvedPackageCurations -> val packageCurationProviderConfig = PackageCurationProviderConfigDao.getOrPut(resolvedPackageCurations.provider) val resolvedPackageCurationProvider = ResolvedPackageCurationProviderDao.new { this.packageCurationProviderConfig = packageCurationProviderConfig this.resolvedConfiguration = resolvedConfiguration this.rank = providerOffset + index } resolvedPackageCurations.curations.forEachIndexed { curationIndex, packageCuration -> val packageCurationDao = PackageCurationDao.new { identifier = IdentifierDao.getOrPut(packageCuration.id) packageCurationData = PackageCurationDataDao.getOrPut(packageCuration.data) } ResolvedPackageCurationDao.new { this.resolvedPackageCurationProvider = resolvedPackageCurationProvider this.packageCuration = packageCurationDao this.rank = curationIndex } } } } override fun addResolutions(ortRunId: Long, resolutions: Resolutions) = db.blockingQuery { val resolvedConfiguration = ResolvedConfigurationDao.getOrPut(ortRunId) resolutions.issues.forEach { issueResolution -> val issueResolutionDao = IssueResolutionDao.getOrPut(issueResolution) ResolvedConfigurationsIssueResolutionsTable.insert { it[resolvedConfigurationId] = resolvedConfiguration.id it[issueResolutionId] = issueResolutionDao.id } } resolutions.ruleViolations.forEach { ruleViolationResolution -> val ruleViolationResolutionDao = RuleViolationResolutionDao.getOrPut(ruleViolationResolution) ResolvedConfigurationsRuleViolationResolutionsTable.insert { it[resolvedConfigurationId] = resolvedConfiguration.id it[ruleViolationResolutionId] = ruleViolationResolutionDao.id } } resolutions.vulnerabilities.forEach { vulnerabilityResolution -> val vulnerabilityResolutionDao = VulnerabilityResolutionDao.getOrPut(vulnerabilityResolution) ResolvedConfigurationsVulnerabilityResolutionsTable.insert { it[resolvedConfigurationId] = resolvedConfiguration.id it[vulnerabilityResolutionId] = vulnerabilityResolutionDao.id } } } }
import requests from bs4 import BeautifulSoup import pandas as pd from urllib.parse import quote import chatGPTSummary headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def fetchAndSaveAsHTML(url, path): # Increase timeout value (in seconds) timeout = 10 # Adjust as needed r = requests.get(url, headers=headers, timeout=timeout) with open(path, "w", encoding="utf-8") as f: f.write(r.text) def readHTMLFile(filename): with open(filename, "r") as f: html_doc = f.read() return html_doc def search_stackoverflow(question): encoded_input = quote(question) # Modify the question to fit the URL format search_query = "+".join(question.split()) # https://stackoverflow.com/search?q=+how+to+upgrade+python+version url = f"https://stackoverflow.com/search?q={quote(question)}" fetchAndSaveAsHTML(url, "data/stackOverflowQnScrape.html") # Send GET request to Stack Overflow search page # response = requests.get(url) response = readHTMLFile("data/stackOverflowQnScrape.html") if response: soup = BeautifulSoup(response, 'html.parser') # Find all search result links search_results = soup.find_all('a', class_='s-link') # Print out the HTML content of the search results page # print(response.text) # Iterate through the search results to find the links to top 10 questions # Go through all the question_links and find the one containing the qn_ as its string store it in question_link and store answers in top_answers question_mapping = {} top_questions = [] for link in search_results: if link: # Extract the question string and URL from the search result question_string = link.text.strip() question_url = "https://stackoverflow.com" + link['href'] question_mapping[question_string] = question_url top_questions.append(question_string) print(top_questions) print(question_mapping) # Find the most relevant question asked by the user and store it in qn_ # most_similar_qn_ = chatGPTSummary.mostSimilarQn(question, top_10_questions) # most_similar_qn_link = question_mapping[most_similar_qn_] if(len(top_questions) != 0): most_similar_qn_ = top_questions[0] most_similar_qn_link = question_mapping[most_similar_qn_] else: print("EMPTY") return # Print out the URLs of the question links # print("Question links:", question_links) # Scrape top 10 answers from just the most_similar_qn_link top_answers = [] response = requests.get(most_similar_qn_link) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') answers = soup.find_all('div', class_='answercell') for answer in answers: top_answers.append(answer.find('div', class_='answercell').text.strip()) return top_answers else: print("Failed to retrieve search results from Stack Overflow") return None # def main(): # Main functionality of your script # if __name__ == "__main__": # main() search_input = input("ENTER THE QUESTION TO BE SEARCHED IN STACKOVERFLOW: ") answers = search_stackoverflow(search_input)
<header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3" > <div class="container"> <a class="navbar-brand" [routerLink]="['/']">Vizualinio programavimo C kalba kursai</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-label="Toggle navigation" [attr.aria-expanded]="isExpanded" (click)="toggle()" > <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-end" [ngClass]="{ show: isExpanded }" > <ul class="navbar-nav flex-grow"> <li *ngIf="isUserStudent()" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/courses']"> Kursai </a> </li> <li *ngIf="isUserTeacher()" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/evaluation']"> Peržiūrėti įkeltus darbus </a> </li> <li *ngIf="isUserAdmin()" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/admin/courses']"> Administravimas </a> </li> <li class="nav-item"> <a class="nav-link text-dark" style="cursor: pointer;" (click)="logout()"> Atsijungti </a> </li> </ul> </div> </div> </nav> </header>
--- title: will-change slug: Web/CSS/will-change tags: - CSS - Propriété - Reference translation_of: Web/CSS/will-change --- <div><section class="Quick_links" id="Quick_Links"><ol><li><strong><a href="/fr/docs/Web/CSS">CSS</a></strong></li><li><strong><a href="/fr/docs/Web/CSS/Reference">Référence CSS</a></strong></li><li><strong><a href="/fr/docs/Web/CSS/CSS_Will_Change">CSS Will Change</a></strong></li><li class="toggle"><details open><summary>Propriétés</summary><ol><li><a href="/fr/docs/Web/CSS/custom-ident"><code>&lt;custom-ident&gt;</code></a></li><li><em><code>will-change</code></em></li></ol></details></li></ol></section></div> <p>La propriété <strong><code>will-change</code></strong> fournit une indication au navigateur sur la propension d&apos;un élément à changer (afin que le navigateur puisse mettre en place les optimisations nécessaires avant que l&apos;élément change vraiment). Ce type d&apos;optimisation permet d&apos;augmenter la réactivité de la page en effectuant des calculs (éventuellement coûteux) en prévision du changement.</p> <div class="warning notecard"> <p><strong>Attention !</strong> <code>will-change</code> est conçu pour être utilisé en dernier recours afin d&apos;aider à la résolutions de problèmes de performance existants. Il ne doit pas être utilisé partout de façon purement préventive.</p> </div> <pre class="brush:css no-line-numbers notranslate">/* Avec un mot-clé */ will-change: auto; will-change: scroll-position; will-change: contents; will-change: transform; /* Exemple de &lt;custom-ident&gt; */ will-change: opacity; /* Exemple de &lt;custom-ident&gt; */ will-change: left, top; /* Exemple de deux &lt;animateable-feature&gt; */ /* Valeurs globales */ will-change: inherit; will-change: initial; will-change: unset; </pre> <p>Il est parfois difficile de bien utiliser cette propriété :</p> <ul> <li> <p id="Don&apos;t_apply_will-change_to_too_many_elements"><em>Il ne faut pas appliquer <code>will-change</code> à de trop nombreux éléments.</em> Le navigateur essaie déjà d&apos;optimiser de nombreuses choses. Certaines de ces optimisations sont fortement couplées avec <code>will-change</code> pour utiliser les ressources de l&apos;ordinateur. Aussi, si <code>will-change</code> est « trop » utilisé, cela peut ralentir la page et consommer intensivement les ressources.</p> </li> <li> <p><em>À utiliser avec parcimonie.</em> Normalement, le navigateur essaie d&apos;appliquer les optimisations dès que possible afin de revenir au plus vite dans un état normal. En revanche, en utilisant <code>will-change</code> dans la feuille de style, on indique que les éléments ciblés vont bientôt changer et le navigateur conservera les optimisations en cours beaucoup plus longtemps si la propriété est maintenue. Il est donc conseillé d&apos;activer et de désactiver <code>will-change</code> de façon pertinente grâce à du script avant et après le changement concerné.</p> </li> <li> <p><em>Ne pas « sur-optimiser » avec <code>will-change</code></em>. Si votre page fonctionne correctement, n&apos;ajoutez pas la propriété <code>will-change</code> sur certains éléments uniquement pour gagner un peu de vitesse. <code>will-change</code> est conçu pour être utilisé en dernier ressort afin de régler les problèmes de performances existants. En utilisant <code>will-change</code> trop souvent, cela consommera plus de mémoire, complexifiera le rendu de la page pour le navigateur (qui se préparera au changement). En bref, cela réduira les performances de la page.</p> </li> <li> <p id="Give_it_sufficient_time_to_work"><em>Laisser le temps à <code>will-change</code> pour qu&apos;il fonctionne.</em> Cette propriété est conçue pour permettre aux auteurs d&apos;indiquer à l&apos;agent-utilisateur les propriétés qui vont probablement changer afin que le navigateur puisse optimiser en avance de phase. Il est donc important de laisser le temps au navigateur d&apos;appliquer ces opérations pour que l&apos;effet obtenu soit bénéfique. Pour cela, mieux vaut donc prévoir légèrement avant le changement que celui-ci aura lieu et alors modifier <code>will-change</code> en prévision.</p> </li> <li> <p><em>Sachez que <code>will-change</code></em><em> peut modifier l&apos;apparence des éléments</em> lorsqu&apos;il est utilisé avec des propriétés qui créent <a href="/fr/docs/Web/CSS/Comprendre_z-index/Empilement_de_couches">des contextes d&apos;empilement</a> (par exemple <code>will-change: opacity</code>) car le contexte d&apos;empilement est créé au préalable.</p> </li> </ul> <h2 id="Syntaxe">Syntaxe</h2> <h3 id="Valeurs">Valeurs</h3> <dl> <dt><code>auto</code></dt> <dd>Ce mot-clé ne traduit pas d&apos;intention particulière. Dans ce cas, l&apos;agent utilisateur applique les méthodes d&apos;optimisations et heuristiques normales.</dd> </dl> <p>Un valeur de type <code>&lt;animateable-feature&gt;</code> peut être :</p> <dl> <dt><code>scroll-position</code></dt> <dd>L&apos;auteur indique que le défilement de l&apos;élément va prochainement être animé et/ou modifié.</dd> <dt><code>contents</code></dt> <dd>L&apos;auteur indique que le contenu de l&apos;élément va prochainement être modifié ou animé.</dd> <dt><a href="/fr/docs/Web/CSS/custom-ident" title="Cette documentation n&apos;a pas encore été rédigée, vous pouvez aider en contribuant !"><code>&lt;custom-ident&gt;</code></a></dt> <dd>Ce type permet d&apos;indiquer que la propriété donnée va prochainement être modifiée ou animée. Si la propriété fournie est un raccourci, on s&apos;attendra à ce que toutes les propriétés détaillées correspondantes soient animées ou changées. Une valeur de ce type ne peut pas être <code>unset</code>, <code>initial</code>, <code>inherit</code>, <code>will-change</code>, <code>auto</code>, <code>scroll-position</code>, ou <code>contents</code>. La spécification ne définit pas le comportement d&apos;une valeur spécifique mais généralement, lorsqu&apos;on utilise <code>transform</code>, cela indique que les couches qui composent la page vont évoluer. <a href="https://github.com/operasoftware/devopera/pull/330">Chrome prend deux mesures</a> selon les propriétés utilisées ici : il établit une nouvelle composition des couches de rendu ou crée un nouveau contexte d&apos;empilement.</dd> </dl> <h3 id="Syntaxe_formelle">Syntaxe formelle</h3> <pre class="syntaxbox notranslate">auto <a href="/fr/docs/CSS/Syntaxe_de_d%C3%A9finition_des_valeurs#Single_bar" title="Single bar: exactly one of the entities must be present">|</a> <a href="#animateable-feature">&lt;animateable-feature&gt;</a><a href="/fr/docs/CSS/Syntaxe_de_d%C3%A9finition_des_valeurs#Hash_mark_()" title="Hash mark: the entity is repeated one or several times, each occurence separated by a comma">#</a><p style="font-family: Open Sans,Arial,sans-serif; margin: 10px 0 0 0;">où <br><code style="font-family: Consolas,Monaco,&quot;Andale Mono&quot;,monospace;"><span id="animateable-feature">&lt;animateable-feature&gt;</span> = scroll-position <a href="/fr/docs/CSS/Syntaxe_de_d%C3%A9finition_des_valeurs#Single_bar" title="Single bar: exactly one of the entities must be present">|</a> contents <a href="/fr/docs/CSS/Syntaxe_de_d%C3%A9finition_des_valeurs#Single_bar" title="Single bar: exactly one of the entities must be present">|</a> <a href="/fr/docs/Web/CSS/custom-ident" title="Le type de données CSS &lt;custom-ident&gt; permet de représenter des chaînes de caractères arbitraires définies par l&apos;utilisateur et qui sont utilisées comme identifiants. Ce type de données est sensible à la casse et pour chaque contexte d&apos;utilisation, plusieurs valeurs sont exclues afin d&apos;éviter des ambiguïtés et des erreurs.">&lt;custom-ident&gt;</a></code></p></pre> <h2 id="Exemples">Exemples</h2> <pre class="brush: css notranslate">.sidebar { will-change: transform; } </pre> <p>Dans l&apos;exemple précédent, on applique la propriété <code>will-change</code> à même la feuille de style. Dans ce cas, le navigateur conservera l&apos;optimisation en mémoire beaucoup plus longtemps que nécessaire. Nous avons vu précédemment que cela devait être évité et voici donc un deuxième exemple qui illustre comment appliquer la propriété <code>will-change</code> grâce à JavaScript (et qui correspond donc à la méthode qui devrait être utilisée la plupart du temps) :</p> <pre class="brush: js notranslate">var el = document.getElementById(&apos;element&apos;); // On applique will-change quand la souris/curseur // pointeur/stylet passe au-dessus de l&apos;élément el.addEventListener(&apos;mouseenter&apos;, hintBrowser); el.addEventListener(&apos;animationEnd&apos;, removeHint); function hintBrowser() { // On liste les propriétés sujettes au changement // lors de l&apos;animation this.style.willChange = &apos;transform, opacity&apos;; } function removeHint() { this.style.willChange = &apos;auto&apos;; }</pre> <p>Cela peut toutefois être pertinent d&apos;inclure <code>will-change</code> dans la feuille de style d&apos;une application qui gère des changements de pages ou des diapositives parmi lesquelles on navigue lorsque les pages sont complexes. Cela permettra au navigateur de préparer la transition en avance de phase et de mieux réagir au changement de page (ou de diapositive) lorsque le bouton associé sera utilisé.</p> <pre class="brush: css notranslate">.slide { will-change: transform; }</pre> <h2 id="Spécifications">Spécifications</h2> <table class="standard-table"> <thead> <tr> <th scope="col">Spécification</th> <th scope="col">État</th> <th scope="col">Commentaires</th> </tr> </thead> <tbody> <tr> <td><a class="external" href="https://drafts.csswg.org/css-will-change/#will-change" hreflang="en" lang="en">CSS Will Change Module Level 1<br><small lang="fr">La définition de &apos;will-change&apos; dans cette spécification.</small></a></td> <td><span class="spec-CR">Candidat au statut de recommandation</span></td> <td>Définition initiale.</td> </tr> </tbody> </table> <table class="properties"><tbody><tr><th scope="row"><a href="/fr/docs/Web/CSS/Valeur_initiale">Valeur initiale</a></th><td><code>auto</code></td></tr><tr><th scope="row">Applicabilité</th><td>tous les éléments</td></tr><tr><th scope="row"><a href="/fr/docs/Web/CSS/H%c3%a9ritage">Héritée</a></th><td>non</td></tr><tr><th scope="row"><a href="/fr/docs/Web/CSS/Valeur_calcul%c3%a9e">Valeur calculée</a></th><td>comme spécifié</td></tr><tr><th scope="row">Type d&apos;animation</th><td>discrète</td></tr></tbody></table> <h2 id="Compatibilité_des_navigateurs">Compatibilité des navigateurs</h2> <div class="hidden">Ce tableau de compatibilité a été généré à partir de données structurées. Si vous souhaitez contribuer à ces données, n&apos;hésitez pas à envoyer une <em>pull request</em> sur <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div> <div class="bc-data" id="bcd:css.properties.will-change"></div>
import 'package:app_geek_plus/Modules/movies/movies_controller.dart'; import 'package:app_geek_plus/application/ui/widgets/movie_card.dart'; import 'package:app_geek_plus/models/movie_model.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart'; class MoviesGroup extends GetView<MoviesController> { final String title; final List<MovieModel> movies; const MoviesGroup({ Key? key, required this.title, required this.movies }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 20, ), Text( title, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold )), SizedBox( height: 280, child: Obx(() { return ListView.builder( shrinkWrap: true, scrollDirection: Axis.horizontal, itemCount: movies.length, itemBuilder: (context, index){ var movie = movies[index]; return MovieCard( movie: movie, favoriteCallback: () => controller.favoriteMovie(movie), ); }, ); } ) ) ], ), ); } }
import React, { useState } from 'react'; import { WorktimeRecord } from '../../behavior/worktime/types'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faFileLines } from '@fortawesome/free-solid-svg-icons'; import { WorktimeEditingModal } from './WorktimeEditingModal'; import { Button } from 'react-bootstrap'; type Props = { worktimeRecord: WorktimeRecord; } export const WorktimeRow = ({ worktimeRecord }: Props) => { const [show, setShow] = useState(false); if(worktimeRecord.finishDate === null) return null; const startDate = new Date(worktimeRecord.startDate); const finishDate = new Date(worktimeRecord.finishDate); const timeDifferenceInMilliseconds = finishDate.getTime() - startDate.getTime(); const timeDifferenceInMinutes = Math.floor(timeDifferenceInMilliseconds / (1000 * 60)); const timeDifferenceInSeconds = Math.floor(timeDifferenceInMilliseconds / 1000); const workedHours = Math.floor(timeDifferenceInMinutes / 60); const workedMinutes = timeDifferenceInMinutes % 60; const workedSeconds = timeDifferenceInSeconds % 60; return ( <> <tr> <td> {startDate.toLocaleDateString() + ', ' + startDate.toLocaleTimeString()} </td> <td> {finishDate.toLocaleDateString() + ', ' + finishDate.toLocaleTimeString()} </td> <td> {workedHours > 0 && `${workedHours}h `} {workedMinutes > 0 && `${workedMinutes}m `} {workedHours === 0 && workedMinutes === 0 && `${workedSeconds}s `} </td> <td> {worktimeRecord.lastEditorName} </td> <td> <Button variant="Link" className="table-action-button" title="Edit" onClick={() => setShow(true)}> <FontAwesomeIcon icon={faFileLines} /> </Button> </td> </tr> <WorktimeEditingModal worktimeRecord={worktimeRecord} show={show} handleClose={() => setShow(false)}/> </> ); };
<!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"> <link rel="stylesheet" href="assets/css/style.css"> <title>History web</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <!-- History web's icon --> <header class="header" id="website-header"> <div class="header" id="header_icon"> <a href="index.html"> <i class="head-logo fa-solid fa-landmark"></i> <h2>History Web</h2> </a> </div> <nav> <!-- Header navigation links to access the get involved page and contact page --> <ul> <li> <div class="get-involved"> <a href="getinvolved.html" aria-label="Jump to the Get Involved page">Get Involved</a><i class="fa-solid fa-hand-holding-heart"></i> </div> </li> <li><a href="contact.html" aria-label="Jump to the Contact page">Contact</a></li> </ul> </nav> </header> <main> <!-- This section contains the main content of the home page --> <div id="middle_section"> <article> <header id="article-header"> <h1>Armistice Day</h1> <p>The Armistice day marks the beginning of the end of The First World War. In 11 of November 1918 an armistice agreement between Germany and the Allies took place in a railroad car outside Compiégne, France.</p> </header> <figure> <!-- The figure tag contains the image with the caption --> <img id="armistice_img" src="assets/images/end-of-wwi-armistice-getty.jpg" alt="End of WWI Celebrations"> <figcaption>Soldiers celebrating World War I Armistice. (Photo by Time Life Pictures/US Army Signal Corps/The LIFE Picture Collection/Getty Images)</figcaption> </figure> <section class="history_allies"> <!-- This section contains extra information that can opens and closes on demand --> <details class="details" id="history_allies"> <summary>History in Allied countries vs Central Powers</summary> <p>Today the Armistice day is seen in most countries as a day of remembrance and honor to those who sacrificed their lives to fight for their country but it has not always been viewed as such. Whilist the first Armistice day was celebrated in Buckinham palace in 1919 and continued being honored for decades and decades to come, the loosing side of the war experienced that day as a momment of defeat and further humiliation imposed due to the Treaty of Versailles. Fortunately today the nations from both sides come together many years later to reflect upon history and help others in need.</p> </details> </section> <section id="remembrance_day"> <!-- This section contains the title with a small summary and list of countries that celebrate the Armistice day --> <h2>Remembrance Day</h2> <p>Not to be confused with Remembrance Sunday or Armistice Day, the Remembrance Day is a memmorial observed in commonwealth states to honour those who lost their lives during war. There are many other countries outside the Commonwealth with festivities and traditions taking place on November 11th to commemorate the armistice signed. Countries such as:</p> <div id="list_countries"> <ul> <li>France</li> <li>Belgium</li> <li>Serbia</li> <li>Bermuda</li> <li>Germany</li> <li>Poland</li> <li>Russia</li> <li>Denmark</li> <li>Norway</li> </ul> <ul> <li>Ireland</li> <li>India</li> <li>South Africa</li> <li>Honk Kong</li> <li>Israel</li> <li>Italy</li> <li>Netherlands</li> <li>Kenya</li> <li>Saint Lucia</li> </ul> </div> </section> <section id="common_symbols"> <!-- This section contains a group of images associated with symbolism related to the Armistice day and a small text explaining --> <h2>Common Symbols Associated</h2> <div class="symbols" id="poppy_history"> <!-- Each div inside this section refers to a different symbol being represented --> <h3>Poppies</h3> <img src="assets/images/poppy.jpg" alt="Poppies" class="symbol_img"> <p class="symbol_p">The red poppy is a symbol of both Remembrance and hope for a peaceful future.</p> </div> <div class="symbols" id="bleuet_history"> <h3>Bleuet de France</h3> <img src="assets/images/bleuet_france.jpg" alt="Bleuet de France" class="symbol_img"> <p class="symbol_p">The bleuet de France is a symbol of memory and solidarity with soldiers, veterans and others affected by war.</p> </div> <div class="symbols" id="natalie_ramonda"> <h3>Natalie's Ramonda</h3> <img src="assets/images/natalies_ramonda.jpg" alt="Serbian Natalie's Ramonda" class="symbol_img"> <p class="symbol_p">Ramonda nathaliae is a species of flowers that grows in Serbia. The Flower is a symbol of the hardships faced by the Serbian army during WW1. Serbia was the Allied country with the <strong>biggest casualty rate</strong> during the war</p> </div> </section> </article> <aside> <!-- The aside section is displayed at the right side of the page and it contains a small clickable glossary --> <h2>Table of Contents</h2> <div id="list_contents"> <a href="#history_allies">History in Allied countries</a> <a href="#remembrance_day">Remembrance Day and List of involved countries</a> <a href="#common_symbols"> Common symbols associated <ol> <li><a href="#poppy_history">Poppies</a></li> <li><a href="#bleuet_history">Bleuet de France</a></li> <li><a href="#natalie_ramonda">Natalie's Ramonda</a></li> </ol> </a> </div> </aside> </div> </main> <footer> <!-- The footer of the page is at the very bottom and it contains links to social media and access to other pages inside History Web --> <div class="footer_social"> <!-- Contains links to social media platforms --> <h3>Find us on:</h3> <a href="https://www.facebook.com/" target="_blank" aria-label="Find us on Facebook (opens in new tab)"><i class="social-icon fa-brands fa-facebook"></i></a> <a href="https://www.instagram.com/" target="_blank" aria-label="Find us on Instagram (opens in new tab)"><i class="social-icon fa-brands fa-instagram"></i></a> <a href="https://twitter.com/" target="_blank" aria-label="Find us on Twitter (opens in new tab)"><i class="social-icon fa-brands fa-twitter"></i></a> <a href="https://www.snapchat.com/en-GB" target="_blank" aria-label="Find us on Snapchat (opens in new tab)"><i class="social-icon fa-brands fa-snapchat"></i></a> </div> <ul class="footer_list"> <!-- Contains the internal links to the contact and get involved page --> <li> <a href="index.html" aria-label="Jump to the Home section">Home</a> </li> <li> <a href="getinvolved.html" aria-label="Jump to the Get involved section">Get involved</a> </li> <li> <a href="contact.html" aria-label="Jump to the Contact section">Contact</a> </li> </ul> <p class="copyright"> Copyright @ History Web 2022 </p> </footer> </body> </html>
.\" $OpenBSD: rpki-client.8,v 1.4 2019/08/09 09:50:44 claudio Exp $ .\" .\" Copyright (c) 2019 Kristaps Dzonsons <kristaps@bsd.lv> .\" .\" Permission to use, copy, modify, and distribute this software for any .\" purpose with or without fee is hereby granted, provided that the above .\" copyright notice and this permission notice appear in all copies. .\" .\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES .\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF .\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR .\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES .\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. .\" .Dd $Mdocdate: August 9 2019 $ .Dt RPKI-CLIENT 8 .Os .Sh NAME .Nm rpki-client .Nd validates the RPKI tree and produces VRPs to be used in .Xr bgpd 8 for Origin Validation. .Sh SYNOPSIS .Nm .Op Fl fnqrv .Op Fl b Ar bind_addr .Op Fl e Ar rsync_prog .Ar tal1 tal2 ... .Sh DESCRIPTION The .Nm utility produces all route announcements starting with trust anchor locators. It uses .Xr openrsync 1 to fetch certificates, manifests, revocation lists, and route announcements themselves. Its arguments are as follows: .Bl -tag -width Ds .It Fl b Ar bind_addr Tell the rsync client to use the specified .Ar bind_addr as the source address for connections. .It Fl e Ar rsync_prog Use .Ar rsync_prog instead of .Xr openrsync 1 to fetch repositories. It must accept the .Fl rlt , .Fl -address and .Fl -delete flags and connect with rsync-protocol locations. .It Fl f Accept out-of-date manifests. This will still report if a manifest has expired. .It Fl n Assume that all requested repositories exist: don't update. .It Fl q Don't emit any Validated RPKI Payloads (VRPs). .It Fl r Don't parse certificate revocation files. This additional step can take a long time. .It Fl v Specified once, prints information about status. Twice, prints each filename as it's processed. .It Ar tal A trust anchor locator (TAL) file. .El .Pp .Nm produces a list of unique .Li roa-set statements as specified by .Xr bgpd.conf 5 on standard output. .\" The following requests should be uncommented and used where appropriate. .\" .Sh CONTEXT .\" For section 9 functions only. .\" .Sh RETURN VALUES .\" For sections 2, 3, and 9 function return values only. .\" .Sh ENVIRONMENT .\" For sections 1, 6, 7, and 8 only. .\" .Sh FILES .Sh EXIT STATUS .Ex -std .\" For sections 1, 6, and 8 only. .\" .Sh EXAMPLES .\" .Sh DIAGNOSTICS .\" For sections 1, 4, 6, 7, 8, and 9 printf/stderr messages only. .\" .Sh ERRORS .\" For sections 2, 3, 4, and 9 errno settings only. .Sh SEE ALSO .Xr openrsync 1 , .Xr bgpd.conf 5 .Sh STANDARDS The following standards are used or referenced in .Nm : .Bl -tag -width -Ds .It RFC 3370 Cryptographic Message Syntax (CMS) Algorithms. .It RFC 3779 X.509 Extensions for IP Addresses and AS Identifiers. .It RFC 4291 IP Version 6 Addressing Architecture. .It RFC 4631 Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan. .It RFC 5280 Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile. .It RFC 5652 Cryptographic Message Syntax (CMS). .It RFC 5781 The rsync URI Scheme. .It RFC 5952 A Recommendation for IPv6 Address Text Representation. .It RFC 6480 An Infrastructure to Support Secure Internet Routing. .It RFC 6482 A Profile for Route Origin Authorizations (ROAs). .It RFC 6485 The Profile for Algorithms and Key Sizes for Use in the Resource Public Key Infrastructure (RPKI). .It RFC 6486 Manifests for the Resource Public Key Infrastructure (RPKI). .It RFC 6487 A Profile for X.509 PKIX Resource Certificates. .It RFC 6488 Signed Object Template for the Resource Public Key Infrastructure (RPKI). .It RFC 7730 Resource Public Key Infrastructure (RPKI) Trust Anchor Locator. .El .\" .Sh HISTORY .Sh AUTHORS The .Nm utility was written by .An Kristaps Dzonsons Aq Mt kristaps@bsd.lv . .\" .Sh CAVEATS .\" .Sh BUGS
<div *ngIf="status != null"> <div class="d-flex justify-content-center my-3"> <div class="alert alert-danger" role="alert"> {{ status!.error.message }} - {{ status!.message }} </div> </div> </div> <div *ngIf="status == null" class="d-flex justify-content-center my-3"> <form [formGroup]="pedidoForm" (ngSubmit)="onSubmit()" class="container"> <!-- ID field - Only shown in EDIT mode --> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <mat-form-field *ngIf="operation == 'EDIT'"> <mat-label>Id:</mat-label> <input matInput formControlName="id" placeholder="ID" required readonly> <mat-hint align="end">No se puede modificar</mat-hint> </mat-form-field> </div> </div> </div> <!-- Fecha de Pedido field --> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <mat-form-field> <mat-label>Fecha de Pedido:</mat-label> <input matInput [matDatepicker]="picker1" formControlName="fecha_pedido" (dateInput)="addEvent('input', $event, 'fecha_pedido')"> <mat-hint>MM/DD/YYYY</mat-hint> <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle> <mat-datepicker #picker1></mat-datepicker> <div *ngIf="hasError('fecha_pedido', 'required')" class="text-danger">Campo obligatorio </div> </mat-form-field> </div> </div> <!-- Fecha de Entrega field --> <div class="col-lg-6"> <div class="form-group"> <mat-form-field> <mat-label>Fecha de Entrega:</mat-label> <input matInput [matDatepicker]="picker2" formControlName="fecha_entrega" (dateInput)="addEvent('input', $event, 'fecha_entrega')"> <mat-hint>MM/DD/YYYY</mat-hint> <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle> <mat-datepicker #picker2></mat-datepicker> <div *ngIf="hasError('fecha_entrega', 'required')" class="text-danger">Campo obligatorio </div> </mat-form-field> </div> </div> </div> <mat-radio-group aria-label="Estado pedido" formControlName="estado_pedido" required> <mat-radio-button [value]="true">Entregado</mat-radio-button> <mat-radio-button [value]="false">No entregado</mat-radio-button> <mat-error *ngIf="hasError('estado_pedido', 'required')">Campo obligatorio</mat-error> </mat-radio-group> <!-- User ID field --> <div formGroupName="user" class="row"> <div class="col-6"> <div class="form-group"> <mat-form-field> <mat-label>User ID:</mat-label> <input matInput formControlName="id" placeholder="User ID" required readonly> </mat-form-field> {{pedido.user.nombre}} {{pedido.user.apellido1}} </div> </div> <div class="col-4"> <button style="margin-bottom: 10px" class="btn btn-primary" type="button" (click)="onShowUsersSelection()"> <i class="fa-solid fa-person-circle-plus"></i> </button> </div> </div> <div class="text-center mt-5"> <button class="btn btn-primary" type="submit">Guardar</button> </div> </form> </div>
import src.utils.data_processing as dp import numpy as np from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler, FunctionTransformer from sklearn.compose import ColumnTransformer class Processing(object): def __init__(self): train, test = dp.loadData() self.train = train.set_index('Id') self.test = test.set_index('Id') self.missing_values_columns = dp.getSummaryForMissingValues(train) self.missing_values_columns = self.missing_values_columns[self.missing_values_columns > 10].index # columns observed from the data visualisation self.high_corr_columns = ['GarageArea', 'TotRmsAbvGrd', '1stFlrSF'] self._filterColumns(self.train) self._filterColumns(self.test) def _filterColumns(self, df): # drop missing value columns df.drop(self.missing_values_columns, axis=1, inplace=True) # drop highly correlated columns columns = list(filter(lambda col: col in df.columns, self.high_corr_columns)) df.drop(columns, axis=1, inplace=True) @staticmethod def getPipeline(df): """ returns preprocessing Pipeline :param df: dataframe :return: """ # in numerical features replace missing values with median and standardize values numerical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy="median")), ('scaler', StandardScaler()) ]) # in categorical features replace missing values with most frequent occurring value and transform to one shot format categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore', sparse=False)) ]) categorical_features = df.select_dtypes(include=["object", "category"]).columns numerical_features = df.select_dtypes(include=[np.number]).columns numerical_cols = numerical_features categorical_cols = categorical_features # combine both transformers preprocessor = ColumnTransformer( transformers=[ ('num', numerical_transformer, numerical_cols), ('cat', categorical_transformer, categorical_cols), ], remainder="passthrough" ) return Pipeline(steps=[('preprocessor', preprocessor)])
// Cineware SDK // // (c) MAXON Computer GmbH, all rights reserved // #ifndef C4D_RENDERDATA_H__ #define C4D_RENDERDATA_H__ #include "c4d_baselist4d.h" #include "c4d_rootvideopost.h" #include "c4d_rootmultipass.h" namespace cineware { #pragma pack (push, 8) class BaseVideoPost; class MultipassObject; //---------------------------------------------------------------------------------------- /// Contains a container with all the render settings/options.\n /// Several render data instances can be added to a document. The active one will be used for rendering. /// @addAllocFreeNote /// @see @C4D Render Settings dialog and its documentation for more information. /// Render settings in @C4D are description based and are defined in @em parameter_ids\drendersettings.h //---------------------------------------------------------------------------------------- class RenderData : public BaseList4D { INSTANCEOF(RenderData, BaseList4D) RootVideoPost mp_posteffect; RootMultipass mp_multipass; BaseContainer inheritance_container; protected: RenderData(); public: /// @name Alloc/Free /// @{ //---------------------------------------------------------------------------------------- /// @allocatesA{render data} /// @return @allocReturn{render data} //---------------------------------------------------------------------------------------- static RenderData* Alloc(); //---------------------------------------------------------------------------------------- /// @destructsAlloc{render data} /// @param[in,out] rd @theToDestruct{render data} //---------------------------------------------------------------------------------------- static void Free(RenderData*& rd); //---------------------------------------------------------------------------------------- /// Gets the object type for a render data. /// @note Always returns @ref Rbase. /// @return The object type for a RenderData. //---------------------------------------------------------------------------------------- virtual Int32 GetType() const; /// @} /// @name Navigation /// @{ //---------------------------------------------------------------------------------------- /// Gets the next render data in the list. /// @return The next render data, or @formatConstant{nullptr} if there is none. @cinewareOwnsPointed{render data} //---------------------------------------------------------------------------------------- RenderData* GetNext(); //---------------------------------------------------------------------------------------- /// Gets the previous render data in the list. /// @return The previous render data, or @formatConstant{nullptr} if there is none. @cinewareOwnsPointed{render data} //---------------------------------------------------------------------------------------- RenderData* GetPred(); //---------------------------------------------------------------------------------------- /// Gets the parent render data of the list node. /// @return The parent render data, or @formatConstant{nullptr} if there is none. @cinewareOwnsPointed{render data} //---------------------------------------------------------------------------------------- RenderData* GetUp(); //---------------------------------------------------------------------------------------- /// Gets the first child render data of the list node. /// @return The first child render data, or @formatConstant{nullptr} if there is none. @cinewareOwnsPointed{render data} //---------------------------------------------------------------------------------------- RenderData* GetDown(); //---------------------------------------------------------------------------------------- /// Gets the last child render data of the list node. /// @return The last child render data, or @formatConstant{nullptr} if there is none. @cinewareOwnsPointed{render data} //---------------------------------------------------------------------------------------- RenderData* GetDownLast(); /// @} /// @name VideoPost List /// @{ //---------------------------------------------------------------------------------------- /// Gets the first video post of the render settings. /// @return The first video post. @theOwnsPointed{render data,video post} //---------------------------------------------------------------------------------------- BaseVideoPost* GetFirstVideoPost(); //---------------------------------------------------------------------------------------- /// Inserts video post @formatParam{pvp} into the render settings.\n /// The insertion position can be specified by the @formatParam{pred} parameter, inserting video post @formatParam{pvp} below it. /// @param[in] pvp The video post to insert. The render data takes over the ownership of the pointed video post. /// @param[in] pred The video post to insert @formatParam{pvp} after, or @formatConstant{nullptr} to insert it first. @callerOwnsPointed{video post} //---------------------------------------------------------------------------------------- void InsertVideoPost(BaseVideoPost* pvp, BaseVideoPost* pred); //---------------------------------------------------------------------------------------- /// Inserts @formatParam{pvp} as the last video post in the render settings. /// @param[in] pvp The video post to insert. The render data takes over the ownership of the pointed video post. //---------------------------------------------------------------------------------------- void InsertVideoPostLast(BaseVideoPost* pvp); /// @} /// @name Multipass List /// @{ //---------------------------------------------------------------------------------------- /// Gets the first multipass channel of the render settings.\n. /// @return The first multipass channel, or @formatConstant{nullptr} if no multipass channels are contained in the render setting. @theOwnsPointed{render data,multipass channel} //---------------------------------------------------------------------------------------- MultipassObject* GetFirstMultipass(); //---------------------------------------------------------------------------------------- /// Inserts multipass channel @formatParam{pmp} into the render settings.\n /// The insertion position can be specified by the @formatParam{pred} parameter, inserting multipass channel @formatParam{pmp} below it. /// @param[in] pmp The multipass channel to insert. The render data takes over the ownership of the pointed object. /// @param[in] pred The multipass channel to insert @formatParam{pvp} after, or @formatConstant{nullptr} to insert it first. @callerOwnsPointed{multipass channel} //---------------------------------------------------------------------------------------- void InsertMultipass(MultipassObject* pmp, MultipassObject* pred); //---------------------------------------------------------------------------------------- /// Inserts @formatParam{pmp} as last the multipass channel into the render settings. /// @param[in] pmp The multipass channel to insert. The render data takes over the ownership of the pointed multipass channel. //---------------------------------------------------------------------------------------- void InsertMultipassLast(MultipassObject* pmp); /// @} /// @name Multipass List /// @{ //---------------------------------------------------------------------------------------- /// Gets the resolution and aspect ratio of the render settings. /// @param[out] width Assigned the render width. /// @param[out] height Assigned the render height. /// @param[out] pixelAspect Assigned the pixel aspect ratio. /// @param[out] filmAspect Assigned the film aspect ratio. //---------------------------------------------------------------------------------------- void GetResolution(Float& width, Float& height, Float& pixelAspect, Float& filmAspect); //---------------------------------------------------------------------------------------- /// Sets the resolution and aspect ratio of the render settings. /// @param[in] width The render width to set. /// @param[in] height The render height to set. /// @param[in] pixelAspect The render pixel aspect ratio to set. /// @param[in] filmAspect The render film aspect ratio to set. //---------------------------------------------------------------------------------------- void SetResolution(Float width, Float height, Float pixelAspect, Float filmAspect); /// @} /// @name Multipass List /// @{ //---------------------------------------------------------------------------------------- /// Gets the animation settings of the render data. /// @param[out] fseq Assigned the frame sequence: @ref RDATA_FRAMESEQUENCE. /// @param[out] fps Assigned the frame rate (Frames per Second). /// @param[out] start Assigned the start time. /// @param[out] end Assigned the end time. /// @param[out] field Assigned the interlace field: @ref RDATA_FIELD. //---------------------------------------------------------------------------------------- void GetAnimationSettings(Int32& fseq, Float& fps, BaseTime& start, BaseTime& end, Int32& field); //---------------------------------------------------------------------------------------- /// Sets the animation settings of the render data. /// @param[in] fseq The frame sequence to set set: @ref RDATA_FRAMESEQUENCE. /// @param[in] fps The frame rate (Frames per Second) to set. /// @param[in] start The start time to set. /// @param[in] end The end time to set. /// @param[in] field The interlace field to set: @ref RDATA_FIELD. //---------------------------------------------------------------------------------------- void SetAnimationSettings(Int32 fseq, Float fps, BaseTime start, BaseTime end, Int32 field); /// @} // LONG fseq: RDATA_FRAMESEQUENCE_MANUAL, RDATA_FRAMESEQUENCE_CURRENTFRAME, RDATA_FRAMESEQUENCE_ALLFRAMES, RDATA_FRAMESEQUENCE_PREVIEWRANGE // LONG field: RDATA_FIELD_NONE, RDATA_FIELD_EVEN, RDATA_FIELD_ODD /// @name Color Profile /// @{ //---------------------------------------------------------------------------------------- /// Sets the RenderData to use @C4D default linear color profile. //---------------------------------------------------------------------------------------- void SetImageColorProfileToDefaultLinearRGB(); //---------------------------------------------------------------------------------------- /// Sets the RenderData to use @C4D default linear grayscale color profile. //---------------------------------------------------------------------------------------- void SetImageColorProfileToDefaultLinearGray(); //---------------------------------------------------------------------------------------- /// Sets the RenderData to use @C4D default sRGB color profile. //---------------------------------------------------------------------------------------- void SetImageColorProfileToDefaultSRGB(); //---------------------------------------------------------------------------------------- /// Sets the RenderData to use @C4D default sRGB grayscale color profile. //---------------------------------------------------------------------------------------- void SetImageColorProfileToDefaultSGray(); /// @} /// @name Clone /// @{ //---------------------------------------------------------------------------------------- /// Gets a clone/copy of the render data. /// @param[in] flags Flags for the clone. /// @param[in] trn An alias translator for the operation. Can be @formatConstant{nullptr}. @callerOwnsPointed{alias translator} /// @return The cloned render data. @callerOwnsPointed{render data} //---------------------------------------------------------------------------------------- virtual BaseList2D* GetClone(COPYFLAGS flags, AliasTrans* trn); /// @} /// @name Private /// @{ //---------------------------------------------------------------------------------------- /// @markPrivate //---------------------------------------------------------------------------------------- virtual Bool CopyToX(PrivateChunk* dst, COPYFLAGS flags, AliasTrans* trn); //---------------------------------------------------------------------------------------- /// @markPrivate //---------------------------------------------------------------------------------------- virtual Bool HandleSubChunk (HyperFile* hf, Int32 id, Int32 level); //---------------------------------------------------------------------------------------- /// @markPrivate //---------------------------------------------------------------------------------------- virtual Bool Write(HyperFile* hf); //---------------------------------------------------------------------------------------- /// @markPrivate //---------------------------------------------------------------------------------------- virtual Bool GetDParameter(const DescID& id, GeData& t_data); //---------------------------------------------------------------------------------------- /// @markPrivate //---------------------------------------------------------------------------------------- virtual Bool SetDParameter(const DescID& id, const GeData& t_data); /// @} }; #pragma pack (pop) } #endif // C4D_RENDERDATA_H__
// widgets/bottom_bar.dart import 'package:flutter/material.dart'; class BottomBar extends StatelessWidget { final int selectedIndex; final Function(int) onItemTapped; const BottomBar({super.key, required this.selectedIndex, required this.onItemTapped}); @override Widget build(BuildContext context) { return BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.cloud), label: 'Currently', ), BottomNavigationBarItem( icon: Icon(Icons.calendar_today), label: 'Today', ), BottomNavigationBarItem( icon: Icon(Icons.view_week), label: 'Weekly', ), ], currentIndex: selectedIndex, selectedItemColor: Colors.amber[800], onTap: onItemTapped, ); } }
from keymgmt.models import SSHKey, Environment, Host, SSHAccountAvailable import os import requests import glob from collections import OrderedDict from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.conf import settings class ImportPuppetdb: def __init__(self): self.settings = self.get_settings() def get_settings(self): if hasattr(settings, 'PUPPETDB') is False: raise Exception("Could not find configuration PUPPETDB in settings") return settings.PUPPETDB def users(self): users = [] puppetdb_users = self._get('/resources/User') for user in puppetdb_users: users.append(user['title']) users = list(OrderedDict.fromkeys(users)) return users def nodes(self): nodes = [] puppetdb_nodes = self._get('/nodes') for node in puppetdb_nodes: nodes.append( { 'name': node["certname"], 'ip': self.node_ipaddress(node["certname"]), 'env': node["catalog-environment"] } ) return nodes def node_ipaddress(self, node): ip = None try: result = self._get('/nodes/' + node + '/facts/ipaddress') ip = result[0]["value"] except: """ we don't care if we found no ip address """ pass return ip def _url(self): if self.settings['SSL_KEY'] is None and self.settings['SSL_CERT'] is None: proto = 'http' else: proto = 'https' return proto + '://' + self.settings['HOST'] + ':' + str(self.settings['PORT']) + '/v4' def _get(self, query, params=None): headers = { 'Content-Type': 'application/json' } url = self._url() + query try: req = requests.get(url, params=params, headers=headers, verify=self.settings['SSL_VERIFY'], cert=(self.settings['SSL_CERT'], self.settings['SSL_KEY']), timeout=self.settings['TIMEOUT'] ) body = req.json() if body is not None: return body else: raise Exception("no body returned by query: " + url) except: print("Error: with connecting to PuppetDB") raise class ImportSSHAccountAvailable: def __init__(self, accounts): self.accounts = accounts self.import_success = [] self.import_already = [] self.import_error = [] def import_names(self): for account in self.accounts: self.create_accountavailable(account) def create_accountavailable(self, name): try: SSHAccountAvailable.objects.get(name=name) self.import_already.append(name) return except ObjectDoesNotExist: try: account = SSHAccountAvailable(name=name) account.clean() account.full_clean() account.save() self.import_success.append(name) except ValidationError: self.import_error.append(name) class ImportHost: def __init__(self, file): self.filename = file self.content = [] self.import_errors = [] self.import_ok = [] self.import_already = [] def import_host(self): for host in self.content: env = self.create_or_return_env(host['env']) if env is not None: try: Host.objects.get(name=host['name']) self.import_already.append(host['name']) continue except: pass chost = self.create_host(host['name'], env, host['ip']) if chost is not None: self.import_ok.append(host['name']) else: self.import_errors.append(host['name']) else: self.import_errors.append(host['name']) def create_host(self, hostname, env, ip): try: host = Host(name=hostname, environment=env, ipaddress=ip) host.clean() host.full_clean() host.save() return host except ValidationError: pass def create_or_return_env(self, envname): try: env = Environment.objects.get(name=envname) except ObjectDoesNotExist: env = Environment(name=envname) try: env.clean() env.full_clean() env.save() except ValidationError: env = None return env def split_line(line): host = { 'env': 'production', 'ip': None } line = line.strip().rstrip() arr = line.split(',', maxsplit=2) if len(arr) == 0 or line == '': return None host['name'] = arr[0].strip() try: if arr[1].strip() != '': host['env'] = arr[1].strip() except IndexError: pass try: if arr[2].strip() != '': host['ip'] = arr[2].strip() except IndexError: pass return host def read_file(self): with open(self.filename) as f: for line in f: self.content.append(ImportHost.split_line(line)) class ImportSSHKey: def __init__(self, options): self.option_with_errors = [] self.sshkeys = [] self.sshkeys_added = [] self.sshkeys_added_already = [] self.sshkeys_added_errors = [] self.parse_option(options) self.make_uniq() def add_keys_to_db(self): for key in self.sshkeys: sshkey_basename = os.path.basename(key) name = SSHKey.filename2name(sshkey_basename) try: SSHKey.objects.get(name=name) self.sshkeys_added_already.append(key) continue except ObjectDoesNotExist: skey = SSHKey(name=name, sshkey=ImportSSHKey.ssh_read_key(key)) try: skey.clean() skey.full_clean() skey.save() self.sshkeys_added.append(key) except ValidationError: self.sshkeys_added_errors.append(key) def parse_option(self, options): for option in options: ftype = self.check_option_mode(option) if ftype == 'directory': self.check_directory(option) elif ftype == 'file': self.sshkeys.append(option) else: self.option_with_errors.append(option) def ssh_read_key(filename): content = open(filename).read() return content def check_option_mode(self, option): """ returns type of option: directory or file """ if os.path.isdir(option) and os.access(option, os.R_OK): return 'directory' elif os.path.isfile(option) and os.access(option, os.R_OK): return 'file' def check_directory(self, directory): for file in glob.glob(os.path.join(directory, '*.pub')): if self.check_option_mode(file): self.sshkeys.append(file) else: self.option_with_errors.append(file) def make_uniq(self): self.sshkeys = list(OrderedDict.fromkeys(self.sshkeys)) self.option_with_errors = list(OrderedDict.fromkeys(self.option_with_errors))