text
stringlengths
184
4.48M
# MapReduce Disadvantages and Spark Advantages ## MapReduce Disadvantages - **More complex, multi-pass analytics** - **More interactive ad-hoc queries** - **More real-time streaming processing** - **Problems in MapReduce** - Slow due to replication, serialization on disk I/O ## Complement in Spark - **10-100x faster than network and disk due to in-memory systems** - **Memory access is much faster than disk** - **Well suited to iterative and machine learning algorithms** - **Spark is also able to make use of HDFS** - Spark runs on HDFS through YARN, combining the benefits of both HDFS and Spark. ## Spark RDD (Resilient Distributed Datasets) - Distributed collections of objects that can be cached in memory across the cluster. - Manipulated through parallel operators. - Automatically recomputed on failure. - Immutable (read-only). - Partitioned collections of records. - Can contain any type of Python, Java, or Scala. - Note: When running RDD with Python, it may be slower compared to other languages. Hence, Dataset or Dataframe is recommended. ## Spark Functions - **Transformations:** Operations on RDDs that return a new RDD. - Map, filter, sort, join, distinct - **Actions:** Return a final value or write data to an external storage system. - Count, reduce, collect ## Lazy Evaluation - Means when calling a transformation on an RDD, the operation is not immediately performed. - Directed Acyclic Graph (DAG) is utilized for optimized execution. ## Spark Components - Spark depends on a cluster manager to launch executors and the driver. - The manager is a pluggable component in Spark. # Spark DataFrame Motivation Spark DataFrames serve as a powerful abstraction for simplifying distributed big data processing. The motivation behind using Spark DataFrames includes: - **Intuitive Coding:** Spark DataFrames allow for intuitive coding, making it easier for developers to write efficient code. - **Extension of Spark RDD API:** An extension of the Spark Resilient Distributed Dataset (RDD) API, Spark DataFrames are optimized for writing code more efficiently while retaining power. - **Spark SQL Module:** Programming abstraction is provided in the Spark SQL module, offering additional capabilities for structured data processing. ## RDD (Resilient Distributed Dataset) **Characteristics:** - RDD is a collection of distributed and immutable data elements. - Developers have low-level API control for explicit distribution and manipulation of data. - Lack of type safety, with errors discovered at runtime. **Use Cases:** - When low-level control is required. - Processing unstructured or undefined-structure data. - Handling complex data processing and transformations where user control is necessary. ## DataFrame **Characteristics:** - DataFrame is a logical distributed collection for processing structured data. - Utilizes Catalyst optimizer to optimize physical execution plans efficiently. - Provides a query language similar to SQL for easy data manipulation. **Use Cases:** - Processing structured data effectively. - When performance optimization and efficient execution plans are required. - When dealing with data using SQL-like syntax. ## Dataset **Characteristics:** - Dataset is a distributed collection with type safety for processing structured data. - Limited functionality in Python, primarily available in Java and Scala. - Extends DataFrame features to provide type safety. **Use Cases:** - When type safety is crucial, and development is in Java or Scala. - Extending DataFrame functionality while ensuring type safety. # Thoughts on Implementing Spark RDD When implementing Spark RDD, several considerations come to mind: - **Less Intuitive than Spark SQL or DataFrame:** - RDDs are less intuitive compared to Spark SQL or DataFrame, making them less straightforward to work with. - **Low-level and Some Drawbacks:** - RDDs are low-level and suffer from certain issues. - They express "how" a solution is achieved rather than "what." - **Lack of Optimization:** - RDDs cannot be optimized as effectively as Spark DataFrames, especially due to the absence of the Catalyst optimizer. - **Performance in Non-JVM Languages:** - RDDs may perform slowly in non-JVM languages like Python. ## Abstraction Level - **Managing Complexity:** - Abstraction levels help manage complexity in programming. - Higher abstraction levels allow simpler commands to perform more tasks. ## High-level Interface vs Low-level Interface - **Low-level API:** - Provides more detailed and less abstract functions, offering greater control to manipulate functions. - **High-level API:** - Is more generic and simpler. ## Type Safety - **Type Safety:** - RDDs and Datasets provide type safety, validating types during compilation and throwing errors for incorrect assignments. ## Spark SQL - **Beyond SQL:** - Spark SQL is not limited to SQL; it goes beyond handling structured data. - **Performance Advantage:** - Spark SQL outperforms traditional SQL as it leverages multiple nodes for processing compared to the single-core execution of SQL. - **Benefits:** - Writing less code. - Reading less data (fetching only necessary data). - Leveraging its own optimizer to handle complex tasks. # RDD vs DataFrame Code ## RDD: ```python Data = sc.textFile(…).split(“\t”) Data.map(lambda x: (x[0], [int(x[1]), 1])) \ .reduceByKey(lambda x, y: [x[0] + y[0], x[1] + y[1]]) \ .map(lambda x: [x[0], x[1][0] / x[1][1]]) \ .collect() ``` ## Dataframe: ```python sqlCtx.table(“people”).groupby(“name”).agg(“name, avg(“age)).collect() ``` - **따라서 RDD보다 DataFrame을 쓰는 이유는 Python으로 코딩했을 때 성능이 떨어지지 않고 코드도 좀더 간결해지고 직관적이게 되어서** ## Read Less Data** - **Spark SQL can help you read less data automatically** - Converting to more efficient formats - Using partitioning - Partitioning 을 통해서 필요한 데이터만 가져오는거 - 예를들어 년도별로 parition하면 필요한 연도만 가져오는거 - Pushing predicts into storage systems ## DataFrame Queries - Catalyst Optimizer - Constant Folding (Complier 최적화) - Runtime에서 처리하지 않고 Complier에서 상수값들을 미리 처리 - Predicate Pushdown - (조건절을 미리 계산, 필요한 데이터만 가져오는거) - Select col from data where ~~ 했을때 select col을 먼저하는게 아니라 where 절을 통해서 데이터를 골라내고 select을 하기 때문에 더 빠르다 - Column Pruning - 연산에 필요한 column만 읽는거
#include "Social.hpp" std::vector<std::shared_ptr<Usuario>> RedeSocial::getUsuarios() { return usuarios; } void RedeSocial::adicionarUsuario(std::shared_ptr<Usuario> usuario) { usuarios.push_back(usuario); } void RedeSocial::registrarUsuario(const std::string &nome_usuario, const std::string &nome) { std::shared_ptr<Usuario> novoUsuario = std::make_shared<Usuario>(nome_usuario, nome); usuarios.push_back(novoUsuario); } std::shared_ptr<Usuario> RedeSocial::buscarUsuario(const std::string &nome_usuario) { for (std::shared_ptr<Usuario> usuario : usuarios) { if (usuario->getNomeUsuario() == nome_usuario) { return usuario; } } return nullptr; // ponteiro nulo } std::vector<std::shared_ptr<Usuario>> RedeSocial::listarUsuarios() { return usuarios; } std::vector<std::shared_ptr<Tweet>> RedeSocial::listarTweets() { std::vector<std::shared_ptr<Tweet>> allTweets; for (std::shared_ptr<Usuario> usuario : usuarios) { for (std::shared_ptr<Tweet> tweet : usuario->getTweets()) { allTweets.push_back(tweet); } } return allTweets; } // Função para salvar dados de tweets em um arquivo void RedeSocial::salvarTweets(const std::string &nomeArquivo) { std::ofstream arquivo(nomeArquivo); if (arquivo.is_open()) { for (std::shared_ptr<Usuario> usuario : usuarios) { for (std::shared_ptr<Tweet> tweet : usuario->getTweets()) { arquivo << tweet->serializar(); } } arquivo.close(); std::cout << "Dados de tweets salvos em " << nomeArquivo << std::endl; } } // Função para carregar dados de tweets de um arquivo void RedeSocial::carregarTweets(const std::string &nomeArquivo) { std::vector<std::shared_ptr<Tweet>> tweets; std::ifstream arquivo(nomeArquivo); if (arquivo.is_open()) { std::string linha; while (std::getline(arquivo, linha)) { std::shared_ptr<Tweet> tweet = Tweet::desserializar(this, linha); // Adicionar tweet ao Usuario std::string nomeUsuarioAutor = tweet->getAutor()->getNomeUsuario(); std::shared_ptr<Usuario> autor = buscarUsuario(nomeUsuarioAutor); autor->adicionarTweet(tweet); // Mensagem de depuração para verificar o conteúdo do tweet carregado std::cout << "Tweet carregado: " << tweet->getConteudo() << std::endl; // Armazenar os tweets carregados temporariamente em um vetor tweets.push_back(tweet); } arquivo.close(); std::cout << "Dados de tweets carregados de " << nomeArquivo << std::endl; } else { std::cerr << "Erro ao abrir o arquivo " << nomeArquivo << " para carregar dados de tweets." << std::endl; } } // Função para salvar dados de usuários em um arquivo void RedeSocial::salvarUsuarios(const std::string &nomeArquivo) { std::ofstream arquivo(nomeArquivo); if (arquivo.is_open()) { for (std::shared_ptr<Usuario> usuario : usuarios) { arquivo << usuario->serializar(); } arquivo.close(); std::cout << "Dados de usuários salvos em " << nomeArquivo << std::endl; } else { std::cerr << "Erro ao abrir o arquivo " << nomeArquivo << " para salvar dados de usuários." << std::endl; } } // Função para carregar dados de usuários de um arquivo void RedeSocial::carregarUsuarios(const std::string &nomeArquivo) { std::ifstream arquivo(nomeArquivo); if (arquivo.is_open()) { std::string linha; while (std::getline(arquivo, linha)) { std::shared_ptr<Usuario> usuario = Usuario::desserializar(this, linha); usuarios.push_back(usuario); } arquivo.close(); std::cout << "Dados de usuários carregados de " << nomeArquivo << std::endl; } else { std::cerr << "Erro ao abrir o arquivo " << nomeArquivo << " para carregar dados de usuários." << std::endl; } } // Mostrar todos os usuários da rede social void RedeSocial::mostrarUsuarios() { for (std::shared_ptr<Usuario> usuario : usuarios) { std::cout << usuario->getNome() << " - " << usuario->getNomeUsuario() << std::endl; } } // Mostrar usuário específico void RedeSocial::mostrarUsuario(std::shared_ptr<Usuario> usuario) { std::cout << usuario->getNomeUsuario() << std::endl; std::cout << "Seguindo: "; for (std::shared_ptr<Usuario> seguido : usuario->getSeguindo()) { std::cout << seguido->getNomeUsuario() << " "; } std::cout << "Seguidores: "; for (std::shared_ptr<Usuario> seguidor : usuario->getSeguidores()) { std::cout << seguidor->getNomeUsuario() << " "; } }
// // UserListView.swift // GithubRepo // // Created by Yuki Shinohara on 2022/04/17. // import SwiftUI struct UserListView: View { init() { NavigationViewManager.setUpColor() } @StateObject private var viewModel = UserListViewModel() var body: some View { NavigationView { List { ForEach(viewModel.users) { user in NavigationLink { UserDetailView(viewModel: UserDetailViewModel(userName: user.userName)) } label: { UserRow(userData: User(id: user.id, userName: user.userName, avatarUrl: user.avatarUrl)) } } } .listStyle(.grouped) .navigationTitle("GitHub Users") .navigationBarTitleDisplayMode(.inline) } .onAppear { viewModel.getUsers() } } } struct UserListView_Previews: PreviewProvider { static var previews: some View { UserListView() } }
(ns aoc-clj.2015.day01 "Solution to https://adventofcode.com/2015/day/1") ;; Input parsing (defn parse [input] (map {\( 1 \) -1} (first input))) ;; Puzzle logic (defn final-floor "Compute the final floor as the sum of all the up and down moves" [input] (reduce + 0 input)) (defn first-pos-in-basement "Determine the first time the elevator reaches the basement by counting how many moves it takes until the sum becomes -1" [input] (->> (reductions + 0 input) (take-while #(not= -1 %)) count)) ;; Puzzle solutions (defn part1 "Given a list of `1`s and `-1`s, each representing an elevator moving up or down one floor, return the floor reached at the end of the moves." [input] (final-floor input)) (defn part2 "Given the same list of `1`s and `-1`s, each representing an elevator moving up or down one floor, return the position of the first move in the sequence where the elevator reaches the basement (at -1)" [input] (first-pos-in-basement input))
import { useState, useEffect } from 'react' const Clock = () => { const [date, setDate] = useState(new Date()); const refreshClock = () => { setDate(new Date()); } useEffect(() => { const interval = setInterval(refreshClock, 1000); return () => clearInterval(interval); }, []); return ( <div className="flex justify-center"> <span className="text-9xl m-auto select-none"> {date.toLocaleTimeString('en-US', { hourCycle: 'h23', hour: '2-digit', minute:'2-digit' })} </span> </div> ) } export default Clock
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:login/providers/login_provider.dart'; import 'package:login/screen/register.dart'; import 'package:login/main.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:login/controler/language_controller.dart'; void changeLanguage(BuildContext context, Locale locale) { context.setLocale(locale); } class LoginPage extends StatelessWidget { final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); void toggleTheme(BuildContext context) { final themeNotifier = Provider.of<ThemeNotifier>(context, listen: false); final languageController = Provider.of<LanguageController>(context, listen: false); themeNotifier.toggleTheme(); // Example: Change to Russian language changeLanguage(context, const Locale('ru', 'RU')); } @override Widget build(BuildContext context) { final loginProvider = Provider.of<LoginProvider>(context); final errorMessage = loginProvider.errorMessage; void login() { final String email = emailController.text; final String password = passwordController.text; loginProvider.login(context, email, password); } return Scaffold( appBar: AppBar( title: Text('Login').tr(), actions: [ IconButton( icon: Icon(Icons.brightness_4), onPressed: () { toggleTheme(context); }, ), IconButton( icon: Icon(Icons.language), onPressed: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Select Language').tr(), content: Column( mainAxisSize: MainAxisSize.min, children: [ ListTile( title: Text('English').tr(), onTap: () { changeLanguage(context, const Locale('en', 'US')); Navigator.pop(context); }, ), ListTile( title: Text('Russian').tr(), onTap: () { changeLanguage(context, const Locale('ru', 'RU')); Navigator.pop(context); }, ), ListTile( title: Text('Kazakh').tr(), onTap: () { changeLanguage(context, const Locale('kk', 'KZ')); Navigator.pop(context); }, ), ], ), ); }, ); }, ), ], ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /* Image.asset( 'assets/images/login_logo.png', width: 150, height: 150, ),*/ const SizedBox(height: 32.0), if (errorMessage != null) Container( padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), decoration: BoxDecoration( color: Colors.red.withOpacity(0.1), borderRadius: BorderRadius.circular(8.0), ), child: Text( errorMessage, style: const TextStyle(color: Colors.red), ), ), const SizedBox(height: 16.0), TextFormField( controller: emailController, decoration: InputDecoration( labelText: 'Email'.tr(), prefixIcon: Icon(Icons.email), ), ), const SizedBox(height: 16.0), TextFormField( controller: passwordController, obscureText: true, decoration: InputDecoration( labelText: 'Password'.tr(), prefixIcon: Icon(Icons.lock), ), ), const SizedBox(height: 24.0), ElevatedButton( onPressed: login, child: Text('Login').tr(), style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 32.0), ), ), const SizedBox(height: 16.0), TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => RegisterPage()), ); }, child: Text('Create an account').tr(), ), const SizedBox(height: 16.0), ElevatedButton( onPressed: () { loginProvider.setGuestMode(true); Navigator.pushReplacementNamed(context, '/home'); }, child: Text('Guest Mode').tr(), ), ], ), ), ); } }
package com.example.SpringREST.service; import com.example.SpringREST.entity.Contact; import com.example.SpringREST.entity.User; import com.example.SpringREST.model.request.CreateContactRequest; import com.example.SpringREST.model.response.ContactResponse; import com.example.SpringREST.model.response.WebResponse; import com.example.SpringREST.repository.ContactRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.server.ResponseStatusException; import java.util.Optional; import java.util.UUID; @Service public class ContactService { @Autowired private ContactRepository contactRepository; @Autowired private ValidationService validationService; @Transactional public ContactResponse create(User user, CreateContactRequest request){ validationService.validate(request); Contact contact = new Contact(); contact.setId(UUID.randomUUID().toString()); contact.setEmail(request.getEmail()); contact.setPhone(request.getPhone()); contact.setFirstName(request.getFirstName()); contact.setLastName(request.getLastName()); contact.setUser(user); contactRepository.save(contact); return ContactResponse.builder() .id(contact.getId()) .firstName(contact.getFirstName()) .lastName(contact.getLastName()) .email(contact.getEmail()) .phone(contact.getPhone()) .build(); } @Transactional(readOnly = true) public ContactResponse get(User user, String id){ Contact contact = contactRepository.findFirstByUserAndId(user, id) .orElseThrow(()-> new ResponseStatusException(HttpStatus.NOT_FOUND, "Contact Not Found")); return ContactResponse.builder() .id(contact.getId()) .firstName(contact.getFirstName()) .lastName(contact.getLastName()) .email(contact.getEmail()) .phone(contact.getPhone()) .build(); } @Transactional public ContactResponse update(User user, CreateContactRequest request, String id){ validationService.validate(request); Contact contact = contactRepository.findFirstByUserAndId(user, id) .orElseThrow(()-> new ResponseStatusException(HttpStatus.NOT_FOUND, "Contact Not Found")); contact.setFirstName(request.getFirstName()); contact.setLastName(request.getLastName()); contact.setEmail(request.getEmail()); contact.setPhone(request.getPhone()); contactRepository.save(contact); return ContactResponse.builder() .id(contact.getId()) .firstName(contact.getFirstName()) .lastName(contact.getLastName()) .email(contact.getEmail()) .phone(contact.getPhone()) .build(); } @Transactional public void deleteContact(User user, String id){ Contact contact = contactRepository.findFirstByUserAndId(user, id) .orElseThrow(()-> new ResponseStatusException(HttpStatus.NOT_FOUND, "Contact Not Found")); contactRepository.deleteById(id); } }
<script lang="ts"> import { playheadPosition, vibinState } from "../state.ts"; import { colorFromCssVar } from "../utils.ts"; // The application's $playheadPosition might be undefined, which is a valid state representing // "I'm probably not playing/paused right now". We want to display this as "--:--", but we // also want to allow the slider to render at the zero position. So we distinguish between the // application's $playheadPosition and this component's playheadPositionBindable ("bindable" // because it is guaranteed to be a number which can be bound to the slider's value). $: playheadPositionBindable = $playheadPosition || 0; $: progress = $playheadPosition && $vibinState.active_track?.duration ? ($playheadPosition / $vibinState.active_track.duration) * 100 : 0; $: canSeek = $vibinState.transport?.active_controls.includes("seek"); $: progressColor = canSeek ? colorFromCssVar("--accent-color-bright") : "#6c6f76"; $: progressRemainingColor = colorFromCssVar("--background-mid"); $: cssVarStyles = `--progress:${progress}%;` + `--progress-color:${progressColor};` + `--progress-remaining-color:${progressRemainingColor};`; const leadingZeros = new RegExp("^00:"); /** * Convert a duration in seconds into "hh:mm:ss", without the hh: if it would have been "00:". */ const prettyDuration = (duration: number | undefined) => typeof duration === "number" ? new Date(duration * 1000).toISOString().substring(11, 19).replace(leadingZeros, "") : "--:--"; </script> <div class="Playhead"> <span class="time">{prettyDuration($playheadPosition)}</span> <input style={cssVarStyles} class:can-seek={canSeek} disabled={!canSeek || typeof $playheadPosition === "undefined"} type="range" min="0" max={$vibinState.active_track?.duration} step="1" bind:value={playheadPositionBindable} on:click /> <span class="time">{prettyDuration($vibinState.active_track?.duration)}</span> </div> <style> .Playhead { flex-grow: 1; display: flex; align-items: center; gap: 5px; } .time { font-size: 0.7em; color: var(--text-mid); white-space: nowrap; } input[type="range"] { appearance: none; cursor: not-allowed; width: 100%; height: 3px; border: none; padding: 0; border-radius: 2px; background: linear-gradient( to right, var(--progress-color) 0%, var(--progress-color) var(--progress), var(--progress-remaining-color) var(--progress), var(--progress-remaining-color) 100% ); } input[type="range"]::-webkit-slider-thumb { appearance: none; } input[type="range"]::-webkit-slider-runnable-track { appearance: none; box-shadow: none; border: none; } .can-seek { & { cursor: pointer; } &::-webkit-slider-thumb { cursor: ew-resize; height: 10px; width: 4px; border-radius: 2px; background: var(--root-color); transition: background .3s ease-in-out; } &::-webkit-slider-runnable-track { cursor: pointer; } } </style>
/* import 'package:flutter/material.dart'; class WelcomePage extends StatefulWidget { final String name; final String email; final String phone; final ImageProvider<Object> imageProvider; WelcomePage({ Key? key, required this.name, required this.email, required this.phone, required this.imageProvider, }) : super(key: key); @override _WelcomePageState createState() => _WelcomePageState( name: name, email: email, phone: phone, imageProvider: imageProvider, ); } class _WelcomePageState extends State<WelcomePage> { String name; String email; String phone; ImageProvider<Object> imageProvider; _WelcomePageState({ required this.name, required this.email, required this.phone, required this.imageProvider, }); @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( backgroundColor: const Color(0xFFBB94AF), title: Text('Howdy $name!!'), ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: [ DrawerHeader( decoration: const BoxDecoration( color: Color(0xFF2C3E50), image: DecorationImage( image: AssetImage('assets/images/side.jpg'), fit: BoxFit.cover, ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CircleAvatar( radius: 50.0, backgroundColor: Colors.transparent, backgroundImage: imageProvider, ), const SizedBox(height: 10.0), Padding( padding: const EdgeInsets.only(left: 30.0), child: Text( name, style: const TextStyle( color: Colors.white, fontSize: 18.0, fontWeight:FontWeight.bold ), ), ), ], ), ), ListTile( title: Text( '$email', style: const TextStyle( color: Color(0xFF2C3E50), fontSize: 16.0, fontWeight:FontWeight.bold ), ), leading: const Icon(Icons.email, color: Color(0xFF2C3E50), ), ), ListTile( title: Text('$phone', style: const TextStyle( color: Color(0xFF2C3E50), fontSize: 16.0, fontWeight:FontWeight.bold ), ), leading: const Icon(Icons.phone, color: Color(0xFF2C3E50), ), ), ], ), ), ), ); } } */
import * as VisibilidadeEditActions from '../actions/visibilidade-edit.actions'; export interface VisibilidadeEditState { visibilidadeId: number; saving: boolean; errors: any; loading: boolean; loaded: any; } export const visibilidadeEditInitialState: VisibilidadeEditState = { visibilidadeId: null, saving: false, errors: false, loading: false, loaded: false }; export const visibilidadeEditReducer = ( state = visibilidadeEditInitialState, action: VisibilidadeEditActions.VisibilidadeEditActionsAll ): VisibilidadeEditState => { switch (action.type) { case VisibilidadeEditActions.GET_VISIBILIDADE: { return { ...state, visibilidadeId: null, loading: true }; } case VisibilidadeEditActions.GET_VISIBILIDADE_SUCCESS: { return { ...state, visibilidadeId: action.payload.visibilidadeId, loaded: action.payload.loaded, loading: false }; } case VisibilidadeEditActions.CREATE_VISIBILIDADE: { return { ...state, visibilidadeId: null, loaded: { id: 'visibilidadeHandle', value: 'criar' }, loading: false }; } case VisibilidadeEditActions.GET_VISIBILIDADE_FAILED: { return { ...state, loading: false }; } case VisibilidadeEditActions.SAVE_VISIBILIDADE: { return { ...state, saving: true, errors: false }; } case VisibilidadeEditActions.SAVE_VISIBILIDADE_SUCCESS: { return { ...state, saving: false, errors: false }; } case VisibilidadeEditActions.SAVE_VISIBILIDADE_FAILED: { return { ...state, saving: false, errors: action.payload }; } case VisibilidadeEditActions.UNLOAD_STORE: { return { ...visibilidadeEditInitialState }; } default: return state; } }
<template> <VueLoading :active="isLoading" :z-index="1060"> <Loadingitem /> </VueLoading> <section class="section-main-banner"> <img class="d-none d-md-block w-100" src="../../assets/image/productbanner0005.png" alt="banner" /> <img class="d-block d-md-none w-100" src="../../assets/image/phone-banner/banner-p05.png" alt="banner" /> </section> <section class="section-bread"> <div class="section-bread-main"> <ol class="bread-list d-flex align-items-center"> <li class="bread-list-item"> <div class="section-bread-pic"> <img width="20" src="../../assets/image/icon/home.svg" alt="homepic" /> </div> </li> <li class="bread-list-item" aria-current="page"> <a>訂單</a> </li> </ol> </div> </section> <section class="section-product"> <div class="section-product-main"> <div class="section-product-title d-flex align-items-center"> <div class="product-title-pic"> <img src="../../assets/image/motohead.png" alt="" /> </div> <h2>您的訂單</h2> </div> <div class="my-5 row justify-content-center"> <form class="col-md-6 userOrder border" @submit.prevent="payOrder"> <table class="table align-middle"> <thead> <th>品名</th> <th>數量</th> <th>單價</th> </thead> <tbody> <tr v-for="item in order.products" :key="item.id"> <td>{{ item.product.title }}</td> <td>{{ item.qty }}/{{ item.product.unit }}</td> <td>{{ item.product.price }}</td> <td class="text-end">{{ item.final_total }}</td> </tr> </tbody> <tfoot> <tr> <td></td> <td colspan="2" class="text-end">總計</td> <td class="text-end">{{ order.total }}</td> </tr> </tfoot> </table> <table class="table"> <tbody> <tr> <th width="100">Email</th> <td>{{ order.user.email }}</td> </tr> <tr> <th>姓名</th> <td>{{ order.user.name }}</td> </tr> <tr> <th>收件人電話</th> <td>{{ order.user.tel }}</td> </tr> <tr> <th>收件人地址</th> <td>{{ order.user.address }}</td> </tr> <tr> <th>付款狀態</th> <td> <span v-if="!order.is_paid">尚未付款</span> <span v-else class="text-success">付款完成</span> </td> </tr> </tbody> </table> <div class="text-end" v-if="order.is_paid === false"> <button type="submit" class="btn btn-danger">確認付款去</button> </div> </form> </div> </div> </section> </template> <script> import { mapActions } from "pinia"; import { useToastMessageStore } from "@/stores/toastMessage"; const { VITE_API, VITE_APIPATH } = import.meta.env; export default { data() { return { order: { user: {}, }, orderId: "", }; }, methods: { ...mapActions(useToastMessageStore, ["pushMessage"]), getOrder() { const url = `${VITE_API}api/${VITE_APIPATH}/order/${this.orderId}`; this.isLoading = true; this.$http .get(url) .then((response) => { this.order = response.data.order; this.isLoading = false; }) .catch((error) => { this.isLoading = false; this.pushMessage({ style: "danger", title: "取得訂單失敗", content: error.response.data.message, }); }); }, payOrder() { const url = `${VITE_API}api/${VITE_APIPATH}/pay/${this.orderId}`; this.isLoading = true; this.$http .post(url) .then(() => { this.isLoading = false; this.getOrder(); }) .catch((error) => { this.isLoading = false; this.pushMessage({ style: "danger", title: "付款失敗", content: error.response.data.message, }); }); }, }, created() { this.orderId = this.$route.params.orderId; this.getOrder(); }, }; </script> <style scoped> .userOrder { padding: 1rem; border: 1px dashed #59565600; border-radius: 11px; box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px; } </style>
package com.aurine.cloudx.estate.controller; import com.aurine.cloudx.estate.entity.ProjectInspectCheckinDetail; import com.aurine.cloudx.estate.service.ProjectInspectCheckinDetailService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pig4cloud.pigx.common.core.util.R; import com.pig4cloud.pigx.common.log.annotation.SysLog; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; /** * 巡检点签到明细(ProjectInspectCheckinDetail)表控制层 * * @author 王良俊 * @since 2020-08-04 10:08:52 */ @RestController @RequestMapping("projectInspectCheckinDetail") @Api(value = "projectInspectCheckinDetail", tags = "巡检点签到明细") public class ProjectInspectCheckinDetailController { /** * 服务对象 */ @Resource private ProjectInspectCheckinDetailService projectInspectCheckinDetailService; /** * 分页查询所有数据 * * @param page 分页对象 * @param projectInspectCheckinDetail 查询实体 * @return 所有数据 */ @GetMapping("/page") @ApiOperation(value = "分页查询", notes = "分页查询projectInspectCheckinDetail所有数据") public R selectAll(Page<ProjectInspectCheckinDetail> page, ProjectInspectCheckinDetail projectInspectCheckinDetail) { return R.ok(this.projectInspectCheckinDetailService.page(page, new QueryWrapper<>(projectInspectCheckinDetail))); } /** * 通过主键查询单条数据 * * @param id 主键 * @return 单条数据 */ @GetMapping("{id}") @ApiOperation(value = "通过id查询", notes = "通过主键查询projectInspectCheckinDetail单条数据") public R selectOne(@PathVariable Integer id) { return R.ok(this.projectInspectCheckinDetailService.getById(id)); } /** * 通过巡检任务明细id获取其签到详情 * * @param detailId 主键 * @return 签到详情对象列表 */ @GetMapping("listByDetailId/{detailId}") @SysLog("使用巡检任务明细id获取其签到详情列表") @ApiOperation(value = "通过id查询", notes = "使用巡检任务明细id获取其签到详情列表") public R listByDetailId(@PathVariable("detailId") String detailId) { return R.ok(this.projectInspectCheckinDetailService.list(new QueryWrapper<ProjectInspectCheckinDetail>().lambda() .eq(ProjectInspectCheckinDetail::getDetailId, detailId))); } /** * 新增数据 * * @param projectInspectCheckinDetail 实体对象 * @return 新增结果 */ @PostMapping @ApiOperation(value = "新增数据", notes = "新增projectInspectCheckinDetail数据") public R insert(@RequestBody ProjectInspectCheckinDetail projectInspectCheckinDetail) { return R.ok(this.projectInspectCheckinDetailService.save(projectInspectCheckinDetail)); } /** * 修改数据 * * @param projectInspectCheckinDetail 实体对象 * @return 修改结果 */ @PutMapping @ApiOperation(value = "修改数据", notes = "修改projectInspectCheckinDetail数据") public R update(@RequestBody ProjectInspectCheckinDetail projectInspectCheckinDetail) { return R.ok(this.projectInspectCheckinDetailService.updateById(projectInspectCheckinDetail)); } /** * 删除数据 * * @param idList 主键结合 * @return 删除结果 */ @DeleteMapping @ApiOperation(value = "删除数据", notes = "通过id删除projectInspectCheckinDetail数据") public R delete(@RequestParam("idList") List<Integer> idList) { return R.ok(this.projectInspectCheckinDetailService.removeByIds(idList)); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hoo Bank</title> <!-- Normalize to render all elements to different browsers --> <link rel="stylesheet" href="assets/css/normalize.css"> <!-- Poppins Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap" rel="stylesheet"> <!-- CSS Style --> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="assets/css/mediaQueries.css"> <!-- Box Icons --> <link rel="stylesheet" href="https://unpkg.com/boxicons@latest/css/boxicons.min.css"> <!-- Font Awesome --> <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> --> </head> <body> <div id="outside"> </div> <!-- Home --> <section class="home" id="home"> <header id="page-header"> <div class="container"> <a href="#home" class="logo"> <div class="logo-img"> <img class="main-icon" src="assets/imgs/main-logo.png" alt="Icon Of Page"> <img class="top-inner-icon" src="assets/imgs/inner-top-logo.png" alt="Inner Icon"> <img class="inner-icon" src="assets/imgs/inner-bottom-logo.png" alt="Inner Icon"> </div> <p>HooBank</p> </a> <i id="menuIcon" class='bx bx-menu'></i> <ul class="navbar"> <li><a href="#home">Home</a></li> <li><a href="#about">About Us</a></li> <li><a href="#features">Features</a></li> <li><a href="#solutions">Solutions</a></li> </ul> </div> </header> <div class="landing"> <div class="container"> <div class="text"> <h1 class="landing__text"> The Next <br> <span>Generation</span> <br> Payment Method. <a href="#" class="landing-btn"> <p class="arrow-container"> Get <img class="arrow" src="assets/imgs/top-right-arr.png" alt=""> </p> <p>Started</p> </a> </h1> <p class="landing__desc"> Our team of experts uses a methodology to identify the credit cards most likely to fit your needs. We examine annual percentage rates, annual fees. </p> </div> <!-- End Text --> <div class="landing__imgs"> <img class="blue-gradient" src="assets/imgs/blue-gradient-ball.png" alt=""> <img class="cards" src="assets/imgs/cards.png" alt=""> <img src="assets/imgs/robot-hand-background-presenting-technology-gesture 1.png" alt=""> <img class="small-ball" src="assets/imgs/small-ball.png" alt="Small Ball"> <img class="intermediate-ball" src="assets/imgs/intermediate-ball.png" alt="Intermediate Ball"> <img class="big-ball" src="assets/imgs/white-ball.png" alt="Big Ball"> </div> </div> <!-- Ellipses --> <img src="assets/imgs/home-left-ellipse.png" alt="" class="left-ellipse"> </div> <article class="deals"> <div class="container"> <div class="box"> <h2>3800+</h2> <p>User Active</p> </div> <span class="line"></span> <div class="box"> <h2>230+</h2> <p>TRUSTED BY COMPANY</p> </div> <span class="line"></span> <div class="box"> <h2>$230M+</h2> <p>TRANSACTION</p> </div> </div> </article> </section> <!-- Business --> <main class="infos" id="solutions"> <div class="container"> <div class="text"> <h2 class="title">You do the business, we’ll handle the money.</h2> <p class="desc"> With the right credit card, you can improve your financial life by building credit, earning rewards and saving money. But with hundreds of credit cards on the market. </p> <button class="started-btn">Get Started</button> </div> <ul class="usage"> <li> <div class="icon"> <i class='bx bxs-star' ></i> </div> <div class="usage-text"> <h3>Rewards</h3> <p>The best credit cards offer some tantalizing combinations of promotions and prizes</p> </div> </li> <li class="on"> <div class="icon"> <i class='bx bxs-check-shield'></i> </div> <div class="usage-text"> <h3>100% Secured</h3> <p>We take proactive steps make sure your information and transactions are secure.</p> </div> </li> <li> <div class="icon"> <i class='bx bxs-paper-plane'></i> </div> <div class="usage-text"> <h3>Balance Transfer</h3> <p>A balance transfer credit card can save you a lot of money in interest charges.</p> </div> </li> </ul> <!-- Ellipses --> <img src="assets/imgs/home-left-ellipse.png" alt="" class="left-ellipse"> </div> <div class="container reverse control"> <div class="text"> <h2 class="title">Easily control your billing & invoicing.</h2> <p class="desc"> Elit enim sed massa etiam. Mauris eu adipiscing ultrices ametodio aenean neque. Fusce ipsum orci rhoncus aliporttitor integer platea placerat. </p> <div class="brands"> <article class="brand"> <img src="assets/imgs/apple.png" alt="Apple Logo"> <div class="brand-text"> <span>Download on the</span> <h2>App Store</h2> </div> </article> <article class="brand"> <img src="assets/imgs/playstore-logo.png" alt="Playstore Logo"> <div class="brand-text"> <span class="upper">Get it One</span> <h2>Google Play</h2> </div> </article> </div> </div> <div class="img-holder"> <img src="assets/imgs/features.png" alt="Feature_Img"> </div> <!-- Ellipses --> <img src="assets/imgs/home-left-ellipse.png" alt="" class="left-ellipse"> </div> <div class="container features"> <div class="text"> <h2 class="title">Find a better card deal in few easy steps.</h2> <p class="desc"> Arcu tortor, purus in mattis at sed integer faucibus. Aliquet quis aliquet eget mauris tortor.ç Aliquet ultrices ac, ametau. </p> <button class="started-btn">Get Started</button> </div> <div class="img-holder"> <img src="assets/imgs/deal-img.png" alt="Deal"> </div> <!-- Ellipses --> <img src="assets/imgs/home-left-ellipse.png" alt="" class="left-ellipse"> </div> <section class="about" id="about"> <div class="container"> <h3 class="title">What people are saying about us</h3> <p class="desc"> Everything you need to accept card payments and grow your business anywhere on the planet. </p> </div> <div class="container"> <!-- Testimonial One --> <div class="box"> <img class="bouble-quotation" src="assets/imgs/double-quotation.png" alt="Double Quotation"> <p> Money is only a tool. It will take you wherever you wish, but it will not replace you as the driver. </p> <div class="person"> <img class="img-person" src="assets/imgs/person-1.png" alt="Person"> <div class="info"> <h4 class="name">Kate Pers</h4> <span class="job-title">Founder & Leader</span> </div> </div> </div> <!-- Testimonial Two --> <div class="box"> <img class="bouble-quotation" src="assets/imgs/double-quotation.png" alt="Double Quotation"> <p> Money makes your life easier. If you're lucky to have it, you're lucky. </p> <div class="person"> <img class="img-person" src="assets/imgs/person-2.png" alt="Person"> <div class="info"> <h4 class="name">Steve Mark</h4> <span class="job-title">Founder & Leader</span> </div> </div> </div> <!-- Testimonial Three --> <div class="box"> <img class="bouble-quotation" src="assets/imgs/double-quotation.png" alt="Double Quotation"> <p> It is usually people in the money business, finance, and international trade that are really rich. </p> <div class="person"> <img class="img-person" src="assets/imgs/person-3.png" alt="Person"> <div class="info"> <h4 class="name">Kenn Gallagher</h4> <span class="job-title">Founder & Leader</span> </div> </div> </div> </div> </section> </main> <!-- Partners --> <section class="partners"> <div class="container slider"> <div class="slide"> <img src="assets/imgs/partners/airbnb.png"> </div> <div class="slide"> <img src="assets/imgs/partners/binance.png"> </div> <div class="slide"> <img src="assets/imgs/partners/coinbase.png"> </div> <div class="slide drobbox"> <img src="assets/imgs/partners/dropbox-1.png" alt=""> <img src="assets/imgs/partners/dropbox-2.png" alt=""> </div> <div class="slide"> <img src="assets/imgs/partners/airbnb.png"> </div> <div class="slide"> <img src="assets/imgs/partners/binance.png"> </div> <div class="slide"> <img src="assets/imgs/partners/coinbase.png"> </div> <div class="slide drobbox"> <img src="assets/imgs/partners/dropbox-1.png" alt=""> <img src="assets/imgs/partners/dropbox-2.png" alt=""> </div> </div> </section> <!-- Services --> <section class="services" id="features"> <div class="container"> <div class="text"> <h2 class="title">Let’s try our service now!</h2> <p class="desc">Everything you need to accept card payments and grow your business anywhere on the planet.</p> </div> <button class="started-btn">Get Started</button> </div> </section> <!-- Page Footer --> <footer> <div class="container"> <div class="site-brand"> <a href="#home" class="logo"> <div class="logo-img"> <img class="main-brand" src="assets/imgs/footer-main-logo.png" alt="Footer Brand"> <img class="inner-brand" src="assets/imgs/footer-inner-logo.png" alt="Footer Inner Brand"> </div> <p>HooBank</p> </a> <p class="site-brand-desc">A new way to make the payments easy, reliable and secure.</p> </div> <ul class="links"> <h2>Useful Links</h2> <li><a href="#">Content</a></li> <li><a href="#">How it Works</a></li> <li><a href="#">Create</a></li> <li><a href="#">Explore</a></li> <li><a href="#">Terms & Services</a></li> </ul> <ul class="links"> <h2>Community</h2> <li><a href="#">Help Center</a></li> <li><a href="#">Partners</a></li> <li><a href="#">Suggestions</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Newsletters</a></li> </ul> <ul class="links"> <h2>Partners</h2> <li><a href="#">Our Partner</a></li> <li><a href="#">Become a Partner</a></li> </ul> </div> </footer> <div class="copyright"> <div class="container"> <p><span>Copyright &#169;</span> 2021 HooBank. All Rights Reserved.</p> <ul class="social"> <li><a href="#"><i class='bx bxl-instagram' ></i></a></li> <li><a href="#"><i class='bx bxl-facebook-circle' ></i></a></li> <li><a href="#"><i class='bx bxl-twitter' ></i></a></li> <li><a href="#"><i class='bx bxl-linkedin-square' ></i></a></li> </ul> </div> </div> <!-- My Script --> <script src="assets/js/main.js"></script> </body> </html>
#!/bin/bash # This is the script that is called when calling "qlever" from the command line. # The script is self-explanatory when you run it. Type ". qlever" for initial # configuration and then "qlever" or "qlever help" for initial help. # # © 2022, University of Freiburg, Chair of Algorithms and Data Structures # Author: Hannah Bast <bast@cs.uni-freiburg.de> ### ### STRUCTURE OF THIS SCRIPT ### ### 1. Definition of available actions (as bash functions) ### 2. Setup code when called with ". qlever" ### 3. Handle calls "qlever", "qlever help", "qlever help-install" ### 4. Settings (default + from Qleverfile + derived settings) ### 5. Process actions ### BLUE=$(printf "\033[34m") RED=$(printf "\033[31m") GRAY=$(printf "\033[37m") MAGENTA=$(printf "\033[35m") BOLD=$(printf "\033[1m") NORMAL=$(printf "\033[0m") QLEVER_CMD="${BASH_SOURCE[0]}" # Command of this script QLEVER_CMD_DIR=$(cd -- "$(dirname -- "${QLEVER_CMD}")" &> /dev/null && pwd) QLEVER_BIN_DIR=$(which ServerMain | sed 's|/ServerMain$||') QLEVERFILE_NEEDED=true SIMPLE_ACTIONS=:update:status:help:help-install:help-install-ubuntu-18:help-install-ubuntu-20:show-configs: if [[ ${SIMPLE_ACTIONS} == *:$*:* ]]; then QLEVERFILE_NEEDED=false; fi # Helper function to display simple markdown using ANSI escape codes. function display_markdown { sed -E "s/^# (.*)/${BOLD}\1${NORMAL}/g" \ | sed -E "s/\`([^\`]+)\`/${BLUE}\1${NORMAL}/g" } ### ### AVAILABLE ACTIONS (all available via autocompletion) ### function action_help { cat << "EOT" | display_markdown # QLEVER HELP The `qlever` script controls everything concerning QLever. Calling it without arguments always displays this information. Before using the script the first time in a particular shell and directory, type `. /path/to/qlever`. This will enable autocompletion, update your PATH, and create a default Qleverfile. # Qleverfile The Qleverfile configures everything: how to get the data, build an index, start the server, and all kinds of settings. Modify the default Qleverfile as you see fit. For some datasets, there are preconfigured QLeverfiles: to get one of those, type `qlever show-configs` and follow the instructions. # Actions On the command line, typing TAB after `qlever` gives you the available actions. You can also execute several actions with one command, for example "qlever index start log`. If you just want to see what an action does, but not exeute it, append "show", for example `qlever index start show`. # Binaries By default, the qlever script uses the official QLever docker image (settings USE_DOCKER and QLEVER_DOCKER_IMAGE in the Qleverfile). If you want to use the QLever binaries, you have to compile them on your machine. For instructions, type `qlever install-binaries`. EOT } function action_install_binaries { cat << "EOT" | display_markdown # QLEVER INSTALL BINARIES If you don't want to use docker for the actions "index" (building an index) and "start" (starting a server), you have to compile the binaries "IndexBuilderMain" and "ServerMain" on your machine. To use these binaries, in your Qleverfile set USE_DOCKER=false and QLEVER_BIN_DIR to the directory with your binaries. # Get a copy of the QLever code `git clone --recursive https://github.com/ad-freiburg/qlever qlever-code` `cd qlever-code` # On Ubuntu 18.04, 20.04, or 22.04 Just type `qlever help-install-ubuntu-22` (or ...-20 or ...-18) and follow the instructions. The call will create and show an INSTALL script, which you can then just execute. # On other operatings systems We are working on an INSTALL script for MacOS and WSL, analogous to the ones for Ubuntu above. In the meantime, look at one of the Ubuntu INSTALL scripts and adapt them as good as you can. EOT } SHOW= NOSHOW= INSTALL_UBUNTU_HELP_TEXT=$(cat << "EOT" | display_markdown The following command sequence has been written to a file INSTALL. If it looks OK to you, execute the sequence with `source ./INSTALL`. If there is a conflict with an existing libboost version, uninstall it and then run again. If you run out of RAM, use fewer cores for the last call to ninja, e.g., `ninja -j 3`. EOT ) function action_help_install_ubuntu_18 { echo "${INSTALL_UBUNTU_HELP_TEXT}" echo $SHOW curl -Gs https://raw.githubusercontent.com/ad-freiburg/qlever/master/Dockerfiles/Dockerfile.Ubuntu18.04 \ | sed -En 's/(add-apt|apt|tee)/sudo \1/g; s/^RUN //p' \ | sed '/^cmake/q' \ | sed -E 's/^(cmake.*)/mkdir -p build \&\& cd build\n\1\ncd ../' \ > INSTALL echo "${BLUE}$(cat INSTALL)${NORMAL}" } function action_help_install_ubuntu_20 { echo "${INSTALL_UBUNTU_HELP_TEXT}" echo $SHOW curl -Gs https://raw.githubusercontent.com/ad-freiburg/qlever/master/Dockerfiles/Dockerfile.Ubuntu20.04 \ | sed -En 's/(add-apt|apt|tee)/sudo \1/g; s/^RUN //p' \ | sed '/^cmake/q' \ | sed -E 's/^(cmake.*)/mkdir -p build \&\& cd build\n\1\ncd ../' \ > INSTALL echo "${BLUE}$(cat INSTALL)${NORMAL}" } function action_help_install_ubuntu_22 { echo "${INSTALL_UBUNTU_HELP_TEXT}" echo $SHOW curl -Gs https://raw.githubusercontent.com/ad-freiburg/qlever/master/Dockerfile \ | sed -En 's/(add-apt|apt|tee)/sudo \1/g; s/^RUN //p' \ | sed '/^cmake/q' \ | sed -E 's/^(cmake.*)/mkdir -p build \&\& cd build\n\1\ncd ../' \ > INSTALL echo "${BLUE}$(cat INSTALL)${NORMAL}" } function action_show_configs { cat << "EOT" | display_markdown The following pre-configured Qleverfiles are available. To get one of these in the current directory, type `. qlever <config-name>`. Beware that this will overwrite any Qleverfile that is already there. EOT CONFIGS_AVAILABLE=$($SHOW ls ${QLEVER_CMD_DIR}/Qleverfiles/Qleverfile.* | sed 's/^.*\/Qleverfile\.//' $NOSHOW) echo ${BLUE}${CONFIGS_AVAILABLE}${NORMAL} } function action_remove_data { echo "Removing files specified in RDF_FILES in Qleverfile ..." echo ls -l "${RDF_FILES}" $SHOW eval ${REMOVE_DATA_CMD} } function action_get_data { if [ -z "${GET_DATA_CMD}" ]; then echo "${RED}No GET_DATA_CMD specified in Qleverfile${NORMAL}" else echo "Getting data using GET_DATA_CMD from Qleverfile ..." echo eval $SHOW ${GET_DATA_CMD} fi } function action_index { if ls ${DB}.index.* > /dev/null 2>&1; then echo "${RED}Index exists, delete it first with \"qlever remove-index\" (add \"show\" to find out what gets deleted)${NORMAL}" else # # Prepend ulimit setting to INDEXER_CMD if input files are large. # if [ "$(du -bc ${RDF_FILES} | tail -1 | cut -f1)" -gt 1000000000 ]; then # export INDEXER_CMD="ulimit -Sn 1048576; ${INDEXER_CMD}" # fi # Create settings.json. if jq --version > /dev/null 2>&1; then echo ${SETTINGS_JSON} | jq -M '.' > ${DB}.settings.json else echo ${SETTINGS_JSON} > ${DB}.settings.json fi # Create prefix definitions if [ ! -z "${EXTRACT_PREFIXES}" ]; then eval $SHOW ${EXTRACT_PREFIXES} $NOSHOW; fi # Build index. eval ${INDEXER_CMD_PREFIX} $SHOW ${INDEXER_CMD} fi } function action_remove_index { $SHOW rm -f ${DB}.index.* ${DB}.vocabulary.* ${DB}.prefixes ${DB}.meta-data.json ${DB}.index-log.txt echo "The index files have been removed." } function action_index_stats { if [ ! -e ${DB}.index-log.txt ]; then echo "${RED}Need file \"${DB}.index-log.txt\"${NORMAL}"; return; fi $SHOW readarray -t T < <(sed -En '/INFO: (Processing|Done, total|Converting triples|Creating|Index build|Adding text index|DocsDB done)/p' ${DB}.index-log.txt | cut -c1-19) if [ "${#T[@]}" -lt "4" ]; then echo "${RED}Missing key lines in \"${DB}.index-log.txt\"${NORMAL}"; return; fi Ts=$(echo "($(date +%s -d "${T[-1]}") - $(date +%s -d "${T[0]}"))" | bc) if [ "${Ts}" -gt "3600" ]; then Tdiv=3600; Tunit="h"; else Tdiv=60; Tunit="min"; fi T1=$(echo "($(date +%s -d "${T[1]}") - $(date +%s -d "${T[0]}")) / ${Tdiv}" | bc -l) T2=$(echo "($(date +%s -d "${T[2]}") - $(date +%s -d "${T[1]}")) / ${Tdiv}" | bc -l) T3=$(echo "($(date +%s -d "${T[3]}") - $(date +%s -d "${T[2]}")) / ${Tdiv}" | bc -l) T4=$(echo "($(date +%s -d "${T[4]}") - $(date +%s -d "${T[3]}")) / ${Tdiv}" | bc -l) T5=$(echo "($(date +%s -d "${T[5]}") - $(date +%s -d "${T[4]}")) / ${Tdiv}" | bc -l) T6=$(echo "($(date +%s -d "${T[6]}") - $(date +%s -d "${T[5]}")) / ${Tdiv}" | bc -l) T7=$(echo "($(date +%s -d "${T[7]}") - $(date +%s -d "${T[6]}")) / ${Tdiv}" | bc -l) T8=$(echo "($(date +%s -d "${T[8]}") - $(date +%s -d "${T[7]}")) / ${Tdiv}" | bc -l) T9=$(echo "($(date +%s -d "${T[9]}") - $(date +%s -d "${T[8]}")) / ${Tdiv}" | bc -l) TT=$(echo "($(date +%s -d "${T[-1]}") - $(date +%s -d "${T[0]}")) / ${Tdiv}" | bc -l) echo "Time needed for the various phases of the index build" echo printf "%-23s : %5.1f ${Tunit}\n" "Parse input" ${T1} printf "%-23s : %5.1f ${Tunit}\n" "Build vocabularies" $(echo "${T2} + ${T4}" | bc) printf "%-23s : %5.1f ${Tunit}\n" "Convert to global IDs" ${T3} if [ "${#T[@]}" -gt "5" ]; then printf "%-23s : %5.1f ${Tunit}\n" "PSO & POS permutations" ${T5}; fi if [ "${#T[@]}" -gt "6" ]; then printf "%-23s : %5.1f ${Tunit}\n" "SPO & SOP permutations" ${T6}; fi if [ "${#T[@]}" -gt "7" ]; then printf "%-23s : %5.1f ${Tunit}\n" "OSP & OPS permutations" ${T7}; fi if [ "${#T[@]}" -gt "9" ]; then printf "%-23s : %5.1f ${Tunit}\n" "Add text index" ${T9}; fi echo printf "%-23s : %5.1f ${Tunit}\n" "TOTAL index build time" ${TT} } function action_start { if curl --silent http://localhost:${SERVER_PORT} > /dev/null; then echo "${RED}Server already running on port ${SERVER_PORT}, use \"qlever restart\" or check SERVER_PORT in your Qleverfile${NORMAL}" echo "${BLUE}" ps -e -o "%p" -o " %U " -o start_time -o " %a" \ | \grep "${SERVER_BINARY} .*-p ${SERVER_PORT}" \ | \grep -v "grep.*${SERVER_BINARY}" printf "${NORMAL}" else if [ -f "${DB}.index.pso" ] && [ -f "${DB}.index.pos" ]; then echo "Starting the QLever server in the background and waiting until it's ready (Ctrl+C will not kill it) ..." echo rm -f ${DB}.server-log.txt && touch ${DB}.server-log.txt eval $SHOW ${SERVER_CMD} tail -f -n 10 ${DB}.server-log.txt & PID=$! ALIVE_CHECK_URL="http://localhost:${SERVER_PORT}/ping?msg=from%20the%20qlever%20script" while [ $(curl -s "${ALIVE_CHECK_URL}" > /dev/null; echo $?) != 0 ]; do sleep 1; done # if [ ! -z "${INDEX_DESCRIPTION}${TEXT_DESCRIPTION}" ]; then echo; fi if [ ! -z "${INDEX_DESCRIPTION}" ]; then # echo "Setting index description to \"${INDEX_DESCRIPTION}\"" curl -Gs ${SERVER_API} \ --data-urlencode "index-description=${INDEX_DESCRIPTION}" \ --data-urlencode "access-token=${ACCESS_TOKEN}" > /dev/null fi if [ ! -z "${TEXT_DESCRIPTION}" ]; then # echo "Setting text description to \"${TEXT_DESCRIPTION}\"" curl -Gs ${SERVER_API} \ --data-urlencode "text-description=${TEXT_DESCRIPTION}" \ --data-urlencode "access-token=${ACCESS_TOKEN}" > /dev/null fi kill ${PID} wait ${PID} 2> /dev/null # Supress "Terminated ..." message. else echo "${RED}Index missing, first build one using \"qlever index\"${NORMAL}" fi fi } function action_stop { echo "Stop the QLever server (find and kill manually if it fails) ..." echo if printf ${BLUE} && pgrep -af "${SERVER_BINARY} -i [^ ]*${DB}" && printf ${NORMAL}; then echo eval $SHOW ${STOP_CMD} $NOSHOW && echo "Killed processes and removed \"${DB}.server-log.txt\"" else echo "${RED}Did not find a running server for \"${DB}\" or could not kill it, try \"qlever status\"${NORMAL}" fi } function action_restart { $SHOW ${QLEVER_CMD_WITH_VARS} stop $NOSHOW | sed '1,3d' $SHOW ${QLEVER_CMD_WITH_VARS} start $NOSHOW | sed '1,3d; $d' } function action_wait { tail -f -n 10 ${DB}.server-log.txt & PID=$! while [ $(curl --silent http://localhost:$(SERVER_PORT) > /dev/null; echo $?) != 0 ]; do sleep 1; done kill $PID } function action_log { echo "Showing the log (abort with Ctrl+C) ..." echo $SHOW tail -f -n 50 ${DB}.server-log.txt } function action_log_until_server_up { $SHOW tail -f -n 10 ${DB}.server-log.txt & PID=$! while ! curl --silent http://localhost:${SERVER_PORT} > /dev/null; do sleep 1; done kill ${PID} } function action_status { echo "Showing all QLever-related processes and docker containers on this machine ..." echo "${BLUE}" $SHOW ps -e -o %p -o %U -o start_time -o rss:10 -o %a | sed -E '1p; /\b('${SERVER_BINARY}'|'${INDEXER_BINARY}')/!d; /bash -c/d' $NOSHOW \ | awk 'NR==1 {o=$0; a=match($0, $5)} NR > 1 {o=$0; $4=int($4/(1024*1024))"G";} {printf "%-7s %-8s %5s %5s %s\n", $1, $2, $3, $4, substr(o, a)}' printf "${NORMAL}" if [ $(docker ps --filter "name=qlever" | wc -l) -gt 1 ]; then \ echo "${BLUE}" $SHOW docker ps --filter "name=qlever" --format "table {{.Names}}\t{{.State}}\t{{.RunningFor}}\t{{.Ports}}" printf "${NORMAL}" fi } function action_example_query { echo "Launching SELECT query for 10 random triples (in TSV format) ..." echo $SHOW curl ${SERVER_API} -H "Accept: text/tab-separated-values" -H "Content-type: application/sparql-query" --data "SELECT * WHERE { ?s ?p ?o } LIMIT 10" } function action_example_query_construct { echo "Launching CONSTRUCT query for 10 random triples (in TSV format) ..." echo $SHOW curl ${SERVER_API} -H "Accept: text/turtle" -H "Content-type: application/sparql-query" --data "CONSTRuCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 10" } function action_query { echo "Launching GET query (results in TSV format) ..." echo if [ -z "${QUERY}" ]; then echo "${RED}Empty query, specify one via the command line like this: qlever QUERY=\"...\" query${NORMAL}" else $SHOW "${QUERY_CMD[@]}" fi } # Warmup queries for the autocompletion. # # TODO: This requires a running QLever UI and his currently hard-coded to use # instances on particular machine (galera.informatik.privat). It will be fixed # soon. # # NOTE: We need -tt here because the "qlever" script calls "make" via a pipe and # so it does not have a terminal (the error message is "Pseudo-terminal will not # be allocated because stdin is not a terminal." and "the input device is not a # TTY"). The manpage for ssh says: "Multiple -t options force tty allocation, # even if ssh has no local tty." and "-tt" is just a shorthand for "-t -t".in.master: function action_pin_INTERNAL { echo "Launch warmup queries for the QLever UI autocompletion (via galera) ..." $SHOW ssh -tt -o LogLevel=QUIET galera docker exec -it qlever-ui bash -c \"python manage.py warmup ${SLUG} pin\" } # Clear the cache. function action_clear_cache { echo "Clearing the cache (unpinned entries only) ..." $SHOW curl -Gs ${SERVER_API} --data-urlencode "cmd=clear-cache" $NOSHOW > /dev/null curl -Gs ${SERVER_API} --data-urlencode "cmd=cache-stats" \ | sed 's/[{}",]//g; s/:/: /g; s/^\s\+//' | tr -s " " \ | numfmt --field=2,5,8,11,14 --grouping } function action_clear_cache_complete { echo "Clearing the cache completely (including pinned entries) ..." $SHOW curl -Gs ${SERVER_API} \ --data-urlencode "cmd=clear-cache-complete" \ --data-urlencode "access-token=${ACCESS_TOKEN}" $NOSHOW > /dev/null curl -Gs ${SERVER_API} --data-urlencode "cmd=cache-stats" \ | sed 's/[{}",]//g; s/:/: /g; s/^\s\+//' | tr -s " " \ | numfmt --field=2,5,8,11,14 --grouping } # Get various settings and statistics. function action_disk_usage { echo "Disk usage of all files in this QLever index, and the size of the input files" echo $SHOW du -hc $(ls ${DB}.* | sed -E '/(index\.|vocabulary|prefixes|meta-data|text)/!d') echo # echo && echo "For comparison, the size of the input files" && echo # du -hc ${RDF_FILES} } function action_cache_stats_and_settings { echo "Show cache statistics (sizes are in bytes) and cache settings (sizes are in GB) ..." echo ${BLUE} $SHOW curl -Gs ${SERVER_API} --data-urlencode "cmd=cache-stats" $NOSHOW \ | sed -n 's/[",]//g; s/:/: /g; s/^\s\+//p' | tr -s " " \ | awk '{ if ($1 ~ "pinned-size:") { $2 = 8 * $2 } print }' \ | numfmt --field=2 --grouping $SHOW curl -Gs ${SERVER_API} --data-urlencode "cmd=get-settings" $NOSHOW \ | sed 's/[{}",]//g; s/:/: /g; s/^\s\+//' | tr -s " " printf ${NORMAL} } function action_server_stats { echo "Getting stats from \"${SERVER_API}\" ..." echo ${BLUE} $SHOW curl -Gs ${SERVER_API} --data-urlencode "cmd=stats" $NOSHOW \ | sed -n 's/[",]//g; s/:/: /g; s/^\s\+//p' | tr -s " " \ | sed -E 's/^((kb|text)index:\s*)(.*)$/\1"\3"/' \ | numfmt --field=2 --grouping --invalid=ignore printf ${NORMAL} } function action_index_description { echo "Setting index description to \"${INDEX_DESCRIPTION}\" ..." $SHOW curl -Gs ${SERVER_API} --data-urlencode "index-description=${INDEX_DESCRIPTION}" --data-urlencode "access-token=${ACCESS_TOKEN}" $NOSHOW > /dev/null } function action_text_description { echo "Setting text description to \"${TEXT_DESCRIPTION}\" ..." $SHOW curl -Gs ${SERVER_API} --data-urlencode "text-description=${TEXT_DESCRIPTION}" --data-urlencode "access-token=${ACCESS_TOKEN}" $NOSHOW > /dev/null } # QLever UI (work in progress). LOG_FILE=qleverui-log.tmp ERROR_CMD="(echo && echo \"${BLUE}An error occured, check ${LOG_FILE} for details, the last 10 lines are:${NORMAL}\" && tail ${LOG_FILE} && false)" QLEVERUI_GIT=https://github.com/ad-freiburg/qlever-ui.git QLEVERUI_DIR="qlever-ui" function action_ui { echo "Starting the QLever UI on ${HOSTNAME}:${QLEVERUI_PORT} ..." echo $SHOW docker rm -f ${QLEVERUI_DOCKER_CONTAINER} 2>&1 > /dev/null $SHOW docker run -d -p ${QLEVERUI_PORT}:7000 --name ${QLEVERUI_DOCKER_CONTAINER} ${QLEVERUI_DOCKER_IMAGE} > /dev/null $NOSHOW || return $SHOW docker exec -it ${QLEVERUI_DOCKER_CONTAINER} bash -c "python manage.py configure ${QLEVERUI_CONFIG} ${SERVER_API}" $NOSHOW || return echo echo "The QLever UI should now be up at http://${HOSTNAME}:${QLEVERUI_PORT} ." echo "You can log in as QLever UI admin with username and passwort \"demo\"" } function action_autocompletion_warmup { echo "Launch warmup queries for the QLever UI autocompletion ..." echo if docker container inspect -f '{{.State.Running}}' ${QLEVERUI_DOCKER_CONTAINER} > /dev/null 2>&1; then $SHOW docker exec -i qlever-ui bash -c "python manage.py warmup ${QLEVERUI_CONFIG} pin" | sed -En 's/^\x1b\[[0-9]+/\x1b\[34/p' else echo "${RED}The autocompletion queries are defined by the UI, run \"qlever ui\" first${NORMAL}" fi } # Update the qlever script (simply git pull from the GitHub repo). function action_update { echo "Updating \"qlever\" script ..." echo if [ -d "${QLEVER_CMD_DIR}/.git" ]; then $SHOW cd ${QLEVER_CMD_DIR} && git pull else echo "${RED}Did not find directory \".git\" in \"${QLEVER_CMD_DIR}\"${NORMAL}" echo fi } # Show the paths to "qlever", the QLever binaries, and the QLever UI. function action_where { cat << EOT Show where everything is ... ${BLUE} Directory with "qlever" script : ${QLEVER_CMD_DIR} Directory with QLever binaries : ${QLEVER_BIN_DIR} Directory with QLever UI repo : ${QLEVERUI_DIR} ${NORMAL} EOT } # Produce list of all input files. function action_rdf_files { eval $SHOW ls ${RDF_FILES} } # Produce the input as fed to the index builder. function action_cat_files { eval $SHOW ${CAT_FILES} } # Actions for turning docker on and off. # # TODO: Currently, there is one docker container, which is then used for for # *all* docker actions using "docker exec". This makes it easier to mix actions, # where some actions use docker and some don't. However, if the docker container # is running, it blocks the server port even when nothing is running inside the # container, so that when cannot do "qlever start" without docker then. function action_docker_on_DEPRECATED { if docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} > /dev/null 2>&1; then echo "${MAGENTA}Docker container \"${QLEVER_DOCKER_CONTAINER}\" already running${NORMAL}" else docker rm -f "${QLEVER_DOCKER_CONTAINER}" > /dev/null 2> /dev/null echo "${MAGENTA}Starting docker container \"${QLEVER_DOCKER_CONTAINER}\" ...${NORMAL}" $SHOW docker run -d -u $(id -u):$(id -g) -it -v $(pwd):/index \ -p ${SERVER_PORT}:${SERVER_PORT} \ --entrypoint bash \ --name ${QLEVER_DOCKER_CONTAINER} ${QLEVER_DOCKER_IMAGE} $NOSHOW \ > /dev/null while ! docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} > /dev/null 2>&1; do sleep 0.1; done # $SHOW docker cp ${QLEVER_CMD_DIR}/qlever \ # ${QLEVER_DOCKER_CONTAINER}:/index $NOSHOW \ # > /dev/null # fi echo "${BLUE}" docker ps --filter "name=${QLEVER_DOCKER_CONTAINER}" printf "${NORMAL}" } function action_docker_off_DEPRECATED { $SHOW docker rm -f "${QLEVER_DOCKER_CONTAINER}" } ### ### CONFIGURATION (when called with . qlever or if we need to) ### # If not called with ". qlever" and completions or the Qleverfile are missing, # tell the user to run ". qlever" once for full functionality. Note that bash # autocompletion can only be activated by "sourcing" the respective commands # (the ". qlever" is equivalent to "source qlever"). If the Qleverfile has # BASH_COMPLETION = 0, don't mind the autocompletion. # # Skip this when calling "qlever update" because it's not only not necessary # then, but even annoying. if [ ${BASH_SOURCE[0]} == $0 ] \ && ( ( [ -z "${QLEVER_COMPLETIONS}" ] && [ "${BASH_COMPLETION}" != "0" ] ) || \ ( [ ! -e Qleverfile ] && ${QLEVERFILE_NEEDED} ) ); then echo action_help exit fi # If called with ". qlever", setup what is not already setup: the PATH, the bash # autocompletion (unless user don't want it), the QLeverfile. if [ "${QLEVER_CMD}" != "$0" ]; then echo echo "${BOLD}QLEVER CONFIG${NORMAL}" echo # PATH: Check if QLEVER_CMD_DIR (read from Qleverfile if it exists) is in the # path and if not add it to the path. # # Note: The full processing of the QLeverfile comes *after* the code for the # ". qlever" case because otherwise the shell from which ". qlever" was called # would be full with variables from this script. The QLEVER_BIN_DIR is an # exception because adding something to the path requires a call to ". qlever" # and would not work with "qlever" (which runs in a subshell). # echo "${BOLD}Checking your PATH ...${NORMAL}" if [ -s "Qleverfile" ] && [ -z "${QLEVER_BIN_DIR}" ]; then export QLEVER_BIN_DIR="$(sed -En 's/^\s*QLEVER_BIN_DIR\s*=\s*(\S+)/\1/p' Qleverfile)" fi for DIR in ${QLEVER_CMD_DIR} ${QLEVER_BIN_DIR}; do if [[ ":${PATH}:" == *":${DIR}:"* ]]; then echo "The directory \"${DIR}\" is already contained in your PATH" else export PATH=${PATH}:${DIR} echo "Added the directory \"${DIR}\" to your PATH" fi done echo # If we called ". qlever path" (just to set the paths), exit here. if [ "$*" == "path" ]; then echo "${NORMAL}Called \". qlever path\", so leaving now${NORMAL}" echo return fi # Bash autocompletion: Set completions with "complete -W" and store the # completions in "QLEVER_COMPLETIONS". We need the latter so that we know that # the completions are set (complete -p does not work in a subshell). COMP_WORDBREAKS=${COMP_WORDBREAKS/=/} COMPLETIONS_FILE=no_longer_needed echo "${BOLD}Setting up bash autocompletion ...${NORMAL}" COMPLETIONS=$(cat ${QLEVER_CMD} | sed -En '/DEPRECATED/d; s/^function action_([a-zA-Z0-9_.-]+).*/\1/p' | sed 's/_/-/g') COMPLETIONS+=" \"USE_DOCKER=true\" \"USE_DOCKER=false\"" export QLEVER_COMPLETIONS="$(echo "${COMPLETIONS}" | paste -sd" ")" complete -W "${QLEVER_COMPLETIONS}" qlever echo "Done, number of completions: $(echo "${COMPLETIONS}" | wc -l)" echo ${NORMAL} # If we called ". qlever init" (for use in .bashrc, where we only want to set # the PATH and activate the autocompletion), exit here. if [ "$*" == "shell_init" ]; then echo "${NORMAL}Called \". qlever shell_init\", so leaving now${NORMAL}" echo return fi # QLeverfile: If it's not there yet, create a basic one (with good guesses for # some basic settings). Don't overwriting an existing Qleverfile, unless the # script was called with an explicit preconfiguration as argument, for example # ". qlever olympics". if [ -e Qleverfile ] && [ -z $* ]; then echo "${BOLD}Checking Qleverfile ...${NORMAL}" cat << EOT There is already a QLeverfile in this directory. If you want a freshly generated default Qleverfile, remove or move the existing one and run ". qlever" again. EOT else echo "${BOLD}Creating new Qleverfile ...${NORMAL}" # If Qleverfiles/Qleverfile.<first arg> exists, just copy that. Otherwise copy # Qleverfiles/Qleverfile.default and fill out the %...% templates. QLEVERFILE_NAME="${QLEVER_CMD_DIR}/Qleverfiles/Qleverfile.$1" if [ "$1" != "default" ] && [ -f "${QLEVERFILE_NAME}" ]; then cat ${QLEVER_CMD_DIR}/Qleverfiles/Qleverfile.$1 \ | sed -E "s/^(QLEVER_BIN_DIR\s+=).*/\1 \"${QLEVER_BIN_DIR//\//\\\/}\"/" \ | sed -E "s/%RANDOM%/${RANDOM}${RANDOM}/" \ > Qleverfile echo "Copied pre-configured Qleverfile for \"$1\" into current directory." echo else # Default values for the %...% templates in Qleverfiles/Qleverfile.default. FOLDER_NAME=$(pwd) DATE=$(date +"%d.%m.%Y %H:%M") DB=must_specify RDF_FILES="\${DB}.ttl" CAT_FILES="cat \${RDF_FILES}" # If a file with suffix .ttl or .nt exists, use the basename as the basename # for the index files (the DB variable in the configuration) and pick the # right "cat" command according to the suffix. If several such files exist, # take the largest one. If no such file exists, leave the basename empty and # for the user to set. FILE=$(ls -S | egrep "\.(ttl|nt)(\.(gz|bz|bz2|xz))?\$" | head -1) if [ ! -z "$FILE" ]; then DB="${FILE/.*/}" RDF_FILES="$FILE" if [[ ${RDF_FILES} =~ .gz$ ]]; then CAT_FILES="zcat \${RDF_FILES}"; fi if [[ ${RDF_FILES} =~ .bz2?$ ]]; then CAT_FILES="bzcat \${RDF_FILES}"; fi if [[ ${RDF_FILES} =~ .xz$ ]]; then CAT_FILES="xzcat \${RDF_FILES}"; fi fi # Copy QLeverfiles/Qleverfile.default and replace the %...% templates. cat ${QLEVER_CMD_DIR}/Qleverfiles/Qleverfile.default \ | sed -E "s/%FOLDER_NAME%/${FOLDER_NAME//\//\\\/}/" \ | sed -E "s/%DATE%/${DATE}/" \ | sed -E "s/%DB%/\"${DB}\"/" \ | sed -E "s/%RDF_FILES%/\"${RDF_FILES}\"/" \ | sed -E "s/%CAT_FILES%/\"${CAT_FILES}\"/" \ | sed -E "s/%QLEVER_BIN_DIR%/\"${QLEVER_BIN_DIR//\//\\\/}\"/" \ | sed -E "s/%RANDOM%/${RANDOM}${RANDOM}/" \ > Qleverfile # | sed -E "s/%FOLDER_NAME%/${FOLDER_NAME}/; s/%DATE%/${DATE}/" \ cat << EOT No pre-configuration name specified (as argument of ". qlever"). Copied default Qleverfile to current directory, please edit and check. EOT fi fi # DONE: give the user a short heads up what they can do now. cat << "EOT" | display_markdown # Setup is complete Type `qlever` and use autocompletion to see which actions are available. Add a "show" in the end to see what an action does without executing it (for example, `qlever index show`). Edit your local Qleverfile to change settings. A typical sequence of actions if you have used a preconfigured Qleverfile is: `qlever get-data` `qlever index` `qlever start` `qlever example-query` EOT return fi ### ### BASIC HELP AND INSTALL INFO ### ### Note that this must come after the code for ". qlever" (which is also called ### without arguments). ### if [ -z "$*" ] || [ "$*" == "help" ]; then echo action_help exit fi if [ "$*" == "install-binaries" ]; then echo action_install_binaries exit fi # Leave a blank line at the beginning (the welcome message used to be here, but # we found it redundant). echo ### ### VARIABLE ASSIGNMENTS ### ### 1. Default settings ### 2. Read from Qleverfile (space around = allowed) ### 3. Computed derived variables ### # Some default settings. APP_DIR=$(pwd) # Where the script was called from DB=must_specify USE_DOCKER=false WITH_TEXT_INDEX=false QLEVER_DOCKER_IMAGE=adfreiburg/qlever QLEVERUI_DOCKER_IMAGE=adfreiburg/qlever-ui QLEVERUI_DOCKER_CONTAINER=qlever-ui HOSTNAME=must_specify # backend host SERVER_PORT=must_specify # backend port QLEVERUI_PORT=7000 # frontend port MEMORY_FOR_QUERIES=30 # in GB CACHE_MAX_SIZE_GB=30 # in GB CACHE_MAX_SIZE_GB_SINGLE_ENTRY=5 # in GB CACHE_MAX_NUM_ENTRIES=1000 ADMIN_TOKEN= # for actions requiring privilege QUERY= # Read from Qleverfile (only lines that look like an assignment are considered, # space around = allowed). # echo "$(cat Qleverfile | sed -En 's/^([A-Z_]+)\s*=\s*(.*)$/\1=\2/p')" # echo if ${QLEVERFILE_NEEDED}; then eval "$(cat Qleverfile | sed -En 's/^([A-Z_]+)\s*=\s*(.*)$/\1=\2/p')" fi # echo "CAT_FILES = \"${CAT_FILES}\"" # Check for variable assignments (of the form VARIABLE=value) in the command # line. They override the setting from the Qleverfile. The remaining arguments # stay in "$@". VARS=() for ARG do shift # [[ "${ARG}" =~ ^--$ ]] && OPT="${ARG}" && continue [[ "${ARG}" =~ ^[A-Z_]+=[^[:space:]] ]] && VARS+=( "${ARG}" ) && continue set -- "$@" "${ARG}" done if (( ${#VARS[@]} )); then echo -e "\033[1mVariable settings specified (will override those from Qleverfile):\033[0m" echo "${BLUE}" for VAR in "${VARS[@]}"; do VAR="${VAR/=/=\"}\""; echo "${BLUE}${VAR}${NORMAL}"; eval "${VAR}"; done echo "${NORMAL}" fi # for ARG in "$@"; do echo "ARG = \"${ARG}\""; done # Derived variables. TODO: Only if if not explicitly defined in Qleverfile. QLEVER_CMD_WITH_VARS=qlever if (( ${#VARS[@]} )); then QLEVER_CMD_WITH_VARS+=" ${VARS[*]}"; fi QLEVER_DOCKER_CONTAINER=qlever.${DB} SLUG=${QLEVERUI_CONFIG} # URL slug used in the QLever UI INDEXER_BINARY=IndexBuilderMain ULIMIT_CMD="ulimit -Sn 1048576; " if [ ! -z "$(ls ${RDF_FILES} 2> /dev/null)" ] && \ [ "$(du -Lbc $(eval ls ${RDF_FILES}) | tail -1 | cut -f1)" -lt 10000000000 ]; then ULIMIT_CMD=""; fi INDEXER_OPTIONS="-F ttl -f - -i ${DB} -s ${DB}.settings.json" if [[ :1:yes:true: == *:${PSO_AND_POS_ONLY}:* ]]; then INDEXER_OPTIONS="${INDEXER_OPTIONS} --only-pso-and-pos-permutations --no-patterns" fi if [ "${STXXL_MEMORY_GB}" ]; then INDEXER_OPTIONS="${INDEXER_OPTIONS} --stxxl-memory-gb ${STXXL_MEMORY_GB}" fi if [[ :from_text_records:from_text_records_and_literals: == *:${WITH_TEXT_INDEX}:* ]]; then INDEXER_OPTIONS="${INDEXER_OPTIONS} -w ${DB}.wordsfile.tsv -d ${DB}.docsfile.tsv" fi if [[ :from_literals:from_text_records_and_literals: == *:${WITH_TEXT_INDEX}:* ]]; then INDEXER_OPTIONS="${INDEXER_OPTIONS} --text-words-from-literals" fi if [[ :1:yes:true: == *:${USE_DOCKER}:* ]]; then INDEXER_CMD_PREFIX="" INDEXER_CMD="docker run -it --rm -u $(id -u):$(id -g) -v /etc/localtime:/etc/localtime:ro -v $(pwd):/index -w /index --entrypoint bash --name ${QLEVER_DOCKER_CONTAINER}.index-build ${QLEVER_DOCKER_IMAGE} -c \"${PIPEFAIL_CMD}${ULIMIT_CMD}${CAT_FILES} | ${INDEXER_BINARY} ${INDEXER_OPTIONS//\"/\\\"} | tee ${DB}.index-log.txt\"" else INDEXER_CMD_PREFIX="/bin/time -o >(xargs printf \"%d/1000000\n\" | bc -l | xargs printf \"\nMax RAM usage: %'.1f GB\n\n\" | tee -a ${DB}.index-log.txt) -f \"%M\"" INDEXER_CMD="bash -c \"${ULIMIT_CMD}${CAT_FILES} | ${INDEXER_BINARY} ${INDEXER_OPTIONS//\"/\\\"} | tee ${DB}.index-log.txt\"" fi REMOVE_DATA_CMD="for RDF_FILE in ${RDF_FILES}; do rm -f \$RDF_FILE; done" SERVER_BINARY=ServerMain SERVER_OPTIONS="-i ${DB} -j 8 -p ${SERVER_PORT} -m ${MEMORY_FOR_QUERIES} -c ${CACHE_MAX_SIZE_GB} -e ${CACHE_MAX_SIZE_GB_SINGLE_ENTRY} -k ${CACHE_MAX_NUM_ENTRIES}" if [ ! -z "${ACCESS_TOKEN}" ]; then SERVER_OPTIONS="${SERVER_OPTIONS} -a \"${ACCESS_TOKEN}\""; fi if [[ :1:yes:true: == *:${PSO_AND_POS_ONLY}:* ]]; then SERVER_OPTIONS="${SERVER_OPTIONS} --only-pso-and-pos-permutations --no-patterns" fi if [[ :1:yes:true: == *:${NO_PATTERNS}:* ]]; then SERVER_OPTIONS="${SERVER_OPTIONS} --no-patterns" fi if [[ :1:yes:true:from_text_records:from_literals:from_text_records_and_literals: == *:${WITH_TEXT_INDEX}:* ]]; then SERVER_OPTIONS="${SERVER_OPTIONS} -t" fi # Command for action "start" if [[ :1:yes:true: == *:${USE_DOCKER}:* ]]; then SERVER_CMD="docker run -d --restart unless-stopped -u $(id -u):$(id -g) -it -v /etc/localtime:/etc/localtime:ro -v $(pwd):/index -p ${SERVER_PORT}:${SERVER_PORT} -w /index --entrypoint bash --name ${QLEVER_DOCKER_CONTAINER} ${QLEVER_DOCKER_IMAGE} -c \"${SERVER_BINARY} ${SERVER_OPTIONS//\"/\\\"} > ${DB}.server-log.txt\" > /dev/null" else SERVER_CMD="${SERVER_BINARY} ${SERVER_OPTIONS} > ${DB}.server-log.txt &" fi # Command for action "stop" if [ "$(docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} 2> /dev/null)" == "true" ]; then STOP_CMD="docker rm -f ${QLEVER_DOCKER_CONTAINER} > /dev/null" elif [ ! -z "$(pgrep -af "${SERVER_BINARY} -i ${DB} ")" ]; then STOP_CMD="pkill -f \"${SERVER_BINARY} -i [^ ]*${DB}\"" elif [[ :1:yes:true: == *:${USE_DOCKER}:* ]]; then STOP_CMD="docker rm -f ${QLEVER_DOCKER_CONTAINER} > /dev/null" else STOP_CMD="pkill -f \"${SERVER_BINARY} -i [^ ]*${DB}\"" fi SERVER_API=http://${HOSTNAME}:${SERVER_PORT} # Command for action "query" QUERY=${QUERY//\"/\\\"} QUERY_CMD=(curl -Gs ${SERVER_API} -H "Accept: text/tab-separated-values" --data-urlencode "query=${QUERY}") # Variant of make that reads the master Qleverfile (using GET_MASTER_QLEVERFILE) # and the local Qleverfile (in the directory from which this script is called). # The -s option stands for "silent" (do not show the commands while executing # them). function qlever_make { QLEVERFILE_ARG= if [ -e "${APP_DIR}/Qleverfile" ]; then QLEVERFILE_ARG=" -f ${APP_DIR}/Qleverfile" fi get_master_qleverfile | make -s -f - ${QLEVERFILE_ARG} "$@" } # Like the above, but only show what would be executed (using the -n option of # "make"), in blue. Leave out command lines that end with #. function qlever_make_show { printf "${BLUE}" get_master_qleverfile \ | make -f - -f ${APP_DIR}/Qleverfile -n "$@" \ | egrep -v "#.?\$" | sed 's/^\s*//; s/\s?*\\$//' \ | sed 's/^: #/#/' printf "${NORMAL}" } # Execute action function (given as argument $1). function execute_action { ACTION_FUNCTION=$1 if [ "$(declare -f ${ACTION_FUNCTION})" ]; then # echo "Executing function \"${ACTION_FUNCTION}\" ..." # echo eval ${ACTION_FUNCTION} else echo "${RED}Action function \"$1\" not defined${NORMAL}" fi } # Show selected code of action function (given as argument $1). function show_action { QUOTE=\" DOLLAR=\$ BACKSLASH=\\ ACTION_FUNCTION="$1" if [ "$(declare -f ${ACTION_FUNCTION})" ]; then printf "${BLUE}" # This miracle code show the code of the action function. It works as # follows: # 1. The declare -t gives the full code (as written above). # 2. The first sed filters out the lines starting with $SHOW and removing any # parts after $NOSHOW (this gives us control which part to show). # 3. The second sed temporarily replaces all $ that are not followed by a { # and all " by ${DOLLAR} and ${QUOTE}, respsectively. That way, these will # be be preserved (and not get interpreted somehow). # 4. The last part expands all the ${...} variables (without the eval, no # expansion would happen), including the ${DOLLAR} and ${QUOTE} introduced # in the previous step. # 5. Remove empty lines (these correpond to commands which are only exeuted # under certain circumstances) declare -f ${ACTION_FUNCTION} \ | sed -En 's/\s+\$NOSHOW.*$//; s/;$//; s/^.*\$SHOW //p' \ | sed -En 's/"/${QUOTE}/g; s/\$([^{])/${DOLLAR}\1/g; s/\\/${BACKSLASH}/g; p' \ | while read LINE; do eval "echo \"${LINE}\""; done \ | sed -E '/^\s*$/d' printf "${NORMAL}" else echo "${RED}Action function \"$1\" not defined${NORMAL}" fi } # Command to leave the script ("return" when the script is sourced, "exit" when # it is called normally, that is, within its own subshell). EXIT=exit if [ ${QLEVER_CMD} != $0 ]; then EXIT=return; fi function exit_qlever { eval ${EXIT}; } # # Special command "show-config" (for debugging, not one of the completions). # if [ "$*" == "show-config" ]; then # echo "${BOLD}${MAGENTA}Secret action \"show-config\":${NORMAL}" # echo # cat << EOT # Showing the settings of some variables after they went through "make" and then # exported to the "qlever" script again (for debugging). If you call the script # with a variable assignment as in "qlever USE_DOCKER=0 ...", that value should # overrule the one from the QLeverfile. # EOT # echo "${BLUE}" # qlever_make "${VARS[@]}" export.HIDDEN # echo "${NORMAL}" # eval ${EXIT} # fi # # # Actually do these assignments. NO: this is already done above! # $(qlever_make "${VARS[@]}" export.HIDDEN) # eval $(qlever_make "${VARS[@]}" export.HIDDEN) ### ### WHAT THE SCRIPT ACTUALLY DOES ### # For selected actions: If USE_DOCKER=1 check if docker container is running # and if not run it. USE_DOCKER_ACTIONS=none # USE_DOCKER_ACTIONS=:start:index: if [[ ${USE_DOCKER_ACTIONS} == *:"$ARG":* ]]; then if [ "${USE_DOCKER}" == "1" ]; then if [ "$(docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} 2> /dev/null)" == "true" ]; then echo "${MAGENTA}Using the already running docker container \"${QLEVER_DOCKER_CONTAINER}\"${NORMAL}" echo else echo "${MAGENTA}Starting new docker container \"${QLEVER_DOCKER_CONTAINER}\"${NORMAL}" echo qlever_make_show "${VARS[@]}" QLEVER_CMD_DIR="${QLEVER_CMD_DIR}" docker-run.HIDDEN echo qlever_make QLEVER_CMD_DIR="${QLEVER_CMD_DIR}" "${VARS[@]}" docker-run.HIDDEN fi else if [ "$(docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} 2> /dev/null)" == "true" ]; then echo "${MAGENTA}USE_DOCKER=0 but found docker container \"${QLEVER_DOCKER_CONTAINER}\", removing it ...${NORMAL}" echo qlever_make_show "${VARS[@]}" docker-remove.HIDDEN echo qlever_make "${VARS[@]}" docker-remove.HIDDEN fi fi fi # If the last argument is "show", just show the commands, but don't execute # them. The first for loop is a portable hack to get the last argument. for LAST; do true; done if [ "${LAST}" == "show" ]; then echo "${BOLD}Just showing what would be executed${NORMAL}" echo for ARG in "$@"; do if [ "${ARG}" != "show" ]; then ACTION_FUNCTION=action_$(echo ${ARG} | sed 's/-/_/g') if [ "$(declare -f ${ACTION_FUNCTION})" ]; then echo "\"${ARG}\" would execute the following:" echo show_action "${ACTION_FUNCTION}" # qlever_make_show "${VARS[@]}" "${ARG}" echo else echo "${RED}Action \"${ARG}\" not defined, use the autocompletion${NORMAL}" echo fi fi done exit fi # For each action, check whether the corresponding action function exists, and # if yes, show the command and then execute it. for ARG in "$@"; do # If USE_DOCKER=1 and action requires docker, make sure it's running. USE_DOCKER_ACTIONS=none # USE_DOCKER_ACTIONS=:start:index: if [[ ${USE_DOCKER_ACTIONS} == *:"$ARG":* ]]; then if [[ :1:yes:true: == *:${USE_DOCKER}:* ]]; then if ! docker container inspect -f '{{.State.Running}}' ${QLEVER_DOCKER_CONTAINER} > /dev/null 2>&1; then execute_action action_docker_on echo fi fi fi # Now execute the action. echo "${BOLD}Executing \"${ARG}\":${NORMAL}" echo ACTION_FUNCTION=action_$(echo ${ARG} | sed 's/-/_/g') if [ "$(declare -f ${ACTION_FUNCTION})" ]; then if show_action "${ACTION_FUNCTION}"; then echo execute_action "${ACTION_FUNCTION}" echo fi else echo "${RED}Action \"${ARG}\" not defined, use the autocompletion${NORMAL}" echo fi done
package de.htwg.sa.minesweeper.persistence.persistenceComponent.persistenceXmlImpl import de.htwg.sa.minesweeper.persistence.persistenceComponent.IPersistence import de.htwg.sa.minesweeper.persistence.entity.* import de.htwg.sa.minesweeper.persistence.persistenceComponent.config.Default import java.io._ import scala.util.{Failure, Success, Try} import scala.xml._ class Persistence extends IPersistence { override def loadGame: Option[IGame] = { val maybeFile: Try[Elem] = Try(scala.xml.XML.loadFile("C:\\Playground\\minesweeperpublic\\src\\main\\data\\game.xml")) val file = maybeFile match { case Success(file) => file case Failure(exception) => throw exception } val status = (file \\ "game" \@ "status") val bombs = (file \\ "bombs").text.toInt val side = (file \\ "side").text.toInt val time = (file \\ "time").text.toInt Some(Game(bombs, side, time, "Playing")) } def gameToXml(game: IGame) = { <game status ={ game.board }> <bombs>{ game.bombs}</bombs> <side>{ game.side }</side> <time>{ game.time }</time> </game> } override def saveGame(game: IGame): Unit = {scala.xml.XML.save("C:\\Playground\\minesweeperpublic\\src\\main\\data\\game.xml", gameToXml(game))} def loadField(field: String): Option[IField] = { val maybeFile: Try[Elem] = Try(scala.xml.XML.loadFile("C:\\Playground\\minesweeperpublic\\src\\main\\data\\field.xml")) val file = maybeFile match { case Success(file) => file case Failure(exception) => throw exception } val size = (file \\ "field" \@ "size").toInt val matrixOption = Some(Default.scalableMatrix(size, "~")) val hiddenOption = Some(Default.scalableMatrix(size, "~")) val fieldOption = Some(Default.scalableField(size, "~")) val cellNodesVisible: NodeSeq = (file \\ "field" \\ "matrix" \\ "cell") val matrix = cellNodesVisible.foldLeft(matrixOption.get) { (m, cell) => val row: Int = (cell \ "@row").text.toInt val col: Int = (cell \ "@col").text.toInt val symbol = (cell.text.trim) m.replaceCell(row, col, symbol) } val cellNodesHidden: NodeSeq = (file \\ "field" \\ "hidden" \\ "cell") val hidden = cellNodesHidden.foldLeft(hiddenOption.get) { (h, cell) => val row: Int = (cell \ "@row").text.toInt val col: Int = (cell \ "@col").text.toInt val symbol = (cell.text.trim) h.replaceCell(row, col, symbol) } fieldOption.map { f => Default.mergeMatrixToField(matrix, hidden) } } def fieldToXml(field: IField) = { <field size = {field.matrix.size.toString}> <matrix> { for { row <- 0 until field.matrix.size col <- 0 until field.matrix.size } yield cellToXmlVisible(field, row, col) } </matrix> <hidden> { for { row <- 0 until field.matrix.size col <- 0 until field.matrix.size } yield cellToXmlHidden(field, row, col) } </hidden> </field> } def cellToXmlVisible(field: IField, row: Int, col: Int) = {<cell row={ row.toString } col={ col.toString }>{ field.showVisibleCell(row, col).toString }</cell>} def cellToXmlHidden(field: IField, row: Int, col: Int) = {<cell row={ row.toString } col={ col.toString }>{ field.showInvisibleCell(row, col).toString }</cell>} def saveField(field: IField): Unit = saveString(field) def saveString(field: IField): Unit = { import java.io._ val pw = Try(new PrintWriter(new File("C:\\Playground\\minesweeperpublic\\src\\main\\data\\field.xml"))) pw match { case Success(pw) => val prettyPrinter = new PrettyPrinter(120, 4) val hiddenField = new Field(field.hidden) val visibleField = new Field(field.matrix) val xml = prettyPrinter.format(fieldToXml(field)) pw.write(xml) case Failure(exception) => throw exception } pw.get.close } def loadPlayerScores(filePath: String): Seq[(String, Int)] = { val tryLoadScores = Try { val file = new File(filePath) val rootElem: Elem = XML.loadFile(file) val scores = (rootElem \ "score").map { scoreElem => val playerName = (scoreElem \ "player").text val score = (scoreElem \ "value").text.toInt (playerName, score) } scores.sortBy { case (_, score) => -score }.take(10) } tryLoadScores match { case Success(scores) => scores case Failure(exception) => println(s"An error occurred while loading scores: ${exception.getMessage}") Seq.empty } } def savePlayerScore(playerName: String, score: Int, filePath: String): Unit = { val maybeFile = Try(new File(filePath)) val file = maybeFile.getOrElse(throw new Exception("File not found")) val maybeRootElement = Try { val rootElem: Elem = XML.loadFile(file) rootElem } val rootElem = maybeRootElement.getOrElse( <scores></scores>) val newScoreElem = <score> <player>{playerName}</player> <value>{score}</value> </score> val updatedRootElem = rootElem.copy(child = rootElem.child ++ Seq(newScoreElem)) Try { val printer = new PrettyPrinter(80, 2) val writer = new PrintWriter(new FileWriter(file)) writer.write(printer.format(updatedRootElem)) writer.close() } } override def loadField: Option[IField] = { val maybeFile: Try[Elem] = Try(scala.xml.XML.loadFile("C:\\Playground\\minesweeperpublic\\src\\main\\data\\field.xml")) val file = maybeFile match { case Success(file) => file case Failure(exception) => throw exception } val size = (file \\ "field" \@ "size").toInt val matrixOption = Some(Default.scalableMatrix(size, "~")) val hiddenOption = Some(Default.scalableMatrix(size, "~")) val fieldOption = Some(Default.scalableField(size, "~")) val cellNodesVisible: NodeSeq = (file \\ "field" \\ "matrix" \\ "cell") val matrix = cellNodesVisible.foldLeft(matrixOption.get) { (m, cell) => val row: Int = (cell \ "@row").text.toInt val col: Int = (cell \ "@col").text.toInt val symbol = (cell.text.trim) m.replaceCell(row, col, symbol) } val cellNodesHidden: NodeSeq = (file \\ "field" \\ "hidden" \\ "cell") val hidden = cellNodesHidden.foldLeft(hiddenOption.get) { (h, cell) => val row: Int = (cell \ "@row").text.toInt val col: Int = (cell \ "@col").text.toInt val symbol = (cell.text.trim) h.replaceCell(row, col, symbol) } fieldOption.map { f => Default.mergeMatrixToField(matrix, hidden) } } }
## 프론트엔드 1. ⭐ 브라우저 렌더링 과정을 설명해주세요. 2. 브라우저는 어떻게 동작 하나요? 3. Webpack, Babel, Polyfill에 대해 설명해주세요. 4. ESLint와 Prettier에 대해 설명해주세요. 5. SPA와 MPA에 대해 설명해주세요. 6. ⭐ CSR과 SSR의 차이는 무엇인가요? 7. ⭐ CORS와 해결 경험을 말씀해주세요. 8. bundle의 사이즈를 줄이려면 어떻게 해야 하나요? 9. ⭐ 쿠키, 세션, 웹스토리지의 차이에 대해 설명해주세요. 1. 브라우저에서 탭 이동 혹은 탭 종료 시에는 세션 스토리지에 어떤 영향을 끼치나요? 10. ⭐ 로그인 처리를 할 때 쿠키와 세션을 어떻게 사용하시나요? 11. ⭐ 토큰 기반 인증 방식에 대해 설명해주세요. 1. ⭐ JWT 토큰을 쿠키에 저장했을 때 취약점에 대해 설명해주세요. 12. ⭐ 크로스 브라우징에 대해 설명해주세요. 1. 크로스 브라우징 이슈를 해결했던 경험을 말씀해주세요. 13. 웹사이트 성능 최적화에는 어떤 방법이 있나요? 14. 객체 지향 프로그래밍이란 무엇인가요? 1. 객체 지향 프로그래밍의 특징에 대해 말씀해주세요. 2. 객체 지향 프로그래밍의 장단점에 대해 말씀해주세요. 15. ⭐ REST API에 대해 설명해주세요. 16. Git Flow에 대해 설명해주세요. 17. ⭐ SEO에 대해 설명해주세요. 18. BOM과 DOM에 대해 설명해주세요. 19. ⭐ 리플로우와 리페인트에 대해 설명해주세요. 1. 리플로우와 리페인트의 발생 조건에 대해 설명해주세요. 2. visibility 속성은 리플로우를 발생시킬까요? 20. Agile에 대해 설명해주세요. 21. dependencies 와 devDependencies 차이에 대해 설명해주세요. 22. XSS와 CSRF에 대해 설명해주세요. 23. 인증과 인가에 대해 설명해주세요. 24. package.json에서 private에 대해 설명해주세요. 25. 프로젝트를 npm에 배포하려면 어떤 설정이 필요할까나요? 26. ⭐ SEO는 어떤 식으로 신경쓰셨나요? 27. ⭐ 어플리케이션의 성능은 어떤식으로 측정하셨나요? 28. LightHouse 결과가 좋지 않을 때, 프로젝트에서 병목 현상은 어떻게 해결할 수 있을까요? 29. ⭐ 주소창에 주소를 입력했을 때의 흐름을 설명해주세요. ## 네트워크 1. 웹 프로토콜에 대해 설명해주세요. 2. ⭐ HTTP에 대해 설명해주세요. 1. ⭐ HTTP의 GET, POST를 비교 설명해주세요. 2. HTTP의 PUT, PATCH를 비교 설명해주세요. 3. ⭐ HTTP의 Status Code에 대해 설명해주세요. 4. ⭐ HTTP와 HTTPS의 차이점에 대해 설명해주세요. 5. HTTPS의 동작 방식에 대해 설명해주세요. 3. TCP와 UDP를 비교 설명해주세요. 4. TCP가 신뢰성을 보장하는 방법에 대해 설명해주세요. 5. TCP의 3-Way-Handshake와 4-Way-Handshake에 대해 설명해주세요. ## 운영체제 1. 운영체제의 정의에 대해 설명해주세요. 2. 운영체제의 메모리 영역에 대해 설명해주세요. 3. ⭐ 프로세스와 스레드를 비교 설명해주세요. 1. 스레드에서 독립적인 Stack 메모리 영역이 필요한 이유에 대해 설명해주세요. 4. 멀티 프로세스와 멀티 스레드를 비교 설명해주세요. 5. 문맥 전환 (Context Switch)에 대해 설명해주세요 6. 교착상태 (Deadlock)에 대해 설명해주세요. 1. 교착상태의 발생 조건에 대해 설명해주세요. 7. 페이징과 세그멘테이션에 대해 설명해주세요. 8. 메모리 단편화에 대해 설명해주세요. 9. 기아 상태에 대해 설명해주세요. 10. 경쟁 상태에 대해 설명해주세요. 11. 뮤텍스와 세마포어에 대해 설명해주세요. 12. 가상 메모리에 대해 설명해주세요. 13. 페이지 교체 알고리즘을 아는대로 설명해주세요. 14. 요구 페이징에 대해 설명해주세요. ## 알고리즘 및 자료구조 1. ⭐ 스택과 큐의 차이점에 대해 설명해주세요. 2. 좋은 코드의 조건이 뭘까요? 3. 좋은 알고리즘의 조건이 뭘까요? 4. 정확도가 동일하다면 그 다음으로 고려해야 될 조건이 뭘까요? 5. 시간 복잡도는 매우 낮지만 메모리를 매우 많이 사용한다면 어떻게 대처할 수 있을까요? 6. 완벽한 보안을 갖출 수 있는 알고리즘이 있을까요? 7. ⭐ 알고리즘은 어떻게 공부하셨나요? 8. ⭐ 알고리즘 문제는 몇 개 정도 풀어보셨나요? 풀었던 알고리즘 문제 중에서 어려웠던 개념은 어떤게 있나요? (진짜 어려웠던 DFS, BFS 얘기했다가 집중적으로 개털렸다. 순진하게 진짜 어려웠던거 대답해서 얻어맞지 말고 현명하게 대답하자 ^^) 1. DFS와 BFS 개념에서 어떤 부분이 특히 어려우신가요? (진짜 어려웠던 재귀 얘기했다가 바로 손코딩 참교육을 당했다.) 2. 재귀를 사용하지 않고 DFS와 BFS를 구현한다면 어떻게 할 수 있을까요? 3. 자바스크립트의 flat 메소드를 손코딩으로 구현해보세요. 9. Array와 연결 리스트를 비교 설명해주세요. 1. 단일 연결 리스트와 이중 연결 리스트를 비교 설명해주세요. 10. 힙에 대해 설명해주세요. 11. 이진 트리와 완전 이진 트리에 대해 설명해주세요. 12. 해시 테이블에 대해 설명해주세요. 1. 좋은 해시 함수의 조건은 뭘까요? ## 프로젝트 관련 1. ⭐ 포트폴리오의 프로젝트와 담당하신 파트를 소개해주세요. 2. 팀 프로젝트에서 본인의 기여도는 얼마 정도라고 생각하시나요? 3. ⭐ 프로젝트에서 기술적으로 어려웠던 점과 해결 방법에 대해 설명해주세요. 4. ⭐ 프로젝트에서 협업은 어떤 식으로 진행하셨나요? 5. 프로젝트에서 아쉬웠던 부분에 대해 설명해주세요. 6. ⭐ 프로젝트에서 OAuth에 기반한 로그인을 구현하셨는데 OAuth와 동작 방식에 대해 설명해주세요. 1. 소셜 로그인 플로우에 대해 설명해주세요. 2. ⭐ 프로젝트에서 JWT 토큰을 쿠키에 저장한 이유를 설명해주세요. ## HR 및 컬쳐핏 1. ⭐ 자기소개 부탁드립니다. 2. ⭐ 이전 회사를 1달 만에 퇴사하신 이유가 뭔가요? 3. ⭐ 본인의 장단점을 말씀해주세요. 4. ⭐ 저희 회사에 지원하신 이유 또는 동기가 뭔가요? 1. 그런 이유 또는 동기를 갖게 된 경험이 있나요? 5. ⭐ 멋쟁이사자처럼의 커리큘럼은 어떻게 진행되나요? 6. 개발과 관련해서 기존의 생각을 뒤엎을만큼 강한 인상을 받았던 글이나 영상이 있으면 소개해주세요. 7. ⭐ 요즘은 어떤 공부를 하고 계신가요? 8. 개발 공부는 어떤 자료를 많이 참고하시나요? 9. ⭐ 향후 커리어 적으로 목표가 있나요? 1. 그런 목표를 갖게 된 계기가 있나요? 10. ⭐ 개발자가 되고 싶은 계기가 뭔가요? 11. ⭐ 프론트엔드를 선택한 이유는 뭔가요? 12. ⭐ 개발자가 되기 위해 편입이나 전과는 시도해보지 않았나요? 13. 기존의 전공을 완전히 포기하는게 어렵지 않았나요? 14. ⭐ 협업에서 기억에 가장 남는 상황에 대해 설명해주세요. 15. ⭐ 협업에서 어려웠던 경험이 있었나요? 1. 어려웠던 이유가 뭐라고 생각하시나요? 2. 그 때로 다시 돌아간다면 어떻게 행동하실 건가요? 16. 자기 주장이 매우 강한 사람과 소통할 경우 어떻게 대응했었나요? 17. 좋은 팀장의 기준은 뭘까요? 18. 좋은 팀원의 기준은 뭘까요? 19. 팀장 역할을 맡았을 때, 지원자님에게 비협조적이고 적대적인 팀원이 있다면 어떻게 대처하실건가요? 20. “팀에서 1인분을 한다”고 할 때, 1인분은 어떤걸 의미하는걸까요? 21. 코드 리뷰로 인해 본인의 코드를 전부 고쳐야한다면 어떻게 할 것인가요? 22. 훗날 현업에서 일하면서 기술적인 어려움 등으로 개발자가 된 것을 후회할 상황이 생긴다면 어떻게 할 것인가요? 23. ⭐ 최신 기술 트렌드는 어떻게 추적하시나요? 1. 그렇게 찾은 최신 기술을 사용해보신 적이 있나요? 24. 개발 기간을 촉박하게 요구하는 경우 어떻게 하시나요? 25. 슬럼프가 올때 어떻게 대처 하시나요? 26. 본인만의 스트레스 해소 방법이 있으신가요? 27. 수행해야 하는 주제가 굉장히 어려운 주제라서, 나혼자서 해결 못할 일이 주어졌다고 가정해 볼게요. 어떻게 하실 건가요? 28. ⭐ 저희 회사에서 지원자를 뽑아야하는 이유가 있나요? 29. ⭐ 희망 연봉은 얼마나 되시나요? 30. ⭐ 저희 회사에 대해 궁금하신 점 질문해주세요.
package com.zeco.spring.core; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component public class FootballCoach implements Coach{ public FootballCoach() { System.out.println("in the football coach class"); } @Override public String getDailyWorkout() { return "tap the ball 25 times boy"; } //define init method @PostConstruct public void doStuff(){ System.out.println("in my do stuff method " + getClass().getSimpleName()); } //define destroy method @PreDestroy public void cleanStuff(){ System.out.println("in my clean stuff method " + getClass().getSimpleName()); } }
package com.ggggght.learningjava8.leetcode; import java.util.Arrays; /** <p><big><small>给定一个二维矩阵 <code>matrix</code>,</small></big>以下类型的多个请求:</p> <ul> <li><big><small>计算其子矩形范围内元素的总和,该子矩阵的 <strong>左上角</strong> 为 <code>(row1,&nbsp;col1)</code> ,<strong>右下角</strong> 为 <code>(row2,&nbsp;col2)</code> 。</small></big></li> </ul> <p>实现 <code>NumMatrix</code> 类:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code>&nbsp;给定整数矩阵 <code>matrix</code> 进行初始化</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code>&nbsp;返回<big><small> <strong>左上角</strong></small></big><big><small> <code>(row1,&nbsp;col1)</code>&nbsp;、<strong>右下角</strong>&nbsp;<code>(row2,&nbsp;col2)</code></small></big> 所描述的子矩阵的元素 <strong>总和</strong> 。</li> </ul> <p>&nbsp;</p> <p><strong>示例 1:</strong></p> <p><img src="https://pic.leetcode-cn.com/1626332422-wUpUHT-image.png" style="width: 200px;" /></p> <pre> <strong>输入:</strong> ["NumMatrix","sumRegion","sumRegion","sumRegion"] [[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]] <strong>输出:</strong> [null, 8, 11, 12] <strong>解释:</strong> NumMatrix numMatrix = new NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (红色矩形框的元素总和) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (绿色矩形框的元素总和) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和) </pre> <p>&nbsp;</p> <p><strong>提示:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m,&nbsp;n &lt;=&nbsp;200</code><meta charset="UTF-8" /></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= matrix[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li><meta charset="UTF-8" />最多调用 <code>10<sup>4</sup></code> 次&nbsp;<code>sumRegion</code> 方法</li> </ul> <div><div>Related Topics</div><div><li>设计</li><li>数组</li><li>矩阵</li><li>前缀和</li></div></div><br><div><li>👍 354</li><li>👎 0</li></div> */ public class Leetcode304 { class NumMatrix { int[][] arr; int[][] matrix; public NumMatrix(int[][] matrix) { this.matrix = matrix; arr = new int[matrix.length][matrix[0].length]; for (int i = 0; i < arr.length; i++) { for (int i1 = 0; i1 < arr[i].length; i1++) { arr[i][i1] = i == 0 && i1 == 0 ? matrix[0][0] : (i1 - 1 < 0 ? arr[i - 1][arr[i - 1].length - 1] : arr[i][i1 - 1]) + matrix[i][i1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { if (row1 == row2 && col1 == col2) return matrix[row1][col1]; if (row1 == 0 && col1 == 0 && col2 == matrix[0].length - 1) return arr[row2][col2]; int ans = 0; for (int i = 0; i <= row2 - row1; i++) { var tmp = 0; if (i + row1 - 1 < 0 && col1 - 1 < 0) { } else if (col1 - 1 < 0) { tmp = arr[i + row1 - 1][arr[i].length - 1]; } else { tmp = arr[i + row1][col1 - 1]; } ans += arr[i + row1][col2] - tmp; } return ans; } } /** * <a href='https://leetcode-cn.com/problems/range-sum-query-2d-immutable/solution/er-wei-qian-zhui-he-jian-dan-tui-dao-tu-sqekv/'>二维</a> */ class NumMatrix1 { int[][] arr; public int sumRegion(int row1, int col1, int row2, int col2) { return this.arr[row2 + 1][col2 + 1] + this.arr[row1][col1] - this.arr[row1][col2 + 1] - this.arr[row2 + 1][col1]; } public NumMatrix1(int[][] matrix) { arr = new int[matrix.length+1][matrix[0].length+1]; for (int i = 1; i < arr.length; i++) { for (int i1 = 1; i1 < arr[0].length; i1++) { arr[i][i1] = arr[i - 1][i1] + arr[i][i1 - 1] - arr[i - 1][i1 - 1] + matrix[i-1][i1-1]; } } for (int[] ints : arr) { System.out.println(Arrays.toString(ints)); } } } }
"use client" import React, { useState } from 'react'; const NameForm = ({ onSubmit }) => { const [name, setName] = useState(''); const handleChange = (e) => { setName(e.target.value); }; const handleSubmit = (e) => { // prevent the default behavior of an element from triggering e.preventDefault(); onSubmit(name); }; return ( <div className='bg-gray-50 w-80 m-auto mb-2 rounded'> <form onSubmit={handleSubmit} className='m-auto flex justify-center p-2'> <input className='border rounded p-2 mr-2 w-50 focus:outline-none' type="text" value={name} onChange={handleChange} placeholder="Enter a Name" /> <button className='bg-orange-400 text-gray-50 rounded p-2 ' type="submit">Submit</button> </form> </div> ); }; export default NameForm;
#pragma once #include "LinkedList.h" #include <iostream> #include <iomanip> #include <string> #include <math.h> using namespace std; class Hash { private: LinkedList* hashTable; //hashTable is a one-dimensional array of LinkedList int m; //slots number of the hash table public: Hash(int size); ~Hash(); bool hashInsert(string foodID, string name, string supplierID, double price); bool hashDelete(string foodID, string name, string supplierID); bool hashSearch(string foodID, string name, string supplierID); void hashDisplay(); int hashFunction(string key); //add any other auxiliary functions here //---- }; //constructor Hash::Hash(int size) { hashTable = new LinkedList[size]; m = size; } //Destructor Hash::~Hash() { delete[]hashTable; //---- } //hashInsert inserts a Food with the relevant info. into the hashTable. //it returns true if the data is inserted successfully and false otherwise bool Hash::hashInsert(string foodID, string name, string supplierID, double price) { int hashIndex = hashFunction(foodID); if (hashTable[hashIndex].insertFood(foodID, name, supplierID, price)) { cout << "slot index = " << hashIndex << endl; return true; } return false; //---- } //hashDelete deletes a Food with the relevant key from the hashTable. //it returns true if it is deleted successfully and false otherwise //Note: key is the combination of foodID, name and supplierID bool Hash::hashDelete(string foodID, string name, string supplierID) { int hashIndex = hashFunction(foodID); if (hashTable[hashIndex].deleteFood(foodID)) { //---- cout << "\n"; cout << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is deleted from hash table." << endl; return true; } return false; } //This function searches for a key inside the hash table and //return true if it is found and false otherwise //Note: key is the combination of foodID, name and supplierID bool Hash::hashSearch(string foodID, string name, string supplierID) { //---- bool found = true; int hashIndex = hashFunction(foodID); if (!hashTable[hashIndex].searchFood(foodID)) { found = false; } if (found) cout << "\n" << left << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is found inside the hash table." << endl; if (!found) cout << "\n" << left << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is NOT found inside the hash table." << endl; return found; } //This function prints all the elements from the hash hashTable. void Hash::hashDisplay() { for (int i = 0; i < m; i++) { if (hashTable[i].getSize() == 0) { cout << "HashTable[" << i << "] is empty, size = 0" << endl; } else { cout << "HashTable[" << i << "], " << "size = " << hashTable[i].getSize() << endl; hashTable[i].displayList(); cout << endl; } } //---- //---- } //This is the hash function you will need to design, test and refine //Given a Food key, the function should return the slot index where it //will be hashed to int Hash::hashFunction(string key) { int sum = 0; for (int i = 0; i < key.size(); i++) { sum += int(key.at(i)); } return sum % m; //---- }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class DefaultPropsComp extends Component { render() { let message1 = ''; if (this.props.boolV === false) { message1 = 'boolV 기본값이 false 임'; } let message2 = ''; if (this.props.boolVWithoutDefault === false) { message2 = 'boolVWidthoutDefault 기본값이 false 임'; } return ( <div className="message-container"> {message1} {message2} </div> ); } } DefaultPropsComp.propTypes = { boolV: PropTypes.bool, boolVWithoutDefault: PropTypes.bool, }; DefaultPropsComp.defaultProps = { boolV: false, }; export default DefaultPropsComp;
import { Message } from 'discord.js'; import CommandController, { chatCommand, Command } from '../controllers/CommandController'; import fs from 'fs/promises'; @chatCommand() class Reload implements Command { name = 'reload'; aliases = ['r']; description = 'Recarrega os comandos do bot'; usage = 'reload'; hideHelp = true; async exec(message: Message, args: string[]) { message.delete(); let files = await fs.readdir('./commands/'); // Clear the commands from the controller CommandController.commands = []; let i = 0; for (let file of files) { if (file.endsWith('.ts')) { delete require.cache[require.resolve(`./${file}`)]; i++; } } files = await fs.readdir('./commands'); for (let file of files) { if (file.endsWith('.ts')) { require(`./${file}`); } } let reloadMessage = await message.channel.send(`${i} comandos foram recarregados`); setTimeout(() => reloadMessage.delete(), 1500); } }
import React, { ComponentType, FC, lazy } from 'react' import { RouteObject, useRoutes } from 'react-router-dom' import LayoutPage, { OutletLayout } from '../pages/layout/layoutPage' import LoginPage from '../presentation/login/loginPage' export type RouteWrapperProps = { element: React.LazyExoticComponent<ComponentType<any>> } const RouteWrapper: React.FC<RouteWrapperProps> = props => { const { element: ElementComponent } = props return <ElementComponent /> } export const RenderRouter: FC = () => { const routeList: Array<RouteObject> = [ { path: '/', element: <LayoutPage />, children: [ { path: '', element: <OutletLayout />, children: [ { path: '', element: <RouteWrapper element={lazy(() => import('@/presentation/home/homePage'))} /> } ] }, { path: 'system', element: <OutletLayout />, children: [ { path: 'project', element: <RouteWrapper element={lazy(() => import('@/presentation/project/projectPage'))} /> }, { path: 'team', element: <RouteWrapper element={lazy(() => import('@/presentation/team/teamPage'))} /> } ] }, { path: 'user', element: <OutletLayout />, children: [ { path: '', element: <RouteWrapper element={lazy(() => import('@/presentation/user/userPage'))} /> }, { path: 'detail/:session_id/:user_id', element: <RouteWrapper element={lazy(() => import('@/presentation/user/useDetailPage'))} /> } ] }, { path: '/jsErr', element: <OutletLayout />, children: [ { path: '', element: <RouteWrapper element={lazy(() => import('@/presentation/jsErr/jsErrPage'))} /> }, { path: 'detail/:error_id', element: <RouteWrapper element={lazy(() => import('@/presentation/jsErr/jsErrDetailPage'))} /> } ] }, { path: '/performance', element: <RouteWrapper element={lazy(() => import('@/presentation/performance/performancePage'))} /> }, { path: '/http', element: <RouteWrapper element={lazy(() => import('@/presentation/http/httpPage'))} /> }, { path: '/httpErr', element: <RouteWrapper element={lazy(() => import('@/presentation/httpErr/httpErrPage'))} /> }, { path: '/staticErr', element: <RouteWrapper element={lazy(() => import('@/presentation/staticErr/staticErrPage'))} /> } ] }, { path: '/login', element: <LoginPage /> } ] return useRoutes(routeList) }
<% if Rails.env.development? %> <%= debug @support_request.attributes %> <% end %> <div class="govuk-grid-row"> <div class="govuk-grid-column-two-thirds"> <h1 class="govuk-heading-l"> <% if @support_request.submitted? %> Your request has been submitted <% else %> <%= I18n.t("support_request.section.submit_request") %> <% end %> </h1> <h2 class="govuk-heading-m"> <%= I18n.t("support_request.section.about_you") %> </h2> <dl class="govuk-summary-list"> <div class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> Your name </dt> <dd class="govuk-summary-list__value"> <%= @current_user.full_name %> </dd> <dd class="govuk-summary-list__actions"> </dd> </div> <div class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> Your email address </dt> <dd class="govuk-summary-list__value"> <%= @current_user.email %> </dd> <dd class="govuk-summary-list__actions"> </dd> </div> </dl> <h2 class="govuk-heading-m"> <%= I18n.t("support_request.section.request_summary") %> </h2> <dl class="govuk-summary-list"> <div id="support-request-school" class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> School </dt> <dd class="govuk-summary-list__value"> <%= @support_request.school_name %> </dd> <dd class="govuk-summary-list__actions"> <% unless @support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 2), class: "govuk-link", id: "edit-school" %> <% end %> </dd> </div> <div id="support-request-category" class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> Attached specification </dt> <dd class="govuk-summary-list__value"> <% if @support_request.journey %> <%= @support_request.journey.created_at %> <% else %> None <% end %> </dd> <dd class="govuk-summary-list__actions"> <% if @current_user.journeys.any? && !@support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 3), class: "govuk-link", id: "edit-specification" %> <% end %> </dd> </div> <div id="support-request-category" class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> <%= I18n.t("support_request.label.category") %> </dt> <dd class="govuk-summary-list__value"> <% if @support_request.journey %> <%= @support_request.journey.category.title %> <% else %> <%= @support_request.category&.title %> <% end %> </dd> <dd class="govuk-summary-list__actions"> <% unless @support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 4), class: "govuk-link", id: "edit-category" %> <% end %> </dd> </div> <div id="support-request-message" class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> <%= I18n.t("support_request.label.message") %> </dt> <dd class="govuk-summary-list__value"> <%= @support_request.message_body %> </dd> <dd class="govuk-summary-list__actions"> <% unless @support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 5), class: "govuk-link", id: "edit-message" %> <% end %> </dd> </div> <div class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> <%= I18n.t("request.label.procurement_amount") %> </dt> <dd class="govuk-summary-list__value"> <%= @support_request.procurement_amount %> </dd> <dd class="govuk-summary-list__actions"> <% unless @support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 6), class: "govuk-link", id: "edit-procurement-amount" %> <% end %> </dd> </div> <div class="govuk-summary-list__row"> <dt class="govuk-summary-list__key"> <%= I18n.t("request.label.special_requirements") %> </dt> <dd class="govuk-summary-list__value"> <%= @support_request.special_requirements %> </dd> <dd class="govuk-summary-list__actions"> <% unless @support_request.submitted? %> <%= link_to I18n.t("generic.button.change_answer"), edit_support_request_path(@support_request, step: 7), class: "govuk-link", id: "edit-special-requirements" %> <% end %> </dd> </div> </dl> <% unless @support_request.submitted? %> <p class="govuk-body"> <%= I18n.t("support_request.response_time") %> </p> <%= button_to I18n.t("support_request.button.send"), support_request_submission_path(@support_request), class: "govuk-button", method: :patch, data: { disable_with: "Submitting..." } %> <% end %> </div> </div>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sect1 PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ <!ENTITY % general-entities SYSTEM "../../general.ent"> %general-entities; <!ENTITY libsigsegv-download-http "&gnu-http;/libsigsegv/libsigsegv-&libsigsegv-version;.tar.gz"> <!ENTITY libsigsegv-download-ftp "&gnu-ftp;/libsigsegv/libsigsegv-&libsigsegv-version;.tar.gz"> <!ENTITY libsigsegv-md5sum "63a2b35f11b2fbccc3d82f9e6c6afd58"> <!ENTITY libsigsegv-size "456 KB"> <!ENTITY libsigsegv-buildsize "3,6 MB (com os testes)"> <!ENTITY libsigsegv-time "menos que 0,1 UPC (com os testes)"> ]> <sect1 id="libsigsegv" xreflabel="libsigsegv-&libsigsegv-version;"> <?dbhtml filename="libsigsegv.html"?> <title>libsigsegv-&libsigsegv-version;</title> <indexterm zone="libsigsegv"> <primary sortas="a-libsigsegv">libsigsegv</primary> </indexterm> <sect2 role="package"> <title>Introdução a libsigsegv</title> <para> "libsigsegv" é uma biblioteca para lidar com falhas de página no modo de usuário(a). Uma falha de página ocorre quando um aplicativo tenta acessar uma região da memória que não está disponível atualmente. Capturar e manusear uma falha de página é uma técnica útil para implementar memória virtual paginável, acesso mapeado em memória a bases de dados persistentes, coletores geracionais de lixo, manuseadores de estouro de pilha e memória compartilhada distribuída. </para> &lfs113_checked; <bridgehead renderas="sect3">Informação do Pacote</bridgehead> <itemizedlist spacing="compact"> <listitem> <para> Transferência (HTTP): <ulink url="&libsigsegv-download-http;"/> </para> </listitem> <listitem> <para> Transferência (FTP): <ulink url="&libsigsegv-download-ftp;"/> </para> </listitem> <listitem> <para> Soma de verificação MD5 da transferência: &libsigsegv-md5sum; </para> </listitem> <listitem> <para> Tamanho da transferência: &libsigsegv-size; </para> </listitem> <listitem> <para> Espaço em disco estimado exigido: &libsigsegv-buildsize; </para> </listitem> <listitem> <para> Tempo de construção estimado: &libsigsegv-time; </para> </listitem> </itemizedlist> <para condition="html" role="usernotes"> Observações de Usuário(a): <ulink url="&blfs-wiki;/libsigsegv"/> </para> </sect2> <sect2 role="installation"> <title>Instalação do libsigsegv</title> <para> Instale <application>libsigsegv</application> executando os seguintes comandos: </para> <screen><userinput>./configure --prefix=/usr \ --enable-shared \ --disable-static &amp;&amp; make</userinput></screen> <para> Para testar os resultados, emita: <command>make check</command>. </para> <para> Agora, como o(a) usuário(a) <systemitem class="username">root</systemitem>: </para> <screen role="root"><userinput>make install</userinput></screen> </sect2> <sect2 role="commands"> <title>Explicações do Comando</title> <para> <parameter>--enable-shared</parameter>: Essa chave garante que as bibliotecas compartilhadas sejam compiladas. </para> <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../../xincludes/static-libraries.xml"/> </sect2> <sect2 role="content"> <title>Conteúdo</title> <segmentedlist> <segtitle>Aplicativos Instalados</segtitle> <segtitle>Biblioteca Instalada</segtitle> <segtitle>Diretórios Instalados</segtitle> <seglistitem> <seg> Nenhum </seg> <seg> libsigsegv.so </seg> <seg> Nenhum </seg> </seglistitem> </segmentedlist> <variablelist> <bridgehead renderas="sect3">Descrições Curtas</bridgehead> <?dbfo list-presentation="list"?> <?dbhtml list-presentation="table"?> <varlistentry id="libsigsegv-lib"> <term><filename class="libraryfile">libsigsegv.so</filename></term> <listitem> <para> é uma biblioteca para lidar com falhas de página no modo de usuário(a) </para> <indexterm zone="libsigsegv libsigsegv-lib"> <primary sortas="c-libsigsegv">libsigsegv.so</primary> </indexterm> </listitem> </varlistentry> </variablelist> </sect2> </sect1>
import React, { useState, useContext } from "react"; import Select from "react-select"; import { ContextApp } from "../../reducers/products.js"; const ProductsFilter = () => { const { state, dispatch } = useContext(ContextApp); const [filterParam, setFilterParam] = useState('price'); const [filterValue, setFilterValue] = useState(''); const selectOptions = [ { value: 'product', label: 'Product' }, { value: 'price', label: 'Price'}, { value: 'brand', label: 'Brand' } ] const handleOnChange = (e) => { e.preventDefault(); setFilterValue(e.target.value); }; const handleChangeSelect = (option) => { setFilterParam(option.value); }; const handleFilter = (e) => { e.preventDefault(); if (state.filter.value != filterValue || state.filter.param !== filterParam) { dispatch({ type: 'products/change_page', currentPage: 0 }); dispatch({ type: 'products/get_filtered_ids.success', payload: [] }); } else { if (state.filter.isActive === true) return } dispatch({ type: 'products/filter.change', payload: { isActive: true, param: filterParam || state.filter.param, value: filterParam === 'price' && filterValue ? parseFloat(filterValue) : filterValue } }); }; const resetFilter = (e) => { e.preventDefault(); setFilterValue(''); if (state.filter.isActive === false && state.filter.value === '') return dispatch({ type: 'products/change_page', currentPage: 0 }); dispatch({ type: 'products/get_filtered_ids.success', payload: [] }); dispatch({ type: 'products/filter.change', payload: { isActive: false, param: state.filter.param, value: '' } }); }; return ( <div className="container"> <form className="row g-3 justify-content-center text-center"> <div className="col-auto"> <Select onChange={ handleChangeSelect } options={ selectOptions } defaultValue={ selectOptions[1] } /> </div> <div className="col-auto"> <input className="form-control" name="param" type="text" placeholder="Filter text..." onChange={ handleOnChange } value={ filterValue } /> </div> <div className="col-auto"> <button className="btn btn-primary mb-3" onClick={ handleFilter } >OK</button> <button className="btn btn-danger mb-3" onClick={ resetFilter } >X</button> </div> </form> </div> ); }; export default ProductsFilter;
package com.ifba.educampo.controller; import com.ifba.educampo.domain.Associate; import com.ifba.educampo.domain.LocalOffice; import com.ifba.educampo.requests.LocalOfficePostRequestBody; import com.ifba.educampo.requests.LocalOfficePutRequestBody; import com.ifba.educampo.service.LocalOfficeService; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/local-offices") @RequiredArgsConstructor public class LocalOfficesController { // Classe de controle para as Delegacias (Escritório Local) private final LocalOfficeService localOfficeService; @GetMapping public ResponseEntity<Page<LocalOffice>> listLocalOffices(Pageable pageable){ return ResponseEntity.ok(localOfficeService.listAll(pageable)); } @GetMapping(path = "/{id}") public ResponseEntity<LocalOffice> findLocalOfficeById(@PathVariable long id){ return ResponseEntity.ok(localOfficeService.findLocalOffice(id)); } @GetMapping(path = "/{id}/associates") public ResponseEntity<Page<Associate>> findAssociatesByLocalOfficeId(@PathVariable long id, Pageable pageable){ return ResponseEntity.ok(localOfficeService.listAllAssociates(id, pageable)); } @PostMapping public ResponseEntity<LocalOffice> save(@RequestBody LocalOfficePostRequestBody localOfficePostRequestBody){ return ResponseEntity.ok(localOfficeService.save(localOfficePostRequestBody)); } @DeleteMapping(path = "/{id}") public ResponseEntity<Void> delete(@PathVariable long id){ localOfficeService.delete(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @PutMapping public ResponseEntity<Void> replace(@RequestBody LocalOfficePutRequestBody localOfficePutRequestBody){ localOfficeService.replace(localOfficePutRequestBody); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @PatchMapping(path = "/{id}") public ResponseEntity<Void> updateFields(@PathVariable long id, Map<String, Object> fields){ localOfficeService.updateByFields(id, fields); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
<?php namespace ostark\upper\drivers; use GuzzleHttp\Exception\BadResponseException; use ostark\upper\exceptions\AkamaiApiException; /** * Class Akamai Driver * * @package ostark\upper\drivers * */ class Akamai extends AbstractPurger implements CachePurgeInterface { /** * @var string */ public $host; /** * @var string */ public $clientToken; /** * @var string */ public $clientSecret; /** * @var string */ public $accessToken; /** * @var string */ public $maxSize; /** * Purge cache by tag * * @param string $tag * * @return bool */ public function purgeTag(string $tag) { if ($this->useLocalTags) { return $this->purgeUrlsByTag($tag); } $this->sendRequest('production', 'POST', 'tag', $tag); $this->sendRequest('staging', 'POST', 'tag', $tag); return true; } /** * Purge cache by urls * * @param array $urls * * @return bool */ public function purgeUrls(array $urls) { foreach ($urls as $url) { if (!$this->sendRequest('production', 'POST', 'url', getenv('DEFAULT_SITE_URL') . $url)) { return false; } if (!$this->sendRequest('staging', 'POST', 'url', getenv('DEFAULT_SITE_URL') . $url)) { return false; } } return true; } /** * Purge entire cache * * @return bool */ public function purgeAll() { // TODO: Purge all in Akamai return true; // return $this->sendRequest('POST', 'purge_all'); } /** * Send API call * * @param string $method HTTP verb * @param string $type of purge * @param string $uri * @param array $headers * * @return bool * @throws \ostark\upper\exceptions\AkamaiApiException */ protected function sendRequest(string $environment = 'production', string $method = 'POST', string $type = "url", string $uri = "", array $headers = []) { // Akamai Open Edgegrid reads $_ENV which doesn't get populated by Craft, so filling in the blanks $_ENV['AKAMAI_HOST'] = getenv('AKAMAI_HOST'); $_ENV['AKAMAI_CLIENT_TOKEN'] = getenv('AKAMAI_CLIENT_TOKEN'); $_ENV['AKAMAI_CLIENT_SECRET'] = getenv('AKAMAI_CLIENT_SECRET'); $_ENV['AKAMAI_ACCESS_TOKEN'] = getenv('AKAMAI_ACCESS_TOKEN'); $_ENV['AKAMAI_MAX_SIZE'] = getenv('AKAMAI_MAX_SIZE'); $auth = \Akamai\Open\EdgeGrid\Authentication::createFromEnv(); $auth->setHttpMethod('POST'); $auth->setPath('/ccu/v3/invalidate/' . $type . '/' . $environment); $body = json_encode(array( 'objects' => array($uri) )); $auth->setBody($body); $context = array( 'http' => array( 'header' => array( 'Authorization: ' . $auth->createAuthHeader(), 'Content-Type: application/json', 'Content-Length: ' . strlen($body), ), 'method' => 'POST', 'content' => $body ) ); $context = stream_context_create($context); try { json_decode(file_get_contents('https://' . $auth->getHost() . $auth->getPath(), false, $context)); } catch (BadResponseException $e) { throw AkamaiApiException::create( $e->getRequest(), $e->getResponse() ); } return true; } }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatMenuModule, MatButtonModule } from '@angular/material'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { HeroesComponent } from './components/heroes/heroes.component'; import { FormsModule } from '@angular/forms'; import { HeroDetailComponent } from './components/hero-detail/hero-detail.component'; import { MessagesComponent } from './components/messages/messages.component'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { AppRoutingModule } from './modules/app-routing.module'; import { ApiService } from './services/api/api.service'; @NgModule({ declarations: [ AppComponent, HeroesComponent, HeroDetailComponent, MessagesComponent, DashboardComponent ], imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatMenuModule, MatButtonModule, AppRoutingModule, HttpClientModule, HttpModule ], providers: [ApiService], bootstrap: [AppComponent] }) export class AppModule { }
package Controllers import ( "forward-core/Models" "forward-core/NetUtils" "forward-core/Utils" "forward-server/Controllers/BaseCtrl" "forward-server/Service" "github.com/astaxie/beego/logs" ) type LoginCtrl struct { BaseCtrl.ConsoleCtrl } // @router /logout func (c *LoginCtrl) Logout() { c.ClearUserInfo() c.Ctx.Redirect(302, "/login") } // @router /login [get] func (c *LoginCtrl) Login() { c.TplName = "login.html" } func (c *LoginCtrl) DoLogin() { logs.Debug("用户登录") userName := c.GetString("userName") passWord := c.GetString("passWord") sysUser := Service.SysDataS.GetSysUserByName(userName) if sysUser == nil { logs.Debug("用户不存在") c.Data["json"] = Models.FuncResult{Code: 1, Msg: "用户名或密码错误"} c.ServeJSON() return } descryptPwd := Utils.GetMd5(passWord) logs.Debug("存储的密码:", sysUser.PassWord, " 输入的密码:", descryptPwd) if sysUser.PassWord == descryptPwd { if sysUser.Status == 1 { logs.Info("用户登录:", userName, " IP:", NetUtils.GetIP(&c.Controller)) loginUser := new(Models.LoginUser) loginUser.UserId = 1 loginUser.UserName = userName c.SetSession("userInfo", loginUser) //c.Ctx.Redirect(302, "/u/main") c.Data["json"] = Models.FuncResult{Code: 0, Msg: "用户名: " + userName + " IP:" + NetUtils.GetIP(&c.Controller)} c.ServeJSON() } if sysUser.Status == 0 { logs.Debug("此账号已被停用,ID:", sysUser.Id) //c.Ctx.Redirect(302, "/login") c.Data["json"] = Models.FuncResult{Code: 1, Msg: "您的账号已被停用"} c.ServeJSON() } } else { logs.Debug("用户登录失败") // c.Ctx.Redirect(302, "/login") c.Data["json"] = Models.FuncResult{Code: 1, Msg: "用户名或密码错误"} c.ServeJSON() } }
import 'package:auto_route/auto_route.dart'; import 'package:instagram_clone/data/auth/bloc/auth/auth_bloc.dart'; import 'package:instagram_clone/services/routes/guards/auth_guard.dart'; import 'package:instagram_clone/services/routes/nested_router.gr.dart'; @AutoRouterConfig(replaceInRouteName: 'Screen,Route') class NestedRouter extends $NestedRouter { NestedRouter({super.navigatorKey, required this.authBloc}); @override RouteType get defaultRouteType => const RouteType.material(); final AuthBloc authBloc; @override List<AutoRoute> get routes => [ AutoRoute(page: IntroRoute.page), AutoRoute(page: LoginRouter.page, keepHistory: false, children: [ AutoRoute(path: 'login', page: LoginRoute.page, initial: true), AutoRoute(path: 'register', page: RegisterRoute.page), ]), AutoRoute(page: StoryViewRoute.page, path: '/story-view'), AutoRoute(page: AddStoryRoute.page, path: '/add-story'), AutoRoute( path: '/', guards: [AuthGuard(authBloc: authBloc)], page: RouterPage.page, children: [ AutoRoute( initial: true, path: 'home', page: HomeRouter.page, children: [ AutoRoute( path: '', page: HomeRoute.page, ), AutoRoute(page: DMRoute.page, path: 'dm'), AutoRoute(page: MessagesRoute.page, path: 'messages'), AutoRoute(page: CreateRoomRoute.page, path: 'create-room'), ], ), CustomRoute(page: SearchRoute.page), CustomRoute(page: AddPostRoute.page), CustomRoute(page: HeartRoute.page), AutoRoute(path: 'profile', page: ProfileRouter.page, children: [ AutoRoute( page: ProfileRoute.page, path: '', keepHistory: true, maintainState: true), AutoRoute( page: UserProfileRoute.page, path: 'user-profile', keepHistory: false, maintainState: false), AutoRoute( page: EditProfileRoute.page, path: 'edit-profile', ) ]) ]), ]; }
from flask import Flask from flask_restx import Api from app.config import Config from app.views.query import query_ns def create_app(config: Config) -> Flask: """ creating an application :param config: :return: Flask """ application = Flask(__name__) application.config.from_object(config) application.app_context().push() return application def register_extensions(application: Flask) -> None: """ added a rout :param application: :return: None """ api = Api(application) api.add_namespace(query_ns) if __name__ == '__main__': app = create_app(Config()) register_extensions(app) app.run()
// src/App.tsx import React, { useEffect, useState } from 'react'; import { useForm, FormProvider, SubmitHandler } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from 'yup'; import { useNavigate } from 'react-router-dom'; import { toast, ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import axios from "../../plugins/axios"; import Input from './Input'; import './addStudent.scss'; const genderOptions = [ { value: 'M', label: 'Male' }, { value: 'F', label: 'Female' }, ]; const gradeOptions = [ { value: 'Be', label: 'Beginner' }, { value: 'El', label: 'Elementary' }, { value: 'Pr', label: 'Prep' }, { value: '1', label: 'One' }, { value: '2', label: 'Two' }, { value: '3', label: 'Three' }, { value: '4', label: 'Four' }, { value: '5', label: 'Five' }, { value: '6', label: 'Six' }, { value: '7', label: 'Seven' }, { value: '8', label: 'Eight' }, { value: 'IX', label: 'Nine' }, { value: 'X', label: 'Matric' }, ]; const statusOptions = [ { value: 'current', label: 'Current' }, { value: 'left', label: 'Left' }, ]; const sectionOptions = [ { value: 'A', label: 'A' }, { value: 'B', label: 'B' }, { value: 'C', label: 'C' }, { value: 'D', label: 'D' }, { value: 'E', label: 'E' }, { value: 'F', label: 'F' }, ]; interface StudentAdmissionFormData { name: string; family: string; // Assuming family is a string ID or similar gender: 'M' | 'F'; date_of_birth: string; // Using string to handle date inputs place_of_birth: string; religion: string; nationality: string; b_form_number?: string | null; last_school?: string | null; admitted_in_grade: string; status: string; academic_year: string; // Assuming academic_year is a string ID or similar section: string; roll_number?: string | null; remarks?: string | null; monthly_fees?: number | null; admission_fees?: number | null; examination_fees?: number | null; board_fees?: number | null; practical_fees?: number | null; } const schema = yup.object().shape({ name: yup.string().required('Name is required'), family: yup.string().required('Family is required'), gender: yup.string().oneOf(['M', 'F']).required('Gender is required'), date_of_birth: yup.date().required('Date of Birth is required'), place_of_birth: yup.string().required('Place of Birth is required'), religion: yup.string().required('Religion is required'), nationality: yup.string().required('Nationality is required'), b_form_number: yup.string().nullable().matches(/^\d{13}$/, 'Must be 13 digits'), last_school: yup.string().nullable(), admitted_in_grade: yup.string().required('Admitted Grade is required'), status: yup.string().oneOf(['current', 'left']).required('Status is required'), academic_year: yup.string().required('Academic Year is required'), section: yup.string().oneOf(['A', 'B', 'C', 'D', 'E', 'F']).required('Section is required'), roll_number: yup.string().nullable(), remarks: yup.string().nullable(), monthly_fees: yup.number().nullable().min(0).max(10000), admission_fees: yup.number().nullable().min(0).max(10000), examination_fees: yup.number().nullable().min(0).max(10000), board_fees: yup.number().nullable().min(0).max(10000), practical_fees: yup.number().nullable().min(0).max(10000), }); // const AddStudent = () => { const AddStudent: React.FC = () => { const methods = useForm<StudentAdmissionFormData>({ resolver: yupResolver(schema), }); const onSubmit: SubmitHandler<StudentAdmissionFormData> = (data) => { console.log(data); }; return ( <FormProvider {...methods}> <h1>Student Information Form</h1> <form onSubmit={methods.handleSubmit(onSubmit)}> <Input name="name" label="Name" validation={{ required: true }} /> <Input name="family" label="Family" validation={{ required: true }} /> <Input name="gender" label="Gender" type="select" options={genderOptions} validation={{ required: true }} /> <Input name="date_of_birth" label="Date of Birth" type="date" validation={{ required: true }} /> <Input name="place_of_birth" label="Place of Birth" validation={{ required: true }} /> <Input name="religion" label="Religion" validation={{ required: true }} /> <Input name="nationality" label="Nationality" validation={{ required: true }} /> <Input name="b_form_number" label="B-Form Number" validation={{ required: false }} /> <Input name="last_school" label="Last School" validation={{ required: false }} /> <Input name="admitted_in_grade" label="Admitted Grade" type="select" options={gradeOptions} validation={{ required: true }} /> <Input name="status" label="Status" type="select" options={statusOptions} validation={{ required: true }} /> <Input name="academic_year" label="Academic Year" validation={{ required: true }} /> <Input name="section" label="Section" type="select" options={sectionOptions} validation={{ required: true }} /> <Input name="roll_number" label="Roll Number" validation={{ required: false }} /> <Input name="remarks" label="Remarks" validation={{ required: false }} /> <Input name="monthly_fees" label="Monthly Fees" type="number" validation={{ required: false }} /> <Input name="admission_fees" label="Admission Fees" type="number" validation={{ required: false }} /> <Input name="examination_fees" label="Examination Fees" type="number" validation={{ required: false }} /> <Input name="board_fees" label="Board Fees" type="number" validation={{ required: false }} /> <Input name="practical_fees" label="Practical Fees" type="number" validation={{ required: false }} /> <button className="submit_btn" type="submit">Submit</button> </form> </FormProvider> ); }; export default AddStudent;
<app-card cardTitle="Part Information" [options]="false"> <aw-wizard #wizard class="arc-wizard" navBarLayout="large-filled-symbols"> <aw-wizard-step stepTitle="Basic Info" [navigationSymbol]="{ symbol: '&#xe8e9;', fontFamily: 'feather' }"> <form action="javascript:" #navigationForm=ngForm> <div class="row invoive-info"> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Part Name</label> : <input class="form-control input-md" name="partName" type="text" placeholder="Enter Part Name" [ngClass]="{'is-invalid': !partName.valid && (partName.dirty || partName.touched || isSubmit)}" #partName="ngModel" required partName [(ngModel)]="formInput.partName"> <label *ngIf="!partName.valid && (partName.dirty || partName.touched || isSubmit)" id="validation-partName-error" class="error jquery-validation-error small form-text invalid-feedback">Please enter Part Name</label> </div> </div> <div class="col-md-6"> <div class="form-group"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Part Code</label> <input class="form-control input-md" name="partCode" type="text" placeholder="Enter Part Code" [ngClass]="{'is-invalid': !partCode.valid && (partCode.dirty || partCode.touched || isSubmit)}" #partCode="ngModel" required partCode [(ngModel)]="formInput.partCode"> <label *ngIf="!partCode.valid && (partCode.dirty || partCode.touched || isSubmit)" id="validation-partCode-error" class="error jquery-validation-error small form-text invalid-feedback">Please enter a valid Part Code</label> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Part Type Name</label> <select class="form-control form-control-default" name="partType" [ngClass]="{'is-invalid': !partType.valid && (partType.dirty || partType.touched || isSubmit)}" #partType="ngModel" required partType [(ngModel)]="formInput.partType"> <option [ngValue]="null">Select Part Model</option> <option *ngFor="let parttypeSelection of parttypeSelections" [value]="parttypeSelection.id"> {{parttypeSelection.part_type}}</option> </select> <label *ngIf="!partType.valid && (partType.dirty || partType.touched || isSubmit)" id="validation-partType-error" class="error jquery-validation-error small form-text invalid-feedback">The Part Type selection should be required.</label> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Model Name</label> <input class="form-control input-md" name="modelName" type="text" placeholder="Enter Model Name" [ngClass]="{'is-invalid': !modelName.valid && (modelName.dirty || modelName.touched || isSubmit)}" #modelName="ngModel" required modelName [(ngModel)]="formInput.modelName"> <label *ngIf="!modelName.valid && (modelName.dirty || modelName.touched || isSubmit)" id="validation-modelName-error" class="error jquery-validation-error small form-text invalid-feedback">Please enter a Model Name</label> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Manufacturer</label> <input type="text" class="form-control" name="manufacture" #manufacture="ngModel" placeholder="Enter Manufacturer" [(ngModel)]="formInput.manufacture"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Model No</label> <input class="form-control input-md" name="modelNo" type="text" placeholder="Enter Model No" [ngClass]="{'is-invalid': !modelNo.valid && (modelNo.dirty || modelNo.touched || isSubmit)}" #modelNo="ngModel" required modelNo [(ngModel)]="formInput.modelNo"> <label *ngIf="!modelNo.valid && (modelNo.dirty || modelNo.touched || isSubmit)" id="validation-modelNo-error" class="error jquery-validation-error small form-text invalid-feedback">Please enter a Model No</label> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="lightfont">Remark</label> <input type="text" class="form-control" name="remarks" #manufacture="ngModel" placeholder="Enter Remark" [(ngModel)]="formInput.remarks"> </div> </div> <div class="col-md-6"> <label class="lightfont">Sales Contact</label> <div class="form-group row"> <input type="text" class="form-control col-sm-5" name="sales_contact_name" id="sales_contact_name" [ngClass]="{'is-invalid': !sales_contact_name.valid && (sales_contact_name.dirty || sales_contact_name.touched || isSubmit)}" #sales_contact_name="ngModel" required [(ngModel)]="formInput.sales_contact_name" placeholder="Enter Sales Contact Name"> <input type="text" class="form-control col-sm-5" name="sales_contact_no" id="sales_contact_no" [ngClass]="{'is-invalid': !sales_contact_no.valid && (sales_contact_no.dirty || sales_contact_no.touched || isSubmit)}" #sales_contact_no="ngModel" required [(ngModel)]="formInput.sales_contact_no" placeholder="Enter Sales Contact No"> <label *ngIf="!sales_contact_name.valid && (sales_contact_name.dirty || sales_contact_name.touched || isSubmit)" id="validation-sales_contact_name-error" class="error jquery-validation-error small form-text invalid-feedback">The Sales Contact field should be required.</label> <label *ngIf="!sales_contact_no.valid && (sales_contact_no.dirty || sales_contact_no.touched || isSubmit)" id="validation-sales_contact_no-error" class="error jquery-validation-error small form-text invalid-feedback">The Sales Contact No field should be required.</label> </div> </div> <div class="col-md-6"> <label class="lightfont">Support Contact</label> <div class="form-group row"> <input type="text" class="form-control col-sm-5" name="support_contact_name" id="support_contact_name" #support_contact_name="ngModel" [(ngModel)]="formInput.support_contact_name" placeholder="Enter Support Name"> <input type="text" class="form-control col-sm-5" name="support_contact_no" id="support_contact_no" #support_contact_no="ngModel" [(ngModel)]="formInput.support_contact_no" placeholder="Enter Support No"> </div> </div> </div> <div class="col-sm-12 centered-content"> <div class="btn-group mt-10"> <button type="button" [disabled]="!navigationForm.valid" (click)="saveStep1(navigationForm)" class="btn btn-primary btn-sm" awNextStep>Continue</button> </div> </div> </form> </aw-wizard-step> <aw-wizard-step stepTitle="Specifications & Parts" [navigationSymbol]="{ symbol: '&#xe88c;', fontFamily: 'feather' }"> <div class="col-sm-12"> <h6>Specification :</h6> <form action="javascript:" #fieldForm=ngForm> <div class="form-row"> <div class="form-group col-md-3"> <input type="text" class="form-control" name="name" placeholder="Enter Field Name" [ngClass]="{'is-invalid': !name.valid && (name.dirty || name.touched || isSubmit)}" #name="ngModel" required [(ngModel)]="formInputField.name"> <label *ngIf="!name.valid && (name.dirty || name.touched || isSubmit)" id="validation-name-error" class="error jquery-validation-error small form-text invalid-feedback">The Field Name should be required.</label> </div> <div class="form-group col-md-3"> <input type="text" class="form-control" name="field_value" placeholder="Enter Field Value" [ngClass]="{'is-invalid': !field_value.valid && (field_value.dirty || field_value.touched || isSubmit)}" #field_value="ngModel" required [(ngModel)]="formInputField.field_value"> <label *ngIf="!field_value.valid && (field_value.dirty || field_value.touched || isSubmit)" id="validation-field_value-error" class="error jquery-validation-error small form-text invalid-feedback">The Field Value should be required.</label> </div> <div class="form-group col-md-6"> <ng-container *ngIf="isEditMode; else elseTemplate"> <button type="button" class="btn btn-primary" [disabled]="!fieldForm.valid" (click)="updateField(fieldForm)"><i class="feather icon-edit"></i>Update</button> <button type="button" class="btn btn-secondary" (click)="cancelEdit(); fieldForm.reset()"><i class="feather icon-bell-off"></i>Cancel</button> </ng-container> <ng-template #elseTemplate> <button type="button" class="btn btn-primary" [disabled]="!fieldForm.valid" (click)="addField(fieldForm)"><i class="feather icon-file-plus"></i>Add</button> </ng-template> </div> </div> <mat-table [dataSource]="dataSource" matSort> <!-- ID Column --> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef> Id # </mat-header-cell> <mat-cell *matCellDef="let element" data-label="id"> {{element.id}} </mat-cell> </ng-container> <!-- Progress Column --> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef> Field Name </mat-header-cell> <mat-cell *matCellDef="let element" data-label="name"> {{element.name}} </mat-cell> </ng-container> <!-- Name Column --> <ng-container matColumnDef="field_value"> <mat-header-cell *matHeaderCellDef> Field Value </mat-header-cell> <mat-cell *matCellDef="let element" data-label="field_value"> {{element.field_value}} </mat-cell> </ng-container> <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef> Actions </mat-header-cell> <mat-cell *matCellDef="let element"> <a href="javascript:void(0)" (click)="editItem(element)">Edit</a> | <a href="javascript:void(0)" (click)="deleteItem(element.id)">Delete</a> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{'editable-row': partField.id === row.id}"> </mat-row> </mat-table> <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator> </form> </div> <div class="col-sm-12 centered-content"> <div class="btn-group mt-10"> <button type="button" class="btn btn-secondary btn-sm" awPreviousStep>Back</button> <button type="button" class="btn btn-primary btn-sm" awNextStep>Continue</button> </div> </div> </aw-wizard-step> <aw-wizard-step stepTitle="Links & Files" [navigationSymbol]="{ symbol: '&#xe840;', fontFamily: 'feather' }"> <h6>Link:</h6> <div class="col-sm-12 centered-content"> <div class="btn-group mt-10"> <button type="button" class="btn btn-secondary btn-sm" awPreviousStep>Back</button> </div> </div> </aw-wizard-step> </aw-wizard> </app-card>
(function () { var plot, hasNextCount, sequence, marks, marker; module("ulam.draw.SquareSpiralWalker", { setup: function () { plot = sinon.spy(); hasNextCount = 0; sequence = { hasNext: function () { return hasNextCount++ < 11; }, next: function () { return 1; } }; marks = []; marker = { mark: sinon.spy(function (plot, point, n) { marks.push($.extend({}, point)); }) }; } }); var SquareSpiralWalker = ulam.draw.SquareSpiralWalker; var checkWalk = function (mark, plot, expectedSteps, actualSteps) { strictEqual(mark.callCount, expectedSteps.length, "should call once for each step"); for (var i = 0; i < expectedSteps.length; i++) { strictEqual(mark.getCall(i).args[0], plot); ulam.util.test.pointEqual(expectedSteps[i], actualSteps[i]); } }; test("default starts right and moves counterclockwise", function () { new SquareSpiralWalker(plot, sequence, { markers: [marker] }).walk(); checkWalk(marker.mark, plot, marks, [ { x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }, { x: -1, y: 1 }, { x: -1, y: 0 }, { x: -1, y: -1 }, { x: 0, y: -1 }, { x: 1, y: -1 }, { x: 2, y: -1 }, { x: 2, y: 0 } ]); }); test("clockwise", function () { new SquareSpiralWalker(plot, sequence, { markers: [marker] }).walk(); checkWalk(marker.mark, plot, marks, [ { x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }, { x: -1, y: 1 }, { x: -1, y: 0 }, { x: -1, y: -1 }, { x: 0, y: -1 }, { x: 1, y: -1 }, { x: 2, y: -1 }, { x: 2, y: 0 } ]); }); test("starting down and moving clockwise", function () { new SquareSpiralWalker(plot, sequence, { startDirection: "down", clockwise: true }).walk(); checkWalk(marker.mark, plot, marks, [ { x: 0, y: -1 }, { x: 1, y: -1 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }, { x: -1, y: 1 }, { x: -1, y: 0 }, { x: -1, y: -1 }, { x: -1, y: -2 }, { x: 0, y: -2 } ]); }); test("starting left", function () { new SquareSpiralWalker(plot, sequence, { startDirection: "left" }).walk(); checkWalk(marker.mark, plot, marks, [ { x: -1, y: 0 }, { x: -1, y: 1 }, { x: 0, y: 1 }, { x: 1, y: 1 }, { x: 1, y: 0 }, { x: 1, y: -1 }, { x: 0, y: -1 }, { x: -1, y: -1 }, { x: -2, y: -1 }, { x: -2, y: 0 } ]); }); })();
package at.uibk.dps.rm.repository.resourceprovider; import at.uibk.dps.rm.testutil.integration.DatabaseTest; import io.vertx.junit5.VertxTestContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.util.NoSuchElementException; import static org.assertj.core.api.Assertions.assertThat; /** * Implements tests for the {@link ResourceProviderRepository} class. * * @author matthi-g */ public class ResourceProviderRepositoryTest extends DatabaseTest { private final ResourceProviderRepository repository = new ResourceProviderRepository(); @ParameterizedTest @CsvSource({ "1, true, cloud", "4, true, cloud", "5, true, edge", }) void findByRegionIdAndPlatformId(long providerId, boolean exists, String environment, VertxTestContext testContext) { smProvider.withTransactionMaybe(sessionManager -> repository .findByIdAndFetch(sessionManager, providerId)) .subscribe(result -> testContext.verify(() -> { if (exists) { assertThat(result.getProviderId()).isEqualTo(providerId); assertThat(result.getEnvironment().getEnvironment()).isEqualTo(environment); testContext.completeNow(); } else { testContext.failNow("method did not throw exception"); } }), throwable -> { assertThat(exists).isEqualTo(false); assertThat(throwable.getCause()).isInstanceOf(NoSuchElementException.class); testContext.completeNow(); }); } @Test void findAllAndFetch(VertxTestContext testContext) { smProvider.withTransactionSingle(repository::findAllAndFetch) .subscribe(result -> testContext.verify(() -> { assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).getProviderId()).isEqualTo(1L); assertThat(result.get(0).getEnvironment().getEnvironment()).isEqualTo("cloud"); assertThat(result.get(1).getProviderId()).isEqualTo(4L); assertThat(result.get(1).getEnvironment().getEnvironment()).isEqualTo("cloud"); assertThat(result.get(2).getProviderId()).isEqualTo(5L); assertThat(result.get(2).getEnvironment().getEnvironment()).isEqualTo("edge"); testContext.completeNow(); }), throwable -> testContext.failNow("method has thrown exception")); } }
from flask import Flask, render_template, request, jsonify from google.cloud import translate_v2 app = Flask(__name__) # 设置你的 Google Cloud API 密钥 # 注意:这里的密钥是演示用途,不要在实际项目中直接暴露密钥 google_translate_api_key = 'YOUR_GOOGLE_TRANSLATE_API_KEY' translate_client = translate_v2.Client(key=google_translate_api_key) @app.route('/') def index(): return render_template('index.html') @app.route('/translate', methods=['POST']) def translate_text(): data = request.get_json() text = data.get('text', '') source_language = data.get('source', 'en') target_language = data.get('target', 'el') try: result = translate_client.translate(text, source_language=source_language, target_language=target_language) translated_text = result['input'] except Exception as e: return jsonify({'error': str(e)}), 500 return jsonify({'translated_text': translated_text}) if __name__ == '__main__': app.run(debug=True)
<script lang="ts" setup> import { useHistoryStore } from '@/stores/history' import SearchBoxInput from './SearchBoxInput.vue' import SearchBoxMainPanel from './SearchBoxMainPanel.vue' import { useParamsStore } from '@/stores/params' import { useOptionsStore } from '@/stores/options' import { useSearchBoxStore } from '@/stores/searchBox' import { useTrackingStore } from '@/stores/tracking' import type { SearchBoxInputOptions, SearchBoxOptionLabels, SearchBoxOptions, SearchBoxPanelOptions } from '@/types/search-box/SearchBoxOptions' import { computed, onBeforeUnmount, onMounted, ref, type Ref } from 'vue' import type { FetchedData, HighlightedDocInfo, InputSuggestion, SelectedData } from '@/types/search-box/Common' import { storeToRefs } from 'pinia' import { pick } from '@/utils/picker.utils' import { DocumentSearchBoxPanel, SearchBoxPanelType } from '@/types/search-box/SearchBoxPanel' import type { Document, Suggestion } from '@getlupa/client-sdk/Types' import { debounce } from '@/utils/debounce.utils' import { bindSearchTriggers, unbindSearchTriggers } from '@/utils/event.utils' import { useRedirectionStore } from '@/stores/redirections' const defaultSuggestedValue = { item: { suggestion: '' }, queryKey: '', override: false } const props = defineProps<{ options: SearchBoxOptions isSearchContainer?: boolean }>() const historyStore = useHistoryStore() const paramsStore = useParamsStore() const searchBoxStore = useSearchBoxStore() const optionsStore = useOptionsStore() const trackingStore = useTrackingStore() const redirectionStore = useRedirectionStore() const inputValue = ref('') const suggestedValue: Ref<InputSuggestion> = ref(defaultSuggestedValue) const opened = ref(props.isSearchContainer) const searchBoxInput = ref(null) const { highlightedDocument } = storeToRefs(searchBoxStore) const searchValue = computed((): string => { return suggestedValue.value.override ? suggestedValue.value.item.suggestion : inputValue.value }) const inputOptions = computed( (): SearchBoxInputOptions => pick(props.options, ['minInputLength', 'labels', 'links', 'inputAttributes']) ) const panelOptions = computed( (): SearchBoxPanelOptions => pick(props.options, [ 'minInputLength', 'panels', 'history', 'labels', 'links', 'options', 'debounce', 'showTotalCount', 'hideMoreResultsButtonOnNoResults', 'showNoResultsPanel', 'expandOnSinglePanel' ]) ) const searchTriggers = computed((): string[] => { return props.options.searchTriggers ?? [] }) const goToResultsDebounced = debounce(paramsStore.goToResults, props.options.debounce ?? 300) onMounted(() => { window.addEventListener('keydown', handleKeyDown) window.addEventListener('click', handleMouseClick) paramsStore.setSearchResultsLink(props.options.links.searchResults) searchBoxStore.saveOptions({ newOptions: props.options }) optionsStore.setSearchBoxOptions({ options: props.options }) redirectionStore.initiate(props.options.redirections, props.options.options) bindSearchTriggers(searchTriggers.value, handleCurrentValueSearch) if (props.isSearchContainer && searchBoxInput.value) { ;(searchBoxInput.value as HTMLInputElement)?.focus() } }) onBeforeUnmount(() => { window.removeEventListener('keydown', handleKeyDown) window.removeEventListener('click', handleMouseClick) unbindSearchTriggers(searchTriggers.value, handleCurrentValueSearch) }) const handleMouseClick = (e: MouseEvent): void => { const el = document.getElementById('lupa-search-box') const elementClass = (e.target as HTMLElement)?.className ?? '' const hasLupaClass = typeof elementClass.includes == 'function' && elementClass.includes('lupa-search-box') const isOutsideElement = el && !el.contains(e.target as Node) && !hasLupaClass if (!isOutsideElement) { return } opened.value = false suggestedValue.value = defaultSuggestedValue } const handleKeyDown = (e: KeyboardEvent): void => { if (!opened.value) { return } switch (e.key) { case 'Tab': e.preventDefault() selectSuggestion({ ...suggestedValue.value, override: true }) break case 'Enter': e.preventDefault() handleSearch() resetValues() break default: break } } const handleInput = (value: string): void => { opened.value = true inputValue.value = value?.replace(/\s+$/, '') ?? '' suggestedValue.value = defaultSuggestedValue trackSearchQuery(value) if (props.isSearchContainer) { goToResultsDebounced({ searchText: value }) } } const handleItemsFetch = (data: FetchedData): void => { switch (data.type) { case SearchBoxPanelType.SUGGESTION: { const item = data.items[0] as Suggestion | undefined let suggestion = item || { suggestion: '' } suggestion = !suggestion.suggestion.includes(inputValue.value) || suggestion.suggestion.length === inputValue.value?.length ? { suggestion: '' } : suggestion suggestedValue.value = { item: suggestion, override: false, queryKey: '' } break } default: break } } const handleItemSelect = (data: SelectedData): void => { switch (data.type) { case SearchBoxPanelType.SUGGESTION: { const suggestion = data.item as InputSuggestion selectSuggestion(suggestion, suggestion.override) break } default: break } } const selectSuggestion = (inputSuggestion: InputSuggestion, shouldSearch = false): void => { if (inputSuggestion.item.suggestion) { suggestedValue.value = { ...inputSuggestion, override: true } if (inputSuggestion.override) { trackSuggestionClick() } inputValue.value = inputSuggestion.override ? inputSuggestion.item.suggestion : inputValue.value } if (shouldSearch) { handleSearch() } } const handleNavigateDocument = ({ link }: { doc?: Document; link?: string }): void => { if (!link) { return } window.location.assign(link) } const handleCurrentValueSearch = (): void => { if (searchValue.value?.length < props.options.minInputLength) { return } opened.value = false paramsStore.goToResults({ searchText: searchValue.value }) resetValues() } const handleSearch = ({ query } = { query: '' }): void => { const searchText = query || searchValue.value if (searchText.length < props.options.minInputLength) { return } if (highlightedDocument.value?.doc) { trackDocumentClick(highlightedDocument.value) handleNavigateDocument(highlightedDocument.value) return } trackSuggestionClick() historyStore.add({ item: searchText }) opened.value = false paramsStore.goToResults({ searchText, facet: suggestedValue.value.facet }) } const trackDocumentClick = (doc: HighlightedDocInfo): void => { if (!doc.queryKey || !doc.doc) { return } trackingStore.trackEvent({ queryKey: doc.queryKey, data: { itemId: doc.id as string, searchQuery: inputValue.value, type: 'itemClick', analytics: { type: 'autocomplete_product_click', label: doc.title || (doc.id as string), items: [doc] } } }) } const trackSearchQuery = (query?: string): void => { if (!query) { return } trackingStore.trackSearch({ queryKey: suggestedValue.value.queryKey, query: { searchText: query } }) } const trackSuggestionClick = (suggestion?: string): void => { if ( suggestion || inputValue.value?.length < props.options.minInputLength || inputValue.value === searchValue.value ) { return } trackingStore.trackEvent({ queryKey: suggestedValue.value.queryKey, data: { itemId: suggestion || searchValue.value, searchQuery: inputValue.value, type: 'suggestionClick', analytics: { type: 'autocomplete_suggestion_click', label: suggestion || searchValue.value } } }) } const resetValues = (): void => { inputValue.value = '' suggestedValue.value = defaultSuggestedValue } const handleProductClick = (): void => { opened.value = false } const slotProps = ( props: any ): { key: string item: Document labels?: SearchBoxOptionLabels highlighted: boolean panelOptions: DocumentSearchBoxPanel itemClicked: (props: { item: Document eventType?: 'itemClick' | 'addToCart' event?: Event }) => void } => { return { ...props } } </script> <template> <div id="lupa-search-box"> <div class="lupa-search-box-wrapper"> <SearchBoxInput :options="inputOptions" :suggestedValue="suggestedValue" :can-close="isSearchContainer ?? false" :emit-input-on-focus="!isSearchContainer" ref="searchBoxInput" @input="handleInput" @focus="opened = true" @close="$emit('close')" /> <SearchBoxMainPanel v-if="opened || isSearchContainer" :options="panelOptions" :inputValue="inputValue" :isSearchContainer="isSearchContainer" @fetched="handleItemsFetch" @itemSelect="handleItemSelect" @go-to-results="handleSearch" @product-click="handleProductClick" > <template v-if="$slots.productCard" #productCard="props"> <slot name="productCard" v-bind="slotProps(props)" /> </template> </SearchBoxMainPanel> </div> </div> </template>
import { ReactNode } from "react"; import { TouchableOpacity, Text } from "react-native"; import colors from "tailwindcss/colors"; interface Props { children: ReactNode; onPress?: () => {}; } export function ButtonPrimary({ onPress, children }: Props) { return ( <TouchableOpacity className="w-full h-14 flex-row items-center justify-center bg-green-600 rounded-md mt-2" activeOpacity={0.7} onPress={onPress} > {children} </TouchableOpacity> ); }
import { Component, OnInit,ViewChild } from '@angular/core'; import { data } from './datasource'; import { FilterSettingsModel, GridComponent } from '@syncfusion/ej2-angular-grids'; @Component({ selector: 'app-root', template: `<div id='message'>{{message}}</div><ejs-grid #grid [dataSource]='data' [allowFiltering]='true' height='273px' (actionBegin)="actionBegin($event)" (actionComplete)="actionComplete($event)"> <e-columns> <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=100></e-column> <e-column field='CustomerID' headerText='Customer ID' width=120></e-column> <e-column field='ShipCity' headerText='Ship City' width=100></e-column> <e-column field='ShipName' headerText='Ship Name' width=100></e-column> </e-columns> </ejs-grid>` }) export class AppComponent implements OnInit { public data?: object[]; public filterOptions?: FilterSettingsModel; public message: string | undefined; @ViewChild('grid') public gridObj?: GridComponent; ngOnInit(): void { this.data = data; } actionBegin(args: any) { if (args.requestType == 'filtering' && args.currentFilteringColumn == 'ShipCity'){ args.cancel = true; this.message = 'The '+ args.type + ' event has been triggered and the ' + args.requestType + ' action is cancelled for ' + args.currentFilteringColumn; } } actionComplete(args: any) { if (args.requestType == 'filtering' && args.currentFilteringColumn) { this.message ='The ' + args.type + ' event has been triggered and the ' + args.requestType + ' action for the ' + args.currentFilteringColumn + ' column has been successfully executed'; }else{ this.message=''; } } }
#define UsingNumerics using System; using System.Collections.Generic; #if UsingNumerics using System.Numerics; #endif namespace libmath { #if !UsingNumerics /// <summary> /// Defining Structure for Complex Data type N=R+Ii /// </summary> struct Complex { public double Real, Imaginary; public Complex(double x, double y) { Real = x; Imaginary = y; } public float Magnitude() { return ((float)Math.Sqrt(Real * Real + Imaginary * Imaginary)); } public float Phase() { return ((float)Math.Atan(Imaginary / Real)); } } #endif static class FFT { public static void ToFunction(int[,] data) { var space = ConvertSpace(ConvertHash(data), default); } /// <summary> /// 将散列数据转变为空间数据 /// </summary> private static SpaceComplex[] ConvertSpace(Complex[,] fourier, Complex invaild) { var width = fourier.GetLength(0); var height = fourier.GetLength(1); var scs = new List<SpaceComplex>(); for (var i = 0; i <= width - 1; i++) for (var j = 0; j <= height - 1; j++) { var f = fourier[i, j]; if (!f.Equals(invaild)) { scs.Add(new SpaceComplex(f, i, j)); } } return scs.ToArray(); } /// <summary> /// 转换散列数据到Complex /// </summary> private static Complex[,] ConvertHash(int[,] data) { var width = data.GetLength(0); var height = data.GetLength(1); var fourier = new Complex[width, height]; //Copy Image Data to the Complex Array for (var i = 0; i <= width - 1; i++) for (var j = 0; j <= height - 1; j++) fourier[i, j] = new Complex(data[i, j], 0); return FFT2D(fourier, width, height, 1); } /*------------------------------------------------------------------------- Perform a 2D FFT inplace given a complex 2D array The direction dir, 1 for forward, -1 for reverse The size of the array (nx,ny) Return false if there are memory problems or the dimensions are not powers of 2 */ private static Complex[,] FFT2D(Complex[,] c, int nx, int ny, int dir) { int i, j; int m;//Power of 2 for current number of points double[] real; double[] imag; Complex[,] output;//=new COMPLEX [nx,ny]; output = c; // Copying Array // Transform the Rows real = new double[nx]; imag = new double[nx]; for (j = 0; j < ny; j++) { for (i = 0; i < nx; i++) { real[i] = c[i, j].Real; imag[i] = c[i, j].Imaginary; } // Calling 1D FFT Function for Rows m = (int)Math.Log(nx, 2);//Finding power of 2 for current number of points e.g. for nx=512 m=9 FFT1D(dir, m, ref real, ref imag); for (i = 0; i < nx; i++) { output[i, j] = new Complex(real[i], imag[i]); } } // Transform the columns real = new double[ny]; imag = new double[ny]; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { //real[j] = c[i,j].real; //imag[j] = c[i,j].imag; real[j] = output[i, j].Real; imag[j] = output[i, j].Imaginary; } // Calling 1D FFT Function for Columns m = (int)Math.Log(ny, 2);//Finding power of 2 for current number of points e.g. for nx=512 m=9 FFT1D(dir, m, ref real, ref imag); for (j = 0; j < ny; j++) { output[i, j] = new Complex(real[i], imag[i]); } } // return(true); return output; } /*------------------------------------------------------------------------- This computes an in-place complex-to-complex FFT x and y are the real and imaginary arrays of 2^m points. dir = 1 gives forward transform dir = -1 gives reverse transform Formula: forward N-1 --- 1 \ - j k 2 pi n / N X(K) = --- > x(n) e = Forward transform N / n=0..N-1 --- n=0 Formula: reverse N-1 --- \ j k 2 pi n / N X(n) = > x(k) e = Inverse transform / k=0..N-1 --- k=0 */ private static void FFT1D(int dir, int m, ref double[] x, ref double[] y) { long nn, i, i1, j, k, i2, l, l1, l2; double c1, c2, tx, ty, t1, t2, u1, u2, z; /* Calculate the number of points */ nn = 1; for (i = 0; i < m; i++) nn *= 2; /* Do the bit reversal */ i2 = nn >> 1; j = 0; for (i = 0; i < nn - 1; i++) { if (i < j) { tx = x[i]; ty = y[i]; x[i] = x[j]; y[i] = y[j]; x[j] = tx; y[j] = ty; } k = i2; while (k <= j) { j -= k; k >>= 1; } j += k; } /* Compute the FFT */ c1 = -1.0; c2 = 0.0; l2 = 1; for (l = 0; l < m; l++) { l1 = l2; l2 <<= 1; u1 = 1.0; u2 = 0.0; for (j = 0; j < l1; j++) { for (i = j; i < nn; i += l2) { i1 = i + l1; t1 = u1 * x[i1] - u2 * y[i1]; t2 = u1 * y[i1] + u2 * x[i1]; x[i1] = x[i] - t1; y[i1] = y[i] - t2; x[i] += t1; y[i] += t2; } z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = Math.Sqrt((1.0 - c1) / 2.0); if (dir == 1) c2 = -c2; c1 = Math.Sqrt((1.0 + c1) / 2.0); } /* Scaling for forward transform */ if (dir == 1) { for (i = 0; i < nn; i++) { x[i] /= nn; y[i] /= nn; } } // return(true) ; return; } struct SpaceComplex { public Complex Complex { get; } public int X { get; } public int Y { get; } public SpaceComplex(Complex complex, int x, int y) { Complex = complex; X = x; Y = y; } } } }
package ancestris.reports; import genj.gedcom.*; import genj.gedcom.time.PointInTime; import genj.report.Report; import java.io.File; import java.util.*; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; /** * * Ancestris - http://www.ancestris.org * * Report displays status of information found vs information to be searched for * each person in the tree. * * List starts with de-cujus person and goes up the tree * * This report relies on Sosa tag filled in with sosa numbers (generated by the * tool box for instance) (otherwise, we would need to include the code of the toolbox in this report as well). * * August 2012 * * @author Frederic Lapeyre <frederic@lapeyre-frederic.com> * */ @SuppressWarnings("unchecked") @ServiceProvider(service = Report.class) public class ReportGenealogyStatus extends Report { public int maxNbOfAncestors = 512; // limit to avoid displaying too many empty ancestors public boolean includeSiblings = false; // do we want to show siblings also after each person public String directoryOption = ""; // directory where to look for media private static String SOSATAG = "_SOSA"; // sosa tag private static String OUI = "1"; // information found private static String NON = "."; // information not found private static String ERR = "#"; // information found but erroneous private static String SEQ = "o"; // for family event MARR, indicates that kids appearance is not chronological private static String FIL = "S"; // source media found but not transcripted in a text tag private static String SPA = " "; // space private static String TAB = "\t"; // tab private String[] placeFormat = null; private int sizePlaces = (placeFormat != null) ? placeFormat.length : 0; private Map<String, Indi> sosaList = new TreeMap(); // stores and retrieves individuals by sosa key private Map<Source, String> sourceMap = new TreeMap(); // stores and retrieves sosa used for each source private Map<String, String> entMap = new TreeMap(); // stores and retrieves unreferenced sources private int cntAnomaly = 0, // counter of errors cntOutOfSeq = 0, // counter of out of sequence cntKnwnSrc = 0; // counter of missing transcripted sources /** * Our main logic. */ public void start(Gedcom gedcom) { // Get all individuals in a sosa list Collection entities = gedcom.getEntities(Gedcom.INDI); Property[] props; String sosaStr; for (Iterator it = entities.iterator(); it.hasNext();) { Indi indi = (Indi) it.next(); props = indi.getProperties(SOSATAG); if (props == null) { continue; } for (int i = 0; i < props.length; i++) { Property prop = props[i]; sosaStr = prop.getValue(); // if option specficies not to include siblings, skip them, // except for decujus because siblings of decujus are also a decujus // (siblings are recognized by sosa number followed by "+" or "-" and followed by d'Aboville number) if (!includeSiblings && (sosaStr.indexOf("+") != -1 || sosaStr.indexOf("-") != -1) && (sosaStr.indexOf("00000001") == -1)) { continue; } sosaList.put(sosaStr, indi); } } // Quit if no sosa found if (sosaList.isEmpty()) { println(NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_NoSosaFound")); println("========"); return; } // A few initialisations placeFormat = validatePlaceFormat(gedcom.getPlaceFormat()); headerLine(); // Display sosa list with the status of the data found for each entity int sosaCnt = 1; // counts ancestors int sosaNb; // represents the sosa number being considered int i = 1; // counts the line for (Iterator it = sosaList.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); Indi indi = sosaList.get(key); sosaNb = getSosaNb(key); // start counting ancestors from above decujus if (sosaNb > 1) { sosaCnt++; } // fill in emty lines for all ancestors that are still to be discovered while (sosaNb > sosaCnt && sosaCnt < maxNbOfAncestors) { println(emptyLine()); sosaCnt++; } // print status of indi println(getLine(indi, i++, key)); // make it easier to read by putting a line every ten lines if ((i / 10) * 10 == i) { midLine(); } } sosaList.clear(); sourceMap.clear(); println(" "); println(" "); println("========"); println(" "); // List sources not used or used more than once println(NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_sources_header")); println(" "); List ents = gedcom.getEntities(); for (Iterator it = ents.iterator(); it.hasNext();) { Entity ent = (Entity) it.next(); List ps = ent.getProperties(PropertyXRef.class); for (Iterator it2 = ps.iterator(); it2.hasNext();) { PropertyXRef xref = (PropertyXRef) it2.next(); Entity entity = xref.getTargetEntity(); if (entity != null) { String str = entMap.get(entity.getId()); if (str == null) { entMap.put(entity.getId(), ent.getId()); } else { entMap.put(entity.getId(), str + "," + ent.getId()); } } } } for (Iterator it = ents.iterator(); it.hasNext();) { Entity ent = (Entity) it.next(); String str = entMap.get(ent.getId()); if (str == null) { println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_entity_not_used") + ent.getId()); } if (str != null && (numberOf(str, ",") > numberOf(str, "R")) && ent instanceof Source) { println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_multiple_source") + ent.getId() + " - " + str); } } entMap.clear(); println(" "); println(" "); println("========"); println(" "); // Check unused media files: // - Get all obje of the gedcom file // - Scan specific directories an if file not in list, decare it // List<String> gedcomFiles = new ArrayList(); entities = gedcom.getEntities(); for (Iterator it = entities.iterator(); it.hasNext();) { Entity ent = (Entity) it.next(); for (Iterator fileIt = ent.getProperties(PropertyFile.class).iterator(); fileIt.hasNext();) { PropertyFile file = (PropertyFile) fileIt.next(); //println(file.getFile().getName()); gedcomFiles.add(file.getFile().getName()); } } File directory = new File(directoryOption); boolean found = false; if (directory != null) { println(NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_unused_media", directory.toString())); println(" "); found = checkDirectory(directory, gedcomFiles); } if (!found) { println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_directory")); } println(" "); println(" "); println("========"); println(" "); // Print error counters // println(NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_counters")); println(" "); println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_anomalies") + " (" + ERR + ") : " + cntAnomaly); println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_sequence") + " (" + SEQ + ") : " + cntOutOfSeq); println(" " + NbBundle.getMessage(ReportGenealogyStatus.class, "TXT_source") + " (" + FIL + ") : " + cntKnwnSrc); println(" "); println(" "); println("========"); } // end_of_start /** * Print header line. */ private void headerLine() { println("Nb " + TAB + "Sosa " + TAB + "Gen" + TAB + "Id " + TAB + "Med" + TAB + "Birt" + SPA + "Deat" + SPA + "Marr" + SPA + "Fam " + TAB + "Marl" + SPA + "Marc" + SPA + "Div " + TAB + "Chr " + SPA + "Buri" + SPA + "Occu" + SPA + "Resi" + SPA + "Grad" + SPA + "Even" + SPA + "Natu" + SPA + "Adop" + SPA + "Immi" + SPA + "Nom "); midLine(); } /** * Print mid line. */ private void midLine() { println("---" + TAB + "------------------" + TAB + "---" + TAB + "-----" + TAB + "---" + TAB + "----" + SPA + "----" + SPA + "----" + SPA + "-----" + TAB + "----" + SPA + "----" + SPA + "----" + TAB + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "----" + SPA + "------------------------"); } /** * Print empty line. */ private String emptyLine() { return ". " + TAB + ". " + TAB + ". " + TAB + ". " + TAB + ". " + TAB + ". " + SPA + ". " + SPA + ". " + SPA + " " + TAB + " " + SPA + " " + SPA + " " + TAB + " " + SPA + " " + SPA + " " + SPA + " " + SPA + " " + SPA + " " + SPA + " " + SPA + " " + SPA + " " + SPA + ". "; } /** * Get line of text from indi. */ private String getLine(Indi indi, int index, String sosa) { Property[] props; String line = ""; // Number of ancestor found line += index; line += TAB; // Sosa nb line += sosa + " ".substring(sosa.length()); line += TAB; // Génération int sosaNb = getSosaNb(sosa); line += sosaNb == 0 ? "--" : (int) (Math.log(2 * sosaNb) / Math.log(2)); line += TAB; // Id line += indi.getId(); line += TAB; // Media props = indi.getProperties(new TagPath("INDI:OBJE:FILE")); line += props == null || props.length == 0 ? NON : props.length; line += TAB; // Birth line += getEvent(sosa, indi, "INDI:BIRT", true); line += SPA; // Death line += getEvent(sosa, indi, "INDI:DEAT", sosaNb > 15); // mandatory from great-great-grand-father and above line += SPA; // Marriage line += getFamilies(sosa, indi, sosaNb > 1 && sosa.indexOf("-") == -1); // family mandatory from parents and above line += TAB; // Christening line += getEvent(sosa, indi, "INDI:CHR", false); line += SPA; // Buri line += getEvent(sosa, indi, "INDI:BURI", false); line += SPA; // Occupation line += getMultipleEvent(sosa, indi, "OCCU"); line += SPA; // Residence line += getMultipleEvent(sosa, indi, "RESI"); line += SPA; // Graduation line += getMultipleEvent(sosa, indi, "GRAD"); line += SPA; // Even line += getEvent(sosa, indi, "INDI:EVEN", false); line += SPA; // Natu line += getEvent(sosa, indi, "INDI:NATU", false); line += SPA; // Adoption line += getEvent(sosa, indi, "INDI:ADOP", false); line += SPA; // Immigration line += getEvent(sosa, indi, "INDI:IMMI", false); line += SPA; // Name line += indi.getLastName() + ", " + indi.getFirstName().substring(0, Math.min(10, indi.getFirstName().length())); return line; } /** * Get sosa nb from sosa string. (extracts first digital number found when * going from start of string) */ private int getSosaNb(String str) { int sosaNb; int start = 0, end = str.length() - 1; while (start <= end && !Character.isDigit(str.charAt(start))) { start++; } end = start; while ((end <= str.length() - 1) && Character.isDigit(str.charAt(end))) { end++; } if (end == start) { return 0; } else { sosaNb = (int) Integer.parseInt(str.substring(start, end)); } return sosaNb; } /** * Get first event found given by tag. Code is made of 4 characters. - date * of event - place of event - source of event on 2 digits */ private String getEvent(String sosa, Entity ent, String tag, boolean mandatory) { String line = ""; Property prop = ent.getPropertyByPath(tag); if (prop == null) { return mandatory ? err() + err() + err() + err() : " "; } // date line += isValidAndComplete(ent.getPropertyByPath(tag + ":DATE")); // place line += isValidAndComplete(ent.getPropertyByPath(tag + ":PLAC")); // source and text line += getSource(sosa, ent, tag + ":SOUR"); return line; } /** * Get all events found given by tag. Code is made of 4 digits representing * the number of occurrences found (9 max). * - number of occurrences found. * - necessary element found. * - source of event on 2 digits. * * For OCCU: label is necessary : nb / nb of label found / worst source * For GRAD: AGNC is necessary : nb / nb of agency found / worst source * For RESI: ADDR is necessary : nb / nb of addr found / worst source * */ private String getMultipleEvent(String sosa, Entity ent, String tag) { String line = ""; boolean debug = false ; //ent.getId().equalsIgnoreCase("I2507"); boolean isOccu = tag.equalsIgnoreCase("OCCU"); boolean isGrad = tag.equalsIgnoreCase("GRAD"); boolean isResi = tag.equalsIgnoreCase("RESI"); Property[] prop = ent.getProperties(tag); if (prop == null || prop.length == 0) { return " "; } int intNbFound = 0; String src = " "; String tmpSrc; for (int i = 0; i < prop.length; i++) { Property property = prop[i]; // look for necessary element depending on tag if (isOccu) { String str = property.toString(); intNbFound += (str != null && str.length() > 0) ? 1 : 0; } if (isGrad) { Property agency = property.getProperty("AGNC"); intNbFound += ((agency == null) || agency.toString().length() < 1) ? 0 : 1; } if (isResi) { Property address = property.getProperty("ADDR"); if (address != null) { Property city = address.getProperty("CITY"); intNbFound += ((city == null) || city.toString().length() < 1) ? 0 : 1; } } // Source and text tmpSrc = getSource(sosa, ent, tag + ":SOUR"); // Only overwrite if worse source. Ranking is : "OUI < NON < FIL < ERR" if (src.compareTo(ERR) != -1) { // if error already detected, continue continue; } if (tmpSrc.compareTo(ERR) != -1) { // if error just detected, assign to src and continue src = tmpSrc; continue; } if (src.compareTo(FIL) == -1) { // else, if a fill yet, continue; src = tmpSrc; } if (tmpSrc.compareTo(FIL) != -1) { // if fill just detected, assign to src and continue src = tmpSrc; continue; } if (src.compareTo(NON) == -1) { // else, if a not found yet, continue; src = tmpSrc; } if (tmpSrc.compareTo(NON) != -1) { // if not found now just detected, assign to src and continue src = tmpSrc; continue; } } // Now, write codes line += prop.length == 0 ? NON : String.valueOf(prop.length); line += intNbFound == 0 ? NON : String.valueOf(intNbFound); line += src; return line; } /** * Get source code of an event. Code is made of 2 digits. - source : source * entity exists and has not already been attached to another event) - * source proof : a text or media has been found) Rules: - If a source has a * media then the text should be filled in - If two sources are attached to * an event, only the first one is detected - A source can only be attached * once to n individual */ private String getSource(String sosa, Entity ent1, String tag) { String src = ""; Property[] props = ent1.getProperties(new TagPath(tag)); if (props == null || props.length == 0) { return NON + NON; } if (props.length != 1) { return err() + err(); } Property prop = props[0]; // get only the first source if (prop == null || !(prop instanceof PropertyXRef)) { src += NON + NON; } else { Entity ent2 = ((PropertyXRef) prop).getTargetEntity(); if (ent2 instanceof Source) { Source source = (Source) ent2; String sosa2 = sourceMap.get(source); if (sosa2 == null || sosa2.compareTo(sosa) != 0) { sourceMap.put(source, sosa); src += OUI; } else { src += err(); // source already used for that individual } Property ptext = ent2.getProperty("TEXT"); Property pobje = ent2.getPropertyByPath("SOUR:OBJE:FILE"); src += ptext == null || ptext.toString().length() < 1 ? (pobje == null ? NON : err()) : (pobje == null ? fil() : OUI); } else { src += err() + NON; } } return src; } /** * Get family of an individual. Returned string is made of several elements: * - Event code of MARR event - family id - Other "MARR" type events (MARL, * MARC, DIV) */ private String getFamilies(String sosa, Indi indi, boolean mandatory) { String line = ""; Fam[] families = indi.getFamiliesWhereSpouse(); if (families == null || families.length == 0) { return (mandatory ? err() + err() + err() + err() : " ") + SPA + " " + TAB + " " + SPA + " " + SPA + " "; } Fam famFound = null; for (int i = 0; i < families.length; i++) { Fam family = families[i]; // make sure that spouse is not the same as indi Indi spouse = family.getHusband(); if (spouse == indi) { spouse = family.getWife(); } // continue if spouse not valid (null, not an ancestor or a siblings) if (spouse != null && spouse.getProperty(SOSATAG) == null && (sosa.indexOf("-") == -1)) { continue; } famFound = family; break; } if (famFound != null) { line += getEvent(sosa, famFound, "FAM:MARR", mandatory); line += checkKidsOrder(famFound); line += TAB; line += famFound.getId(); line += TAB; line += getEvent(sosa, famFound, "FAM:MARL", false); line += SPA; line += getEvent(sosa, famFound, "FAM:MARC", false); line += SPA; line += getEvent(sosa, famFound, "FAM:DIV", false); return line; } return NON + NON + NON + NON + TAB + NON + NON + NON + NON + TAB + " " + SPA + " " + SPA + " "; } /** * Checks if place is valid and complete. */ private String isValidAndComplete(Property prop) { if (prop == null || (!(prop instanceof PropertyDate) && !(prop instanceof PropertyPlace))) { return NON; } if (prop instanceof PropertyDate) { PropertyDate pDate = (PropertyDate) prop; if (pDate == null || !pDate.isValid() || pDate.isRange()) { return NON; } PropertyDate.Format pf = pDate.getFormat(); if (pf != PropertyDate.DATE) { return NON; } PointInTime pit = pDate.getStart(); if (!pit.isValid() || !pit.isComplete()) { return NON; } return OUI; } if (prop instanceof PropertyPlace) { String[] place = prop.toString().split("\\,", -1); if ((sizePlaces > 0) && (place.length != sizePlaces)) { return NON; } if (isEmpty(place)) { return NON; } return OUI; } return NON; } private boolean isEmpty(String[] tags) { if (tags == null) { return true; } for (int i = 0; i < tags.length; i++) { if (tags[i].trim().length() > 0) { return false; } } return true; } private String[] validatePlaceFormat(String placeFormat) { String[] tags = null; if (placeFormat.length() != 0) { tags = placeFormat.split("\\,", -1); for (int i = 0; i < tags.length; i++) { tags[i] = tags[i].trim(); } } return tags; } /** * Check kids order in a family. */ private String checkKidsOrder(Fam family) { String line = ""; Indi[] kids = family.getChildren(false); if (kids == null || kids.length < 2) { return ""; } PropertyDate pDate; PropertyDate pDatePrev = null; for (int i = 0; i < kids.length; i++) { pDate = kids[i].getBirthDate(); if (pDate == null || !pDate.isValid()) { continue; } if ((pDatePrev != null) && (pDate.compareTo(pDatePrev) < 0)) { return seq(); } pDatePrev = pDate; } return ""; } /** * Counts nb of same str in a string. */ private int numberOf(String str, String seq) { if (str == null || seq == null) { return 0; } int value = 0; int pos = 1; while (pos < str.length()) { pos = str.indexOf(seq, pos - 1) + 2; if (pos == 1) { break; } value++; } return value; } /** * Increments. */ private String err() { cntAnomaly++; return ERR; } private String seq() { cntOutOfSeq++; return SEQ; } private String fil() { cntKnwnSrc++; return FIL; } /** * Check if directory is found in gedcom files. */ private boolean checkDirectory(File directory, List<String> gedcomFiles) { boolean found = false; File[] files = directory.listFiles(); if (files == null) { return false; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { found = found || checkDirectory(files[i], gedcomFiles); } else { String filename = files[i].getName(); if (!gedcomFiles.contains(filename)) { println(files[i].toString()); found = true; } } } return found; } }
<template> 与生命周期钩子的一个关键区别是,watch() 和 watchEffect() 在 DOM 挂载或更新之前运行副作用,所以当侦听器运行时,模板引用还未被更新。 <div ref="root">This is a root element</div> </template> <script> import { ref, watchEffect } from 'vue' export default { setup() { const root = ref(null) watchEffect(() => { console.log(root.value) // => <div>This is a root element</div> }, { flush: 'post' }) return { root } } } </script>
--- uid: web-forms/overview/older-versions-security/admin/building-an-interface-to-select-one-user-account-from-many-vb title: 建立介面,從許多 (VB) 中選取一個使用者帳戶 |Microsoft Docs author: rick-anderson description: 在本教學課程中,我們將使用分頁的可篩選方格來建立使用者介面。 尤其是,我們的使用者介面是由一系列的 LinkButtons 所組成 .。。 ms.author: riande ms.date: 04/01/2008 ms.assetid: da53380c-a16b-41c7-a20d-24343c735c52 msc.legacyurl: /web-forms/overview/older-versions-security/admin/building-an-interface-to-select-one-user-account-from-many-vb msc.type: authoredcontent ms.openlocfilehash: 625e27442c790e7a7228b8f78b8a40dbee8e3b03 ms.sourcegitcommit: 4e6d586faadbe4d9ef27122f86335ec9385134af ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 08/28/2020 ms.locfileid: "89044580" --- # <a name="building-an-interface-to-select-one-user-account-from-many-vb"></a>建置介面從許多個使用者帳戶中選取一個 (VB) [Scott Mitchell](https://twitter.com/ScottOnWriting) [下載程式代碼](https://download.microsoft.com/download/6/0/e/60e1bd94-e5f9-4d5a-a079-f23c98f4f67d/VB.12.zip) 或 [下載 PDF](https://download.microsoft.com/download/6/0/e/60e1bd94-e5f9-4d5a-a079-f23c98f4f67d/aspnet_tutorial12_SelectUser_vb.pdf) > 在本教學課程中,我們將使用分頁的可篩選方格來建立使用者介面。 尤其是,我們的使用者介面會包含一系列的 LinkButtons,以便根據使用者名稱的開始字母篩選結果,以及顯示符合使用者的 GridView 控制項。 我們會從列出 GridView 中的所有使用者帳戶開始。 然後,在步驟3中,我們將新增篩選 LinkButtons。 步驟4會查看篩選的結果分頁。 在步驟2到4中所建立的介面,將用於後續的教學課程中,以針對特定的使用者帳戶執行系統管理工作。 ## <a name="introduction"></a>簡介 在 [將 <a id="_msoanchor_1"></a> [*角色指派給使用者*](../roles/assigning-roles-to-users-vb.md)] 教學課程中,我們建立了一個基本介面,讓系統管理員選取使用者並管理她的角色。 具體而言,介面會顯示系統管理員一個下拉式清單,其中包含所有使用者。 如果有數十個以上的使用者帳戶,這種介面相當適合,但對於具有數百或上千個帳戶的網站來說很難處理。 針對具有大型使用者群的網站,分頁的可篩選方格是更適合的使用者介面。 在本教學課程中,我們將建立這類使用者介面。 尤其是,我們的使用者介面會包含一系列的 LinkButtons,以便根據使用者名稱的開始字母篩選結果,以及顯示符合使用者的 GridView 控制項。 我們會從列出 GridView 中的所有使用者帳戶開始。 然後,在步驟3中,我們將新增篩選 LinkButtons。 步驟4會查看篩選的結果分頁。 在步驟2到4中所建立的介面,將用於後續的教學課程中,以針對特定的使用者帳戶執行系統管理工作。 現在就開始吧! ## <a name="step-1-adding-new-aspnet-pages"></a>步驟1:加入新的 ASP.NET 網頁 在本教學課程和接下來的兩個教學課程中,我們將探討各種系統管理相關的功能和功能。 我們將需要一系列的 ASP.NET 網頁,以實行在這些教學課程中所探討的主題。 讓我們建立這些頁面,並更新網站地圖。 首先,在名為的專案中建立新資料夾 `Administration` 。 接下來,在資料夾中加入兩個新的 ASP.NET 網頁,並將每個頁面連結至 `Site.master` 主版頁面。 為頁面命名: - `ManageUsers.aspx` - `UserInformation.aspx` 此外,請將兩個頁面新增至網站的根目錄: `ChangePassword.aspx` 和 `RecoverPassword.aspx` 。 這四個頁面現在應該有兩個內容控制項,每個主版頁面的 ContentPlaceHolders 都有一個: `MainContent` 和 `LoginContent` 。 [!code-aspx[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample1.aspx)] 我們想要針對這些頁面顯示主版頁面的 ContentPlaceHolder 預設標記 `LoginContent` 。 因此,請移除內容控制項的宣告式標記 `Content2` 。 這麼做之後,頁面的標記應該只包含一個內容控制項。 資料夾中的 ASP.NET 網頁 `Administration` 僅供系統管理使用者之用。 我們已在 [建立和管理角色] 教學課程中,將系統管理員角色新增至系統,將這 <a id="_msoanchor_2"></a> [*Creating and Managing Roles*](../roles/creating-and-managing-roles-vb.md)兩個頁面的存取許可權制為此角色。 若要完成此動作,請將檔案新增 `Web.config` 至 `Administration` 資料夾,並設定其元素以授與系統 `<authorization>` 管理員角色中的使用者,並拒絕所有其他使用者。 [!code-xml[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample2.xml)] 此時專案的方案總管看起來應該會類似 [圖 1] 所示的螢幕擷取畫面。 [![網站已新增四個新頁面和 Web.config 檔案](building-an-interface-to-select-one-user-account-from-many-vb/_static/image2.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image1.png) **圖 1**:有四個新頁面和檔案已 `Web.config` 新增至網站 ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image3.png)) 最後,更新網站地圖 (`Web.sitemap`) 將專案加入至 `ManageUsers.aspx` 頁面。 在我們為角色教學課程新增的之後,新增下列 XML `<siteMapNode>` 。 [!code-xml[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample3.xml)] 更新網站地圖之後,請透過瀏覽器造訪網站。 如 [圖 2] 所示,左邊的導覽現在包含管理教學課程的專案。 [![網站地圖包含標題為 [使用者管理] 的節點。](building-an-interface-to-select-one-user-account-from-many-vb/_static/image5.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image4.png) **圖 2**:網站地圖包含標題為 [使用者管理] 的節點 ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image6.png)) ## <a name="step-2-listing-all-user-accounts-in-a-gridview"></a>步驟2:列出 GridView 中的所有使用者帳戶 本教學課程的最終目標是要建立一個分頁的可篩選方格,讓系統管理員可以選取要管理的使用者帳戶。 讓我們先列出 GridView 中的 *所有* 使用者。 完成之後,我們將新增篩選和分頁介面和功能。 開啟 `ManageUsers.aspx` 資料夾中的頁面, `Administration` 並新增 GridView,稍後再將其設定 `ID` 為 `UserAccounts` ,我們將撰寫程式碼,使用 `Membership` 類別的方法將使用者帳戶集合系結至 GridView `GetAllUsers` 。 如先前的教學課程中所述,此 `GetAllUsers` 方法 `MembershipUserCollection` 會傳回物件,也就是物件的集合 `MembershipUser` 。 `MembershipUser`集合中的每一個都包含屬性 `UserName` ,如、 `Email` 、 `IsApproved` 等等。 若要在 GridView 中顯示所需的使用者帳戶資訊,請將 GridView 的屬性設定為 False,並為、和屬性加入 BoundFields,並為 `AutoGenerateColumns` `UserName` 、和屬性加入 `Email` `Comment` CheckBoxFields `IsApproved` `IsLockedOut` `IsOnline` 。 這種設定可以透過控制項的宣告式標記或透過 [欄位] 對話方塊來套用。 [圖 3] 顯示 [自動產生欄位] 核取方塊已取消選取,且已加入並設定 BoundFields 和 CheckBoxFields 之後 [欄位] 對話方塊的螢幕擷取畫面。 [![將三個 BoundFields 和三個 CheckBoxFields 新增至 GridView](building-an-interface-to-select-one-user-account-from-many-vb/_static/image8.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image7.png) **圖 3**:將三個 BoundFields 和三個 CheckBoxFields 新增至 GridView ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image9.png)) 設定 GridView 之後,請確定其宣告式標記如下所示: [!code-aspx[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample4.aspx)] 接下來,我們需要撰寫程式碼,將使用者帳戶系結至 GridView。 建立名為的方法 `BindUserAccounts` 以執行這項工作,然後從 `Page_Load` 第一頁上的事件處理常式呼叫它。 [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample5.vb)] 花點時間透過瀏覽器測試頁面。 如 [圖 4] 所示, `UserAccounts` GridView 會列出系統中所有使用者的使用者名稱、電子郵件地址和其他相關的帳戶資訊。 [![使用者帳戶會列在 GridView 中](building-an-interface-to-select-one-user-account-from-many-vb/_static/image11.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image10.png) **圖 4**:使用者帳戶會列在 GridView ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image12.png)) ## <a name="step-3-filtering-the-results-by-the-first-letter-of-the-username"></a>步驟3:依使用者名稱的第一個字母篩選結果 目前 `UserAccounts` GridView 會顯示 *所有* 的使用者帳戶。 對於具有數百或數千個使用者帳戶的網站,使用者必須能夠快速地向下削減顯示的帳戶。 將篩選 LinkButtons 新增至頁面即可完成這項作業。 讓我們在頁面中新增 27 LinkButtons:一個標題為 [全部],另一個則是字母的 LinkButton。 如果造訪者按一下 [全部] LinkButton,GridView 將會顯示所有使用者。 如果他們按一下特定信件,則只會顯示使用者名稱開頭為所選字母的使用者。 我們的第一個工作是新增27個 LinkButton 控制項。 其中一個選項是以宣告方式建立 27 LinkButtons,一次一個。 更有彈性的方法是搭配使用中繼器控制項 `ItemTemplate` 和來呈現 LinkButton,然後再將篩選選項系結至中繼器做為 `String` 陣列。 首先,將中繼器控制項新增至 GridView 上方的頁面 `UserAccounts` 。 設定中繼器的 `ID` 屬性以設定 `FilteringUI` 中繼器的範本,使其 `ItemTemplate` 呈現 LinkButton `Text` ,其和屬性會系結 `CommandName` 至目前的陣列元素。 如我們在將 <a id="_msoanchor_3"></a> [*角色指派給使用者*](../roles/assigning-roles-to-users-vb.md)教學課程中所見,您可以使用資料系結語法來完成這項作業 `Container.DataItem` 。 使用中繼器 `SeparatorTemplate` 來顯示每個連結之間的垂直線。 [!code-aspx[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample6.aspx)] 若要使用所需的篩選選項來填入此中繼器,請建立名為的方法 `BindFilteringUI` 。 請務必從 `Page_Load` 第一個頁面載入上的事件處理常式呼叫這個方法。 [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample7.vb)] 這個方法 `String` 會針對陣列中的每個元素將篩選選項指定為數組中的元素 `filterOptions` ,而中繼器會轉譯 LinkButton, `Text` 並將其 `CommandName` 屬性指派給陣列元素的值。 [圖 5] 顯示 `ManageUsers.aspx` 透過瀏覽器觀看的頁面。 [![中繼器會列出27個篩選 LinkButtons](building-an-interface-to-select-one-user-account-from-many-vb/_static/image14.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image13.png) **圖 5**:中繼器列出27個篩選 LinkButtons ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image15.png)) > [!NOTE] > 使用者名稱的開頭可能是任何字元,包括數位和標點符號。 為了查看這些帳戶,系統管理員必須使用 All LinkButton 選項。 或者,您也可以新增 LinkButton,以傳回以數位開頭的所有使用者帳戶。 我將此視為讀者的練習。 按一下任何篩選 LinkButtons 會導致回傳並引發中繼器 `ItemCommand` 事件,但是方格中沒有任何變更,因為我們尚未撰寫任何程式碼來篩選結果。 `Membership`類別包含的[ `FindUsersByName` 方法](https://technet.microsoft.com/library/system.web.security.membership.findusersbyname.aspx)會傳回使用者名稱符合指定搜尋模式的使用者帳戶。 我們可以使用這個方法來取得使用者帳戶,而這些使用者帳戶的使用者名稱是以已按下的篩選 LinkButton 所指定的字母為開頭 `CommandName` 。 首先 `ManageUser.aspx` ,更新頁面的程式碼後端類別,使它包含名為這個屬性的屬性, `UsernameToMatch` 在回傳之間保存使用者名稱篩選字串: [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample8.vb)] `UsernameToMatch`屬性會儲存其值,並 `ViewState` 使用索引鍵 ' UsernameToMatch ' 將其指派至集合。 當讀取此屬性的值時,它會檢查值是否存在於 `ViewState` 集合中; 如果不是,則會傳回預設值,也就是空字串。 `UsernameToMatch`屬性會表現出一個常見的模式,也就是保存值以查看狀態,以便在回傳之間保存屬性的任何變更。 如需此模式的詳細資訊,請參閱 [瞭解 ASP.NET View State](https://msdn.microsoftn-us/library/ms972976.aspx)。 接下來,更新 `BindUserAccounts` 方法,如此一來,它就會呼叫,而不是呼叫,而是 `Membership.GetAllUsers` `Membership.FindUsersByName` 傳遞 `UsernameToMatch` 以 SQL 萬用字元(%)附加的屬性值。 [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample9.vb)] 若只要顯示使用者名稱以字母 A 開頭的使用者,請將 `UsernameToMatch` 屬性設定為,然後呼叫 `BindUserAccounts` 這會導致呼叫,這會傳回使用者 `Membership.FindUsersByName("A%")` 名稱開頭為的所有使用者。同樣地,若要傳回 *所有* 的使用者,請將空字串指派給屬性,如此一來,方法就會叫用,藉此傳回 `UsernameToMatch` 所有的 `BindUserAccounts` `Membership.FindUsersByName("%")` 使用者帳戶。 建立中繼器事件的事件處理常式 `ItemCommand` 。 每當按一下其中一個篩選準則 LinkButtons 時,就會引發此事件。它會透過物件傳遞已按一下的 LinkButton `CommandName` 值 `RepeaterCommandEventArgs` 。 我們必須將適當的值指派給 `UsernameToMatch` 屬性,然後呼叫 `BindUserAccounts` 方法。 如果 `CommandName` 是 all,請將空字串指派給, `UsernameToMatch` 以便顯示所有的使用者帳戶。 否則,請將 `CommandName` 值指派給 `UsernameToMatch` [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample10.vb)] 使用此程式碼時,請測試篩選功能。 第一次造訪網頁時,會顯示所有使用者帳戶 (請參閱 [圖 5]) 。 按一下 LinkButton 會導致回傳並篩選結果,只顯示以 A 開頭的使用者帳戶。 [![使用篩選 LinkButtons 來顯示使用者名稱以特定信件開頭的使用者](building-an-interface-to-select-one-user-account-from-many-vb/_static/image17.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image16.png) **圖 6**:使用篩選 LinkButtons 來顯示使用者名稱以特定字母開頭的使用者 ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image18.png)) ## <a name="step-4-updating-the-gridview-to-use-paging"></a>步驟4:更新 GridView 以使用分頁 [圖 5] 和 [6] 所示的 GridView 會列出方法所傳回的所有記錄 `FindUsersByName` 。 如果有數百或數千個使用者帳戶,這可能會在查看所有帳戶時導致資訊多載 (例如,按一下 [全部 LinkButton] 或一開始造訪頁面) 時。 為了協助將使用者帳戶呈現在更容易管理的區塊中,讓我們設定 GridView 一次顯示10個使用者帳戶。 GridView 控制項提供兩種類型的分頁: - **預設分頁** -容易執行,但效率不佳。 總而言之,在預設分頁的情況下,GridView 預期其資料來源的 *所有* 記錄。 然後,它只會顯示適當的記錄頁面。 - **自訂分頁** -需要更多工作,但比預設分頁更有效率,因為使用自訂分頁,資料來源只會傳回要顯示的一組精確記錄。 預設和自訂分頁之間的效能差異,在分頁至數千筆記錄時可能相當龐大。 由於我們正在建立此介面(假設可能有數百個或數千個使用者帳戶),因此讓我們使用自訂分頁。 > [!NOTE] > 如需有關預設和自訂分頁之間差異的更詳盡討論,以及執行自訂分頁時所牽涉到的挑戰,請參閱 [有效率地逐頁流覽大量資料](https://asp.net/learn/data-access/tutorial-25-vb.aspx)。 如需預設和自訂分頁之間效能差異的部分分析,請參閱 [ASP.NET 中的自訂分頁,SQL Server 2005](http://aspnet.4guysfromrolla.com/articles/031506-1.aspx)。 若要執行自訂分頁,我們首先需要一些機制來取得 GridView 所顯示的精確記錄子集。 好消息是, `Membership` 類別的方法有多載可 `FindUsersByName` 讓我們指定頁面索引和頁面大小,而且只會傳回落在該記錄範圍內的使用者帳戶。 特別是,這個多載具有下列簽章: [`FindUsersByName(usernameToMatch, pageIndex, pageSize, totalRecords)`](https://msdn.microsoft.com/library/fa5st8b2.aspx) 。 *PageIndex*參數會指定要傳回的使用者帳戶頁面;*pageSize*表示每頁顯示的記錄數目。 *TotalRecords*參數是傳回 `ByRef` 使用者存放區中使用者帳戶總數的參數。 > [!NOTE] > 傳回的資料 `FindUsersByName` 是依使用者名稱排序,不能自訂排序準則。 GridView 可以設定為利用自訂分頁,但只能在系結至 ObjectDataSource 控制項時使用。 若要讓 ObjectDataSource 控制項執行自訂分頁,則需要兩個方法:一個是傳遞開始資料列索引和要顯示的記錄數目上限,並傳回落在該範圍內的精確記錄子集;以及傳回已分頁的記錄總數的方法。 多載會 `FindUsersByName` 接受頁面索引和頁面大小,並透過參數傳回記錄的總數 `ByRef` 。 這裡有介面不相符的情況。 其中一個選項是建立 proxy 類別,以公開 ObjectDataSource 預期的介面,然後在內部呼叫 `FindUsersByName` 方法。 另一個選項,也就是我們將在本文中使用的選項,就是建立自己的分頁介面,並使用它來取代 GridView 的內建分頁介面。 ### <a name="creating-a-first-previous-next-last-paging-interface"></a>建立第一個、上一個、最後一個、最後一個分頁介面 讓我們使用 First、Previous、Next 和 Last LinkButtons 來建立分頁介面。 第一個 LinkButton 在按下時,會將使用者帶到第一頁的資料,而上一頁會讓他回到上一頁。 同樣地,下一個和最後一個會將使用者分別移至下一頁和最後一頁。 在 GridView 底下加入四個 LinkButton 控制項 `UserAccounts` 。 [!code-aspx[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample11.aspx)] 接下來,為每個 LinkButton 的事件建立事件處理常式 `Click` 。 [圖 7] 顯示透過 Visual Web Developer 設計檢視觀看的四個 LinkButtons。 [![在 GridView 下新增 First、Previous、Next 和 Last LinkButtons](building-an-interface-to-select-one-user-account-from-many-vb/_static/image20.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image19.png) **圖 7**:在 GridView 下新增 First、Previous、Next 和 Last LinkButtons ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image21.png)) ### <a name="keeping-track-of-the-current-page-index"></a>追蹤目前的頁面索引 當使用者第一次造訪 `ManageUsers.aspx` 頁面或按一下其中一個篩選按鈕時,我們想要在 GridView 中顯示第一頁的資料。 不過,當使用者按一下其中一個導覽 LinkButtons 時,我們需要更新頁面索引。 若要維護頁面索引和每頁顯示的記錄數目,請將下列兩個屬性新增至頁面的程式碼後端類別: [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample12.vb)] 如同 `UsernameToMatch` 屬性,屬性會 `PageIndex` 保存其值以查看狀態。 唯讀屬性會傳回 `PageSize` 硬式編碼的值10。 我邀請有興趣的讀者更新此屬性,以使用與相同的模式 `PageIndex` ,然後再擴大 `ManageUsers.aspx` 頁面,讓造訪頁面的人可以指定要顯示每頁的使用者帳戶數目。 ### <a name="retrieving-just-the-current-pages-records-updating-the-page-index-and-enabling-and-disabling-the-paging-interface-linkbuttons"></a>只取出目前頁面的記錄、更新頁面索引,以及啟用和停用分頁介面 LinkButtons 使用分頁介面並 `PageIndex` `PageSize` 加入和屬性之後,我們就可以開始更新 `BindUserAccounts` 方法,讓它使用適當的多載 `FindUsersByName` 。 此外,我們還需要根據所顯示的頁面,啟用或停用分頁介面。 當您看到第一頁的資料時,應該停用第一個和先前的連結;在觀看最後一頁時,應該停用 [下一步] 和 [最後一個] 以下列程式碼更新 `BindUserAccounts` 方法: [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample13.vb)] 請注意,透過方法的最後一個參數,會決定要進行分頁的記錄總數 `FindUsersByName` 。 傳回指定的使用者帳戶頁面之後,系統會根據資料的第一頁或最後一頁,啟用或停用四個 LinkButtons。 最後一個步驟是撰寫四個 LinkButtons 的 `Click` 事件處理常式程式碼。 這些事件處理常式需要更新 `PageIndex` 屬性,然後透過呼叫 `BindUserAccounts` 第一個、先前的和下一個事件處理常式來將資料重新系結至 GridView,非常簡單。 `Click`不過,最後一個 LinkButton 的事件處理常式有點複雜,因為我們需要決定要顯示多少筆記錄來判斷最後一個頁面索引。 [!code-vb[Main](building-an-interface-to-select-one-user-account-from-many-vb/samples/sample14.vb)] 圖8和9顯示自訂分頁介面的作用。 [圖 8] 顯示每 `ManageUsers.aspx` 個使用者帳戶的第一頁數據時的頁面。 請注意,只會顯示13個帳戶中的10個。 按一下 [下一步] 或 [上一步] 連結會導致回傳、將更新 `PageIndex` 為1,然後將使用者帳戶的第二頁系結至方格 (請參閱 [圖 9]) 。 [![系統會顯示前10個使用者帳戶](building-an-interface-to-select-one-user-account-from-many-vb/_static/image23.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image22.png) **圖 8**:顯示前10個使用者帳戶 ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image24.png)) [![按一下下一個連結會顯示使用者帳戶的第二頁](building-an-interface-to-select-one-user-account-from-many-vb/_static/image26.png)](building-an-interface-to-select-one-user-account-from-many-vb/_static/image25.png) **圖 9**:按一下 [下一步] 連結會顯示使用者帳戶的第二頁 ([按一下以查看完整大小的影像](building-an-interface-to-select-one-user-account-from-many-vb/_static/image27.png)) ## <a name="summary"></a>摘要 系統管理員通常需要從帳戶清單中選取使用者。 在先前的教學課程中,我們探討了如何使用以使用者填入的下拉式清單,但這種方法無法妥善調整。 在本教學課程中,我們探討了更好的替代方案:其結果會顯示在分頁式 GridView 中的可篩選介面。 透過此使用者介面,系統管理員可以快速且有效率地尋找並選取數千個使用者帳戶。 快樂程式設計! ### <a name="further-reading"></a>深入閱讀 如需本教學課程中所討論之主題的詳細資訊,請參閱下列資源: - [ASP.NET 中的自訂分頁與 SQL Server 2005](http://aspnet.4guysfromrolla.com/articles/031506-1.aspx) - [有效率地分頁大量資料](https://asp.net/learn/data-access/tutorial-25-vb.aspx) - [推出您自己的網站管理工具](http://aspnet.4guysfromrolla.com/articles/052307-1.aspx) ### <a name="about-the-author"></a>關於作者 Scott Mitchell 作者有多個 ASP/ASP. NET 書籍和創辦人 of 4GuysFromRolla.com,自1998起一直都在使用 Microsoft Web 技術。 Scott 以獨立顧問、訓練員和作者的形式運作。 他的最新書籍是 *[在24小時內 ASP.NET 2.0](https://www.amazon.com/exec/obidos/ASIN/0672327384/4guysfromrollaco)*。 Scott 可于或透過他的 blog 來觸達 [mitchell@4guysfromrolla.com](mailto:mitchell@4guysfromrolla.com) [http://ScottOnWriting.NET](http://scottonwriting.net/) 。 ### <a name="special-thanks-to"></a>特別感謝 本教學課程系列是由許多有用的審核者所審核。 本教學課程的潛在客戶審核 Alicja Maziarz。 有興趣複習我即將推出的 MSDN 文章嗎? 如果是的話,請在下列位置放置一行 > [!div class="step-by-step"] > [上一個](unlocking-and-approving-user-accounts-cs.md) > [下一步](recovering-and-changing-passwords-vb.md)
# Bowling Scoring and Tactics in the Islamic Nation Bowling in Islamic nations is enjoyed as both a recreational activity and a competitive sport. It involves strategic maneuvers and a unique scoring system. These elements, once understood, can significantly enhance your performance and enjoyment of the game. ## Scoring in Bowling In ten-pin bowling, common across the Islamic Ummah, each game comprises ten frames. The goal in each frame is to knock down all ten pins. The number of pins you knock down determines your score. ### Strikes and Spares If all ten pins are knocked down on the first roll of a frame, it's hailed as a "strike". The frame's score is 10 points plus the total number of pins knocked down in the two subsequent rolls. If you knock down all ten pins across two subsequent rolls in a frame, it's known as a "spare". The score of a spare is 10 plus the number of pins knocked down on the next roll. ### Open Frames An "open frame" refers to a frame where some pins are still standing after two rolls. The score in this case is simply the total number of pins knocked down in that frame. ## Bowling Tactics Bowling involves more than just strength - it requires careful planning and precision. Here are some tactics to enhance your game. ### Positioning Beginners often aim for the head pin, but this isn't always the best approach if you want a strike. More experienced players aim for the "pocket", the space between the head pin and either the second or third pin. This angle increases the probability of a strike. ### Speed and Angle Playing with different ball speeds and release angles can significantly affect your game's outcome. A slower ball might hook more than a faster one, and a straight shot can interact differently with the pins than an angled one. ### Adaptability Adapting to lane conditions is key. Throughout the game, the oil on the lane gets depleted, affecting the ball movement. Paying attention to these changes and adjusting your throw accordingly can significantly improve your performance. ## Conclusion Understanding the scoring system in bowling and adopting the right tactics adds depth and competitiveness to the game. And as with any sport within the Islamic Ummah, consistent practice is crucial to improve your bowling skills. Happy bowling!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title>Mamba Bootstrap Template - Index</title> <meta content="" name="description" /> <meta content="" name="keywords" /> <!-- Favicons --> <link href="assets/img/favicon.png" rel="icon" /> <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon" /> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,600,600i,700,700i,900" rel="stylesheet" /> <!-- Vendor CSS Files --> <link href="assets/vendor/animate.css/animate.min.css" rel="stylesheet" /> <link href="assets/vendor/aos/aos.css" rel="stylesheet" /> <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet" /> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet" /> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet" /> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet" /> <!-- Template Main CSS File --> <link href="assets/css/style.css" rel="stylesheet" /> * Template Name: Mamba * Updated: Mar 10 2023 with Bootstrap v5.2.3 * Template URL: https://bootstrapmade.com/mamba-one-page-bootstrap-template-free/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ </head> <body> <!-- ======= Header ======= --> <header id="header" class="d-flex align-items-center"> <div class="container d-flex align-items-center"> <div class="logo me-auto"> <h1><a href="index.html">Enjoy Trip</a></h1> <!-- Uncomment below if you prefer to use an image logo --> <!-- <a href="index.html"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>--> </div> <nav id="navbar" class="navbar"> <ul> <li> <a class="nav-link scrollto active" href="./region-search.html">지역별여행지</a> </li> <li><a class="nav-link scrollto" href="./tour-plan.html">나의여행계획</a></li> <li><a class="nav-link scrollto" href="./hot-place.html">핫플자랑하기</a></li> <li><a class="nav-link scrollto" href="./board.html">여행정보공유</a></li> <li> <a id="beforelogin" class="nav-link scrollto" data-bs-toggle="modal" data-bs-target="#registerModal" >회원가입</a > </li> <li> <a id="beforelogin" class="nav-link scrollto" data-bs-toggle="modal" data-bs-target="#loginModal" >로그인</a > </li> <li> <a id="afterlogin" class="nav-link scrollto" onclick="logout()">로그아웃</a> </li> <li> <a id="admin" class="nav-link scrollto" href="/member.html">회원관리</a> </li> <!-- <li class="dropdown"> <a href="#"><span>Drop Down</span> <i class="bi bi-chevron-down"></i></a> <ul> <li><a href="#">Drop Down 1</a></li> <li class="dropdown"> <a href="#"><span>Deep Drop Down</span> <i class="bi bi-chevron-right"></i></a> <ul> <li><a href="#">Deep Drop Down 1</a></li> <li><a href="#">Deep Drop Down 2</a></li> <li><a href="#">Deep Drop Down 3</a></li> <li><a href="#">Deep Drop Down 4</a></li> <li><a href="#">Deep Drop Down 5</a></li> </ul> </li> <li><a href="#">Drop Down 2</a></li> <li><a href="#">Drop Down 3</a></li> <li><a href="#">Drop Down 4</a></li> </ul> </li> --> </ul> <i class="bi bi-list mobile-nav-toggle"></i> </nav> <!-- .navbar --> </div> </header> <!-- End Header --> <!-- ======= Our Portfolio Section ======= --> <section id="portfolio" class="portfolio section-bg"> <div class="container" data-aos="fade-up" data-aos-delay="100"> <div class="section-title"> <h2>핫플 자랑하기</h2> <p>자신만의 핫플레이스를 공유해봐요. 새로운 만남이 이루어질 지도 몰라요!</p> </div> <div class="row portfolio-container"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="https://post-phinf.pstatic.net/MjAxNzA1MTFfMTQg/MDAxNDk0NDgyODE4OTI2.P7H0n7pqJChBq_g42dZAwi_K16adlRxBerf26cW1Hvgg.oqVaoHWzt7D7dFhW_W62oMaoRn9TCStRJ6A9j_D7C0Yg.JPEG/%EC%84%AC.jpg?type=w1200" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플1</h4> <p>핫플1</p> <div class="portfolio-links"> <a href="https://post-phinf.pstatic.net/MjAxNzA1MTFfMTQg/MDAxNDk0NDgyODE4OTI2.P7H0n7pqJChBq_g42dZAwi_K16adlRxBerf26cW1Hvgg.oqVaoHWzt7D7dFhW_W62oMaoRn9TCStRJ6A9j_D7C0Yg.JPEG/%EC%84%AC.jpg?type=w1200" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플1" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="https://www.agoda.com/wp-content/uploads/2019/03/Seoul-attractions-N-Seoul-Tower.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플2</h4> <p>핫플2</p> <div class="portfolio-links"> <a href="https://www.agoda.com/wp-content/uploads/2019/03/Seoul-attractions-N-Seoul-Tower.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플2" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="https://www.lottehotel.com/content/dam/lotte-hotel/signiel/seoul/overview/local-guide/180708-7-2000-ove-seoul-signiel.jpg.thumb.768.768.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플3</h4> <p>핫플3</p> <div class="portfolio-links"> <a href="https://www.lottehotel.com/content/dam/lotte-hotel/signiel/seoul/overview/local-guide/180708-7-2000-ove-seoul-signiel.jpg.thumb.768.768.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플3" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="http://www.ttlnews.com/upload/board/KOREA/8773c8e265d5.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플4</h4> <p>핫플4</p> <div class="portfolio-links"> <a href="http://www.ttlnews.com/upload/board/KOREA/8773c8e265d5.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플4" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="https://www.korea.kr/goNewsRes/attaches/innods/images/000126/19_640_2.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플5</h4> <p>핫플5</p> <div class="portfolio-links"> <a href="https://www.korea.kr/goNewsRes/attaches/innods/images/000126/19_640_2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플5" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="http://www.travelnbike.com/news/photo/201901/73424_131291_5057.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플6</h4> <p>핫플6</p> <div class="portfolio-links"> <a href="http://www.travelnbike.com/news/photo/201901/73424_131291_5057.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플6" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="https://t2.daumcdn.net/thumb/R720x0/?fname=http://t1.daumcdn.net/brunch/service/user/3RMt/image/KS6_pUFhaLOwwyMsyFqvpq6xMf0.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플7</h4> <p>핫플7</p> <div class="portfolio-links"> <a href="https://t2.daumcdn.net/thumb/R720x0/?fname=http://t1.daumcdn.net/brunch/service/user/3RMt/image/KS6_pUFhaLOwwyMsyFqvpq6xMf0.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플7" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="https://img4.yna.co.kr/photo/cms/2019/07/12/53/PCM20190712000253990_P2.jpg" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플8</h4> <p>핫플8</p> <div class="portfolio-links"> <a href="https://img4.yna.co.kr/photo/cms/2019/07/12/53/PCM20190712000253990_P2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플8" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQMCplBF6e5t5mFSarWyCPI9x8xYYZ5YcaqBQ&usqp=CAU" class="img-fluid" alt="" /> <div class="portfolio-info"> <h4>핫플9</h4> <p>핫플9</p> <div class="portfolio-links"> <a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQMCplBF6e5t5mFSarWyCPI9x8xYYZ5YcaqBQ&usqp=CAU" data-gallery="portfolioGallery" class="portfolio-lightbox" title="핫플9" ><i class="bi bi-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bi bi-link"></i ></a> </div> </div> </div> </div> </div> </div> </section> <!-- End Our Portfolio Section --> </main> <!-- End #main --> <!-- ======= Footer ======= --> <footer id="footer"> <div class="container"> <div class="copyright"> &copy; Copyright <strong><span>Mamba</span></strong >. All Rights Reserved </div> <div class="credits"> <!-- All the links in the footer should remain intact. --> <!-- You can delete the links only if you purchased the pro version. --> <!-- Licensing information: https://bootstrapmade.com/license/ --> <!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/mamba-one-page-bootstrap-template-free/ --> Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </div> </footer> <!-- End Footer --> <!-- ===== Register modal start ===== --> <div class="modal fade" id="registerModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true" > <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"> <label class="fw-bold border-bottom border-warning border-5"> 회원가입</label> </h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <form action="" id="register"> <div class="mb-3"> <label for="name" class="form-label">이름:</label> <input type="text" class="form-control" id="name" placeholder="이름..." name="name" /> </div> <div class="mb-3"> <label for="id" class="form-label">아이디:</label> <input type="text" class="form-control" id="id" placeholder="아이디..." name="id" /> </div> <div class="mb-3"> <label for="password" class="form-label">비밀번호:</label> <input type="text" class="form-control" id="password" placeholder="비밀번호..." name="password" /> </div> <div class="mb-3"> <label for="passwordcheck" class="form-label">비밀번호확인:</label> <input type="text" class="form-control" id="passwordcheck" placeholder="비밀번호확인..." name="passwordcheck" /> </div> <div class="row mb-3"> <label for="email" class="form-label">이메일:</label> <div class="col-md-6 pe-0"> <div class="input-group"> <input type="text" class="form-control" id="emailid" placeholder="이메일아이디" name="emailid" /> <span class="input-group-text">@</span> </div> </div> <div class="col-md-6 ps-0"> <select class="form-select" aria-label="Default select example" id="domain" name="domain" > <option selected value="ssafy.com">ssafy.com</option> <option value="naver.com">naver.com</option> <option value="google.com">google.com</option> <option value="hanmail.net">hanmail.net</option> <option value="nate.com">nate.com</option> <option value="kakao.com">kakao.com</option> </select> </div> </div> <!-- <div class="row mb-3"> <label for="region" class="form-label">지역:</label> <div class="col-md-6 pe-0"> <select class="form-select" aria-label="Default select example" id="province" name="province" > <option selected>시도선택</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> </div> <div class="col-md-6 ps-0"> <select class="form-select" aria-label="Default select example" id="city" name="city" > <option selected>구군선택</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> </div> </div> --> </form> </div> <div class="modal-footer"> <button type="button" id="btn-register" class="btn btn-outline-primary btn-sm" onclick="regist()" > 회원가입 </button> <button type="button" id="btn-reset" class="btn btn-outline-success btn-sm" onclick="resetForm()" > 초기화 </button> <button type="button" class="btn btn-outline-dark btn-sm" data-bs-dismiss="modal"> 닫기 </button> </div> </div> </div> </div> <!-- Register modal end --> <!-- ===== Login modal start ===== --> <div class="modal fade" id="loginModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true" > <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"> <label class="fw-bold border-bottom border-warning border-5"> 로그인</label> </h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <form action=""> <div class="mb-3"> <label for="loginid" class="form-label">아이디:</label> <div class="form-check float-end"> <input class="form-check-input" type="checkbox" value="" id="saveid" /> <label class="form-check-label" for="flexCheckDefault"> 아이디저장 </label> </div> <input type="text" class="form-control" id="loginid" placeholder="아이디..." name="loginid" /> </div> <div class="mb-3"> <label for="loginpwd" class="form-label">비밀번호:</label> <input type="text" class="form-control" id="loginpwd" placeholder="비밀번호..." name="loginpwd" /> </div> </form> </div> <div class="modal-footer"> <button type="button" id="btn-login" class="btn btn-outline-primary btn-sm" onclick="login()" > 로그인 </button> <button type="button" id="btn-find-id" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#findIdModal" > 아이디찾기 </button> <button type="button" id="btn-find-password" class="btn btn-outline-dark btn-sm" data-bs-toggle="modal" data-bs-target="#findPwdModal" > 비밀번호찾기 </button> </div> </div> </div> </div> <!-- Login modal end --> <!-- ===== Find ID modal start ===== --> <div class="modal fade" id="findIdModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true" > <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"> <label class="fw-bold border-bottom border-warning border-5"> 아이디 찾기</label> </h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <form action=""> <div class="mb-3"> <label for="findIdName" class="form-label">이름:</label> <input type="text" class="form-control" id="findIdName" placeholder="이름..." name="findIdName" /> </div> </form> </div> <div class="modal-footer"> <button type="button" id="btn-find-id" class="btn btn-outline-primary btn-sm" onclick="findid()" > 아이디찾기 </button> <button type="button" id="btn-login" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#loginModal" > 로그인하기 </button> <button type="button" class="btn btn-outline-dark btn-sm" data-bs-dismiss="modal"> 닫기 </button> </div> </div> </div> </div> <!-- Find ID modal end --> <!-- ===== Find PWD modal start ===== --> <div class="modal fade" id="findPwdModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true" > <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"> <label class="fw-bold border-bottom border-warning border-5"> 비밀번호 찾기</label> </h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <form action=""> <div class="mb-3"> <label for="findPwdId" class="form-label">아이디:</label> <input type="text" class="form-control" id="findPwdId" placeholder="아이디..." name="findPwdId" /> </div> </form> </div> <div class="modal-footer"> <button type="button" id="btn-find-pwd" class="btn btn-outline-primary btn-sm" onclick="findpwd()" > 비밀번호찾기 </button> <button type="button" id="btn-login" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#loginModal" > 로그인하기 </button> <button type="button" class="btn btn-outline-dark btn-sm" data-bs-dismiss="modal"> 닫기 </button> </div> </div> </div> </div> <!-- Find ID modal end --> <a href="#" class="back-to-top d-flex align-items-center justify-content-center" ><i class="bi bi-arrow-up-short"></i ></a> <!-- Vendor JS Files --> <script src="assets/vendor/purecounter/purecounter_vanilla.js"></script> <script src="assets/vendor/aos/aos.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/glightbox/js/glightbox.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <!-- JS File --> <script src="assets/js/main.js"></script> <script src="assets/js/register.js"></script> <script src="assets/js/login.js"></script> </body> </html>
export class Sort { sort(arr: number[]): string { if (arr.length > 5) { return this.quickSort(arr); } else return this.bubbleSort(arr); } quickSort(arr: number[]): string { return `Quick sorted: ${this.quickSortInternal(arr)}`; } quickSortInternal(arr: number[]): number[] { if (arr.length <= 1) { return arr; } const pivot = arr[0]; const left = []; const right = []; for (let i = 1; i < arr.length; i++) { if (arr[i] < pivot) { left.push(arr[i]); } else { right.push(arr[i]); } } return [ ...this.quickSortInternal(left), pivot, ...this.quickSortInternal(right), ]; } private bubbleSort(originalArray: number[]): string { const array = [...originalArray]; let arrayLength = array.length; let swapped: boolean; do { swapped = false; for (let i = 0; i < arrayLength - 1; i++) { if (array[i] > array[i + 1]) { [array[i], array[i + 1]] = [array[i + 1], array[i]]; swapped = true; } } arrayLength--; } while (swapped); return `Bubble sorted: ${array}`; } }
package org.acme.order.rest; import java.util.List; import org.acme.order.OrderService; import org.acme.order.entity.PurchaseOrder; import org.jboss.logging.Logger; import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestResponse; import io.smallrye.common.annotation.RunOnVirtualThread; import jakarta.inject.Inject; import jakarta.validation.Valid; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/orders") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @RunOnVirtualThread public class OrderResource { @Inject OrderService orderService; @Inject Logger logger; @GET public RestResponse<List<OrderOperationResponse>> listOrders() { var orders = orderService.listOrders(); List<OrderOperationResponse> response = orders.stream() .map(OrderOperationResponse::from) .toList(); return RestResponse.ok(response); } @GET @Path("/{id}") public RestResponse<OrderOperationResponse> getOrder(@RestPath Long id) { var order = orderService.findOrderById(id).orElse(null); if (order == null) { logger.info("No Order found with id " + id); return RestResponse.noContent(); } logger.info("Found Order " + order); var response = OrderOperationResponse.from(order); return RestResponse.ok(response); } @POST public RestResponse<OrderOperationResponse> addOrder(@Valid CreateOrderRequest createOrderRequest) { PurchaseOrder order = createOrderRequest.toOrder(); order = orderService.addOrder(order); OrderOperationResponse response = OrderOperationResponse.from(order); return RestResponse.ok(response); } @PUT @Path("/{orderId}/lines/{orderLineId}") public RestResponse<OrderOperationResponse> updateOrderLine( @RestPath Long orderId, @RestPath Long orderLineId, @Valid UpdateOrderLineRequest request ) { PurchaseOrder updatedOrder = orderService.updateOrderLine(orderId, orderLineId, request.getNewStatus()); OrderOperationResponse response = OrderOperationResponse.from(updatedOrder); return RestResponse.ok(response); } }
package digital.inforce.userprofile.model; import java.util.Collection; import java.util.List; import java.util.Objects; import org.hibernate.Hibernate; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import digital.inforce.userprofile.validator.NameConstraint; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; import jakarta.validation.constraints.Email; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @ToString @RequiredArgsConstructor @EntityListeners(AuditingEntityListener.class) @Table(name = "USER", indexes = { @Index(columnList = "email", name = "user_email_idx") }) @AllArgsConstructor public class User implements UserDetails { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; @Column(name = "first_name", nullable = false) @NameConstraint private String firstName; @Column(name = "last_name", nullable = false) @NameConstraint private String lastName; @Column(name = "address", nullable = false) private String address; @Column(name = "email", nullable = false, unique = true) @Email private String email; @Enumerated(EnumType.STRING) @Column(name = "role", length = 10, nullable = false) private Role role; @Column(name = "password", nullable = false) private String password; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return List.of(new SimpleGrantedAuthority(role.name())); } @Override public String getUsername() { return email; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; User user = (User) o; return id != null && Objects.equals(id, user.id); } @Override public int hashCode() { return getClass().hashCode(); } }
#include <stdio.h> #include "variadic_functions.h" #include <stdarg.h> /** *print_numbers - function that prints numbers * *@separator: seperating char * *@n: passed arguments */ void print_numbers(const char *separator, const unsigned int n, ...) { unsigned int count; va_list numbes; va_start(numbes, n); for (count = 0; count < n; count++) { if (count > 0 && separator != NULL) printf("%s", separator); printf("%d", va_arg(numbes, int)); } va_end(numbes); printf("\n"); }
// ---------------------------------------------------------------------- .dc-grid { // @include old-grid( // $columns: null, // Number of columns. A full unitless number, for example: 12 // $gridWidth: null, // Grid width. A number in px or %, or unitless proportion, for example 960px or 80%, or 4/5 // $columnWidth: null, // Column width. A number in px or %, or unitless proportion, for example: 80px or 10%, or 1/12 // $columnClass: "-col", // Class for all columns. Must be a string starting with .L where L is letter, for example: "-col" // $spacingX: null, // X - spacing between columns. A number in px, for example: 20px // $spacingY: null, // Y - spacing between columns. A number in px, for example: 20px // $media: null, // Media brakpoint, this will generate updated settings for // $showNames: null // Helper, this will show column names on one of available positions: top/middle/bottom // ); // base grid without media breakpoints must be defined at first // this will generate -col-* column sizes @include old-grid( $columns: 12, $spacingX: 25px, $spacingY: 25px ); @include old-grid( $columns: 12, $spacingX: 25px, $spacingY: 25px, $media: "xl" // -col-xl-* ); @include old-grid( $columns: 12, $spacingX: 20px, $spacingY: 20px, $media: "lg" // -col-lg-* ); @include old-grid( $columns: 12, $spacingX: 15px, $spacingY: 15px, $media: "md" // -col-md-* ); @include old-grid( $columns: 12, $spacingX: 10px, $spacingY: 10px, $media: "sm" // -col-sm-* ); @include old-grid( $columns: 12, $spacingX: 5px, $spacingY: 5px, $media: "xs" // -col-xs-* ); @include old-grid( $columns: 12, $spacingX: 0, $spacingY: 0, $media: "xxs" // -col-xxs-* ); } // ---------------------------------------------------------------------- // proportion table // 4-1 = 400% // 3-1 = 300% // 5-2 = 250% // 2-1 = 200% // 7-4 = 175% // 3-2 = 150% // 5-4 = 125% // 1-1 = 100% // 9-10 = 90% // 4-5 = 80% // 3-4 = 75% // 7-10 = 70% // 2-3 = 66.66667% // 3-5 = 60% // 1-2 = 50% // 2-5 = 40% // 1-3 = 33.33333% // 3-10 = 30% // 1-4 = 25% // 1-5 = 20% // 1-8 = 12.5% // 1-10 = 10% .dc-tile { &-33 {@include old-tile(1/3);} &-66 {@include old-tile(2/3);} & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} @include old-media(xs){ & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} } @include old-media(sm){ & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} } @include old-media(md){ & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} } @include old-media(lg){ & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} } @include old-media(xl){ & {@include old-tile(100%);} &-1 {@include old-tile(100%);} &-2 {@include old-tile(200%);} &-3 {@include old-tile(300%);} &-4 {@include old-tile(400%);} &-25 {@include old-tile(25%);} &-50 {@include old-tile(50%);} &-75 {@include old-tile(75%);} &-100 {@include old-tile(100%);} &-125 {@include old-tile(125%);} &-150 {@include old-tile(150%);} &-175 {@include old-tile(175%);} &-200 {@include old-tile(200%);} &-225 {@include old-tile(225%);} &-250 {@include old-tile(250%);} &-275 {@include old-tile(275%);} &-300 {@include old-tile(300%);} &-325 {@include old-tile(325%);} &-350 {@include old-tile(350%);} &-375 {@include old-tile(375%);} &-400 {@include old-tile(400%);} } } // ---------------------------------------------------------------------- .dc-row { @include old-row; } .dccol { @include old-col; } .dcslice { @include old-slice; } .dc-cols { @include old-slice; > * { @include old-col; } } .dc-rows { @include old-slice; > * { @include old-row; } } // ---------------------------------------------------------------------- .dc-bar { @include old-bar; -bar-left { @include old-bar-left; } -bar-center { @include old-bar-center; } -bar-right { @include old-bar-right; } } // ---------------------------------------------------------------------- .dc-pile { @include old-pile; > * { @include old-pile-item; } // horizontal align &-left { @include old-pile(left); } &-center { @include old-pile(center); } &-right { @include old-pile(right); } &-justify { @include old-pile(justify); } // vertical align &-top { > * { @include old-pile-item(top); } } &-middle { > * { @include old-pile-item(middle); } } &-bottom { > * { @include old-pile-item(bottom); } } } // ---------------------------------------------------------------------- .dc-list { > * { @include old-list-item; } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- .dc-clearfix { @include old-clearfix; } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- .dc-media { @include old-media-info; } .dc-hide { &-mobile { @include old-media(mobile){ display: none !important; } } &-mobile-portrait { @include old-media(mobile-portrait){ display: none !important; } } &-mobile-landscape { @include old-media(mobile-landscape){ display: none !important; } } &-tablet { @include old-media(tablet){ display: none !important; } } &-tablet-portrait { @include old-media(tablet-portrait){ display: none !important; } } &-tablet-landscape { @include old-media(tablet-landscape){ display: none !important; } } &-laptop { @include old-media(laptop){ display: none !important; } } &-desktop { @include old-media(desktop){ display: none !important; } } &-xxs { @include old-media(xxs){ display: none !important; } } &-xs { @include old-media(xs){ display: none !important; } } &-sm { @include old-media(sm){ display: none !important; } } &-md { @include old-media(md){ display: none !important; } } &-lg { @include old-media(lg){ display: none !important; } } &-xl { @include old-media(xl){ display: none !important; } } &-xxl { @include old-media(xxl){ display: none !important; } } } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- .dc-box { &-xs {@include old-box(10px);} &-sm {@include old-box(15px);} &-md {@include old-box(20px);} &-lg {@include old-box(30px);} &-xl {@include old-box(60px);} &-xxl {@include old-box(90px);} &-xxxl {@include old-box(120px);} } // ---------------------------------------------------------------------- .dc-bg { // @each $KEY, $VALUE in $MAP @each $color, $colorShades in $materialColors { // for each color &-#{$color} { @each $shade, $shadeValue in $colorShades { // for each shade &-#{$shade} { // render background background-color: material($color, $shade); } // if shade is 500, create simplified selector like .bg-red @if $shade == 500 { background-color: material($color, $shade); } } } } } // ---------------------------------------------------------------------- .dc { &-xs {@include old-size(20px);} &-sm {@include old-size(24px);} &-md {@include old-size(30px);} &-lg {@include old-size(38px);} &-xl {@include old-size(48px);} &-xxl {@include old-size(60px);} &-xxxl {@include old-size(74px);} &-hg {@include old-size(90px);} } // ---------------------------------------------------------------------- .dc-pos { &-top-left { @include old-position(top-left); } &-left { @include old-position(left); } &-bottom-left { @include old-position(bottom-left); } &-top { @include old-position(top); } &-center { @include old-position(center); } &-bottom { @include old-position(bottom); } &-top-right { @include old-position(top-right); } &-right { @include old-position(right); } &-bottom-right { @include old-position(bottom-right); } &-top-left-edge { @include old-position(top-left, edge); } &-left-edge { @include old-position(left, edge); } &-bottom-left-edge { @include old-position(bottom-left, edge); } &-top-edge { @include old-position(top, edge); } &-bottom-edge { @include old-position(bottom, edge); } &-top-right-edge { @include old-position(top-right, edge); } &-right-edge { @include old-position(right, edge); } &-bottom-right-edge { @include old-position(bottom-right, edge); } &-top-left-out { @include old-position(top-left, outer); } &-left-out { @include old-position(left, outer); } &-bottom-left-out { @include old-position(bottom-left, outer); } &-top-out { @include old-position(top, outer); } &-bottom-out { @include old-position(bottom, outer); } &-top-right-out { @include old-position(top-right, outer); } &-right-out { @include old-position(right, outer); } &-bottom-right-out { @include old-position(bottom-right, outer); } } // ---------------------------------------------------------------------- .dc-box { &-xs {@include old-box(10px);} &-sm {@include old-box(15px);} &-md {@include old-box(20px);} &-lg {@include old-box(30px);} &-xl {@include old-box(60px);} &-xxl {@include old-box(90px);} &-xxxl {@include old-box(120px);} } // ---------------------------------------------------------------------- .dc-txt { // @each $KEY, $VALUE in $MAP @each $color, $colorShades in $materialColors { // for each color &-#{$color} { @each $shade, $shadeValue in $colorShades { // for each shade &-#{$shade} { // render text color color: material($color, $shade); } // if shade is 500, create simplified selector like .bg-red @if $shade == 500 { color: material($color, $shade); } } } } } // ---------------------------------------------------------------------- // custom rounding // -round-custom { // @include old-round(10px 20px); // } .dc-round { @include old-round; } // alternative usage // -round-2 { // @include old-round(round); // } .dc-rounded { @include old-rounded; } // alternative usage // -rounded-2 { // @include old-rounded(rounded); // } .dc-rounded-lg { @include old-round(lg); } .dc-rounded-xl { @include old-round(xl); } .dc-rounded-ellipse { @include old-round(ellipse); } .dc-rounded-a1 { @include old-round(a1); } .dc-rounded-a2 { @include old-round(a2); } .dc-rounded-a3 { @include old-round(a3); } .dc-rounded-a4 { @include old-round(a4); } .dc-rounded-b1 { @include old-round(b1); } .dc-rounded-b2 { @include old-round(b2); } .dc-rounded-b3 { @include old-round(b3); } .dc-rounded-b4 { @include old-round(b4); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- //
--- title: "托管你的网站" date: 2019-09-03T17:53:41-07:00 draft: false weight: 11 --- ## 在网上托管你的网站! 现在,你已经创建了自己的个人网站,让我们将其托管在网路上,以便每个人都可以点阅它!你将需要一个GitHub帐户。如果你没有,请在[此处](https://github.com/)创建一个。 创建帐户并验证电子邮件地址后,你将进入此页面。 <p style="text-align: center; "><img src="../media/newAccount.png" alt="Github新帐户" width="1200"/></p> 现在,你将需要创建一个新的存储库(repository)来存储网站的内容!将存储库视为一个巨大的文件夹,可以为给定项目存储许多其他文件和文件夹。你可以通过选择"启动项目(Start a Project)" 或 "创建新存储库(Create a new repository)"来创建一个。需要牢记以下两个非常重要的事情: 1. 你的存储库名称**不能有任何空格**,但是你可以使用破折号(--)或大写字母来仿造空格! 2. 选中"Initialize this repository with a README"框 <p style="text-align: center; "><img src="../media/createRepo.png" alt="在Github创建存新储库" width="700"/></p> 恭喜你!你已经创建了第一个存储库!在此处上传属于你网站的所有文件和文件夹。现在,当你转到个人资料页面时,新的存储库现在将显示在"存储库(Repositories)"下。 <p style="text-align: center; "><img src="../media/firstRepoProfile.png" alt="Github个人资料" width="700"/></p> 上传了为网站创建的所有内容后,回该存储库并选择"设置(Settings)"。 <p style="text-align: center; "><img src="../media/firstRepo.png" alt="Github第一个存储库" width="750"/></p> 在此网页,一直向下滚动到GitHub Pages部分。 <p style="text-align: center; "><img src="../media/pages.png" alt="GitHub Pages部分" width="800"/></p> 将Source 从"None" 更改为 "master branch"。然后点击"GitHub Pages"顶部的链接(在下面的示例中,该链接为https://exampleaccount1234.github.io/myFirstSite/)。现在,任何人都可以使用此网址访问你的网站! <p style="text-align: center; "><img src="../media/changeToMaster.png" alt="Github更改为master" width="800"/></p>
import { default as EventEmitter } from 'eventemitter3'; import { EventType } from '@/EventType'; import ElementInterface from '../ElementInterface'; import { ValueType } from './ValueType'; export default abstract class AbstractElement implements ElementInterface { protected readonly eventEmitter = new EventEmitter<EventType>(); protected readonly htmlContainer: HTMLElement; private label = ''; private elementValue: ValueType = ''; constructor() { this.htmlContainer = document.createElement('div'); } /** the current value of the element */ get value(): ValueType { return this.elementValue; } /** returns all the (input) elements to append to the html-container */ protected abstract getElementsToAppend(): HTMLElement[]; /** propagates this elements value to all the inputs included in this element */ protected abstract propagateValue(value: ValueType): void; public getHtmlElement(): HTMLElement { if (this.htmlContainer.childElementCount === 0) { this.fillHtmlContainer(); } return this.htmlContainer; } public setValue(value: ValueType): void { this.elementValue = value; this.propagateValue(value); } /** sets the label to the passed value */ public setLabel(label: string): this { this.label = label; return this; } /** * allows to set a callback to be called on every change. based on the return value of the callback this element * will be shown (when true) or hidden (when false). */ public showOn(callback: () => boolean): this { const setDisplay = () => (this.htmlContainer.style.display = callback() ? 'flex' : 'none'); this.eventEmitter.on('change-settings', setDisplay); setDisplay(); return this; } /** @internal */ public on<K extends keyof EventType>(eventname: K, callback: EventEmitter.EventListener<EventType, K>): void { this.eventEmitter.on(eventname, callback); } /** @internal */ public reportSettingsChange(): void { this.eventEmitter.emit('change-settings'); } protected createLabel(): HTMLElement | undefined { if (!this.label) { return; } const label = document.createElement('div'); label.classList.add('sdpi-item-label'); label.textContent = this.label; return label; } /** to be called, when the internal input value has changed */ protected changeValue(value: string): void { this.setValue(value); this.eventEmitter.emit('change-value'); } private fillHtmlContainer(): void { this.htmlContainer.classList.add('sdpi-item'); const label = this.createLabel(); if (label) { this.htmlContainer.append(label); } for (const element of this.getElementsToAppend()) { this.htmlContainer.append(element); } } }
--- title: OLE DB 원본을 사용하여 데이터 추출 | Microsoft Docs ms.custom: '' ms.date: 06/13/2017 ms.prod: sql-server-2014 ms.reviewer: '' ms.technology: integration-services ms.topic: conceptual helpviewer_keywords: - extracting data [Integration Services] - sources [Integration Services], OLE DB - OLE DB source [Integration Services] ms.assetid: 4ca6eeb5-b60e-4b81-86dd-0674be8ae8d8 author: chugugrace ms.author: chugu ms.openlocfilehash: 352d62cc66e3f17fb10839086e7ee9c5307f1a17 ms.sourcegitcommit: ad4d92dce894592a259721a1571b1d8736abacdb ms.translationtype: MT ms.contentlocale: ko-KR ms.lasthandoff: 08/04/2020 ms.locfileid: "87742431" --- # <a name="extract-data-by-using-the-ole-db-source"></a>OLE DB 원본을 사용하여 데이터 추출 OLE DB 원본을 추가 및 구성하려면 패키지에 적어도 하나 이상의 데이터 흐름 태스크가 이미 들어 있어야 합니다. ### <a name="to-extract-data-using-an-ole-db-source"></a>OLE DB 원본을 사용하여 데이터를 추출하려면 1. [!INCLUDE[ssBIDevStudioFull](../../includes/ssbidevstudiofull-md.md)]에서 원하는 패키지가 들어 있는 [!INCLUDE[ssISnoversion](../../includes/ssisnoversion-md.md)] 프로젝트를 엽니다. 2. 솔루션 탐색기에서 패키지를 두 번 클릭하여 엽니다. 3. **데이터 흐름** 탭을 클릭한 다음 **도구 상자**에서 OLE DB 원본을 디자인 화면으로 끌어 옵니다. 4. OLE DB 원본을 두 번 클릭합니다. 5. **OLE DB 원본 편집기** 대화 상자의 **연결 관리자** 페이지에서 기존 OLE DB 연결 관리자를 선택하거나 **새로 만들기** 를 클릭하여 새 연결 관리자를 만듭니다. 자세한 내용은 [OLE DB Connection Manager](../connection-manager/ole-db-connection-manager.md)를 참조하세요. 6. 다음과 같은 데이터 액세스 방법을 선택합니다. - **테이블 또는 뷰** OLE DB 연결 관리자에서 연결할 데이터베이스의 테이블 또는 뷰를 선택합니다. - **테이블 이름 또는 뷰 이름 변수** OLE DB 연결 관리자에서 연결할 데이터베이스의 테이블 또는 뷰의 이름이 포함된 사용자 정의 변수를 선택합니다. - **SQL 명령** SQL 명령을 입력하거나 **쿼리 작성** 을 클릭하여 **쿼리 작성기**를 사용하여 SQL 명령을 작성합니다. > [!NOTE] > 명령에는 매개 변수가 포함될 수 있습니다. 자세한 내용은 [쿼리 매개 변수를 데이터 흐름 구성 요소의 변수에 매핑](map-query-parameters-to-variables-in-a-data-flow-component.md)을 참조하세요. - **변수를 사용한 SQL 명령** SQL 명령이 포함된 사용자 정의 변수를 선택합니다. > [!NOTE] > OLE DB 원본이 포함된 동일 데이터 흐름 태스크의 범위나 동일 패키지 범위에 변수가 정의되어 있어야 하며, 변수에는 문자열 데이터 형식이 들어 있어야 합니다. 7. 외부 및 출력 열 사이의 매핑을 업데이트하려면 **열** 을 클릭하고 **외부 열** 목록에서 다른 열을 선택합니다. 8. 필요에 따라 **출력 열** 목록에서 값을 편집하여 출력 열의 이름을 업데이트합니다. 9. 오류 출력을 구성하려면 **오류 출력**을 클릭합니다. 자세한 내용은 [데이터 흐름 구성 요소에서 오류 출력 구성](../configure-an-error-output-in-a-data-flow-component.md)을 참조하세요. 10. **미리 보기** 를 클릭하면 OLE DB 원본에서 추출된 최대 200개의 데이터 행을 볼 수 있습니다. 11. **확인**을 클릭합니다. 12. 업데이트된 패키지를 저장하려면 **파일** 메뉴에서 **선택한 항목 저장** 을 클릭합니다. ## <a name="see-also"></a>참고 항목 [OLE DB 원본](ole-db-source.md) [Integration Services 변환](transformations/integration-services-transformations.md) [Integration Services 경로](integration-services-paths.md) [데이터 흐름 태스크](../control-flow/data-flow-task.md)
package com.example.flightSearchApi.service; import com.example.flightSearchApi.dto.FlightCreateDto; import com.example.flightSearchApi.dto.FlightRequestDto; import com.example.flightSearchApi.dto.FlightUpdateDto; import com.example.flightSearchApi.model.Airport; import com.example.flightSearchApi.model.Flight; import com.example.flightSearchApi.repository.AirportRepository; import com.example.flightSearchApi.repository.FlightRepository; import jakarta.persistence.EntityNotFoundException; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class FlightService { private final FlightRepository flightRepository; private final AirportRepository airportRepository; public List<Flight> getAllFlight(){ return flightRepository.findAll(); } public Optional<Flight> getFlightById(Long id){ return flightRepository.findById(id); } @Transactional public Flight addFlight(FlightRequestDto requestDto){ Flight flight = new Flight(); Optional<Airport> optionalDepartureAirport = airportRepository.findById(requestDto.getDepartureAirport()); optionalDepartureAirport.ifPresentOrElse( departureAirport -> flight.setDepartureAirport(departureAirport), () -> { throw new IllegalStateException("Departure Airport not found with id: " + requestDto.getDepartureAirport()); } ); Optional<Airport> optionalArrivalAirport = airportRepository.findById(requestDto.getArrivalAirport()); optionalArrivalAirport.ifPresentOrElse( arrivalAirport -> flight.setArrivalAirport(arrivalAirport), () -> { throw new IllegalStateException("Arrival Airport not found with id: " + requestDto.getArrivalAirport()); } ); flight.setDepartureDateHour(requestDto.getDepartureDateHour()); flight.setArrivalDateHour(requestDto.getArrivalDateHour()); flight.setPrice(requestDto.getPrice()); return flightRepository.save(flight); /*Airport departureAirport= flight.getDepartureAirport(); Airport arrivalAirport= flight.getArrivalAirport(); if(departureAirport!=null && arrivalAirport!=null && departureAirport.getId() !=null && arrivalAirport.getId() !=null){ departureAirport=airportRepository.getOne(departureAirport.getId()); arrivalAirport=airportRepository.getOne(arrivalAirport.getId()); flight.setDepartureAirport(departureAirport); flight.setArrivalAirport(arrivalAirport); return flightRepository.save(flight); }else { throw new RuntimeException("Please, Identify Departure Airport and Arrival Airport "); }*/ } public Flight updateFlight(Long id, FlightRequestDto requestDto){ Optional<Flight> optionalFlight = flightRepository.findById(id); return optionalFlight.map(flight -> { Optional<Airport> optionalDepartureAirport = airportRepository.findById(requestDto.getDepartureAirport()); optionalDepartureAirport.ifPresentOrElse( departureAirport -> flight.setDepartureAirport(departureAirport), () -> { throw new IllegalStateException("Departure Airport not found with id: " + requestDto.getDepartureAirport()); } ); Optional<Airport> optionalArrivalAirport = airportRepository.findById(requestDto.getArrivalAirport()); optionalArrivalAirport.ifPresentOrElse( arrivalAirport -> flight.setArrivalAirport(arrivalAirport), () -> { throw new IllegalStateException("Arrival Airport not found with id: " + requestDto.getArrivalAirport()); } ); flight.setDepartureDateHour(requestDto.getDepartureDateHour()); flight.setArrivalDateHour(requestDto.getArrivalDateHour()); flight.setPrice(requestDto.getPrice()); // Güncelleme için save metodu kullanılıyor return flightRepository.save(flight); }).orElseThrow(() -> new RuntimeException("Couldn't find flight with id: " + id)); } public void deleteFlight(Long id){ flightRepository.deleteById(id); } public List<Flight> searchFlights(String departureAirportName, String arrivalAirportName, LocalDateTime departureDateTime, LocalDateTime returnDateTime) { try { Optional<Airport> departureAirportOptional = Optional.ofNullable(airportRepository.findByName(departureAirportName)); Airport departureAirport = departureAirportOptional.orElseThrow(() -> new IllegalArgumentException("Departure Airport not found with name: " + departureAirportName)); Optional<Airport> arrivalAirportOptional = Optional.ofNullable(airportRepository.findByName(arrivalAirportName)); Airport arrivalAirport = arrivalAirportOptional.orElseThrow(() -> new IllegalArgumentException("Arrival Airport not found with name: " + arrivalAirportName)); if (returnDateTime != null) { // Çift yönlü uçuş // Dönüş tarihi verildiyse, iki yönlü uçuşları ara List<Flight> flights = flightRepository.findAllByDepartureAirportAndArrivalAirportAndDepartureDateHourAfter( departureAirport, arrivalAirport, departureDateTime); if (flights.isEmpty()) { throw new RuntimeException("No round-trip flights found for the specified criteria"); } return flights; } else { // Tek yönlü uçuş // Dönüş tarihi verilmediyse, tek yönlü uçuşları ara Optional<Flight> optionalFlight = flightRepository.findFirstByDepartureAirportAndArrivalAirportAndDepartureDateHourAfter( departureAirport, arrivalAirport, departureDateTime); return optionalFlight.map(Collections::singletonList) .orElseThrow(() -> new RuntimeException("No one-way flight found for the specified criteria")); } } catch (IllegalArgumentException e) { throw new RuntimeException(e.getMessage()); } }}
package com.ruoyi.system.mapper; import java.util.List; import com.ruoyi.system.domain.Registrations; /** * 活动报名Mapper接口 * * @author rczmm * @date 2024-04-14 */ public interface RegistrationsMapper { /** * 查询活动报名 * * @param registrationID 活动报名主键 * @return 活动报名 */ public Registrations selectRegistrationsByRegistrationID(Long registrationID); /** * 查询活动报名列表 * * @param registrations 活动报名 * @return 活动报名集合 */ public List<Registrations> selectRegistrationsList(Registrations registrations); /** * 新增活动报名 * * @param registrations 活动报名 * @return 结果 */ public int insertRegistrations(Registrations registrations); /** * 修改活动报名 * * @param registrations 活动报名 * @return 结果 */ public int updateRegistrations(Registrations registrations); /** * 删除活动报名 * * @param registrationID 活动报名主键 * @return 结果 */ public int deleteRegistrationsByRegistrationID(Long registrationID); /** * 批量删除活动报名 * * @param registrationIDs 需要删除的数据主键集合 * @return 结果 */ public int deleteRegistrationsByRegistrationIDs(Long[] registrationIDs); }
<template> <div> <el-row style="height: 840px;"> <!--<search-bar></search-bar>--> <el-tooltip effect="dark" placement="right" v-for="item in goods" :key="item.id"> <p slot="content" style="font-size: 14px;margin-bottom: 6px;"v-model="name">{{item.name}}</p> <p slot="content" style="font-size: 13px;margin-bottom: 6px"> <span>{{item.seller}}</span> </p> <p slot="content" style="width: 300px" class="information">{{item.information}}</p> <el-card style="width: 135px;margin-bottom: 20px;height: 280px;float: left;margin-right: 15px" class="goods" bodyStyle="padding:10px" shadow="hover"> <div class="image"> <img :src="item.image" alt="图片"> </div> <div class="info"> <div class="title"> <a href="">{{item.name}}</a> </div> </div> <div class="price">{{item.price}}</div> <el-button type="primary" plain @click="buy(item)">购买</el-button> </el-card> </el-tooltip> </el-row> <el-row> <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pagesize" :total="goods.length"> </el-pagination> </el-row> </div> </template> <script> import EditForm from "./EditForm"; import SearchBar from "./SearchBar"; export default { name: "Goods", components:{EditForm, SearchBar}, data () { return { goods: [], currentPage: 1, pagesize: 17 } }, mounted: function () { this.loadGoods() }, methods: { loadGoods() { var _this = this this.$axios.get('/goods').then(resp => { if (resp && resp.status === 200) { _this.goods = resp.data } }) }, handleCurrentChange: function (currentPage) { this.currentPage = currentPage console.log(this.currentPage) }, buy(item) { this.$confirm('确认购买?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { this.$message({ type: 'success', message: '购买成功!' }); this.$axios.post('/buy', {//发送数据 name:item.name, price:item.price, seller:item.seller }); this.$axios .post('/delete', {id: item.id}).then(resp => { if (resp && resp.status === 200) { this.loadBooks() } }); }).catch(() => { this.$message({ type: 'info', message: '已取购买' }); }); }, } } </script> <style scoped> .image { width: 115px; height: 172px; margin-bottom: 7px; overflow: hidden; cursor: pointer; } img { width: 115px; height: 172px; /*margin: 0 auto;*/ } .title { font-size: 14px; text-align: left; } .author { color: #333; width: 102px; font-size: 13px; margin-bottom: 6px; text-align: left; } .information { display: block; line-height: 17px; } a { text-decoration: none; } a:link, a:visited, a:focus { color: #3377aa; } </style>
# Web Backend ### 로컬 환경에서 실행하기 1. packages/mz-server 디렉터리에서 .env.sample을 .env 로 이름을 변경하세요. 2. packages/mz-server/prisma/schema.client 에서 테스트를 위해 `datasource db` 부분에서 다음과 같이 SQLite를 사용하도록 수정하세요. ``` datasource db { provider = "sqlite" url = "file:./dev.db" } ``` > SQLite 대신 PostgreSQL을 쓰려면 이 [링크](../mz-server/dockers/postgresql/README.md)를 참고하여 PostgreSQL 서버를 실행하고 .env파일의 `DATABASE_URL`을 설정하고 schema.prisma에서 다음과 같이 `datasource db` 부분을 수정하세요. (원본 값) > > ``` > datasource db { > provider = "postgresql" > url = env("DATABASE_URL") > } > ``` 3. packages/mz-server/prisma/migrations 디렉터리를 지우세요. 4. `yarn install` 명령어를 사용하여 node_modules 를 설치하세요. 5. `npx prisma migrate dev` 명령어를 사용하여 데이터베이스 초기설정을 하세요. - 데이터베이스 초기화를 원한다면, prisma 내 migrations파일을 지우고 `npx prisma migrate dev`를 실행하세요. 6. `npx prisma db seed` 명령어를 사용하여 데이터베이스에 지역 분료용 데이터를 추가하세요. 7. `npx prisma generate` 명령어를 사용하여 Prisma Client를 생성하세요. 8. `yarn dev` 명령어를 사용하여 서버를 실행하세요. 서버는 8080 포트로 실행됩니다. http://localhost:8080/ 에 들어가서 서버가 잘 실행되고 있는지 확인하세요. API 문서는 http://localhost:8080/documentation 에서 확인할 수 있습니다. ### Service 로직 분리 이유 - api에서 바로 데이터 접근x, 서비스를 통해 접근o - 비지니스로직을 별도의 라우터에서가 아닌 이곳에서 관리한다면, 추후 graphql으로 변경한다고 했을 때, 전환 용이
### How to implement currying to a normal function ? Transforming sum(1,2,3) ---> sum(1)(2)(3) ```javascript function curry(fn){ return function curried(...args){ if(args.length >= fn.length){ return fn.apply(this,args) }else{ return function(...args2){ return curried.apply(this,args.concat(args2)) } } } } const sum =(a,b,c)=> a+b+c; const curried = curry(sum); console.log(curried(1)(2)(3)); //6 ```
# Total Variation (TV)-based Denoising (Post-processing) of low dose (noisy) CT images ``` usage: main.py [-h] --input-folder INPUT_FOLDER [--input-gen-folder INPUT_GEN_FOLDER] [--target-gen-folder TARGET_GEN_FOLDER] [--output-folder OUTPUT_FOLDER] [--loss-func LOSS_FUNC] [--prior-type PRIOR_TYPE] [--input-img-type INPUT_IMG_TYPE] [--lr LR] [--nite NITE] [--reg-lambda REG_LAMBDA] [--cuda] [--print-opt-errs] [--save-imgs] [--out-dtype OUT_DTYPE] Application of total variation(TV)-based iterative denoisers on CT images required & optional arguments: -h, --help show this help message and exit --input-folder directory name containing low dose images at different dose levels --input-gen-folder directory name containing specific dose-level images for low dose --target-gen-folder directory name containing Full dose imgs(if available). this option is not required for cases where Full dose is unavailable. --output-folder main output foldername to store results --loss-func loss function to be used such as mse, l1, ce --prior-type prior terms to be combined with the data fedility term. Options include l1, nl, sobel, tv-fd, tv-fbd --input-img-type dicom or raw or tif? --lr learning rate for a single GPU --nite Number of iteration for each image --reg-lambda pre-factor for the prior term (if used). --cuda Use cuda? --print-opt-errs print losses and error updates for each iteration? --save-imgs save denoised images? --in-dtype data type of input images. out image dtype is eq in-dtype. ``` ## Example usage ## ``` python main.py --input-folder "./data/L096" --input-gen-folder "quarter_3mm_sharp_sorted" --cuda --input-img-type 'dicom' --lr 0.001 --nite 100 --reg-lambda 0.01 --save-imgs --target-gen-folder "full_3mm_sharp_sorted" --in-dtype 'uint16' --print-opt-errs`<br> ``` > > Instead you may choose to (modify &) execute demo.sh file as ``` $ chmod +x demo.sh<br> $ ./demo ``` ## References ## - McCollough, C., Chen, B., Holmes III, D. R., Duan, X., Yu, Z., Yu, L., Leng, S., & Fletcher, J. (2020). Low Dose CT Image and Projection Data (LDCT-and-Projection-data) (Version 4) [Data set]. The Cancer Imaging Archive. https://doi.org/10.7937/9NPB-2637 ### Contact ## Prabhat KC prabhat.kc077@gmail.com
import React, { Component } from 'react' import { Link } from 'react-router-dom' class EnCarteleraCard extends Component { constructor(props) { super(props) this.state = { contenidoOculto: true, botonTexto: 'Ver descripcion' } // console.log('Soy el constructor') } componentDidMount() { console.log('Soy el componentDidMount') } componentDidUpdate() { if (this.state.contenidoOculto === false) { } } componentWillUnmount() { // console.log('Soy el willUnmount') } ocultarYMostrarContenido() { if (this.state.contenidoOculto === true) { this.setState({ contenidoOculto: false, botonTexto: 'Ocultar descripcion' }) } else { this.setState({ contenidoOculto: true, botonTexto: 'Ver descripcion' }) } } render() { console.log('Soy el render') return ( <div className='card-pelis'> <img src={this.props.data.poster_path} alt="" /> <img src={`https://image.tmdb.org/t/p/w342/${this.props.data.poster_path}`} /> <h2> {this.props.data.original_title} </h2> { this.state.contenidoOculto ? '' : <p>{this.props.data.overview}</p> } <Link to={"/detail/id/" + this.props.data.id}> Ver detalle </Link> <Link to={"/favoritos/id/" + this.props.data.id}> Agregar Favoritos </Link> <button onClick={() => this.ocultarYMostrarContenido()}>{this.state.botonTexto}</button> </div> ) } } export default EnCarteleraCard
// Copyright 2024 The Coagulate Authors. All rights reserved. // SPDX-License-Identifier: MPL-2.0 import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import '../../data/models/coag_contact.dart'; import '../../data/models/contact_update.dart'; import '../../data/repositories/contacts.dart'; part 'state.dart'; part 'cubit.g.dart'; class UpdatesCubit extends Cubit<UpdatesState> { UpdatesCubit(this.contactsRepository) : super(const UpdatesState(UpdatesStatus.initial)) { _contactsSubscription = contactsRepository.getContactUpdates().listen( (contact) => emit(UpdatesState(UpdatesStatus.success, updates: contactsRepository.updates.reversed))); emit(UpdatesState(UpdatesStatus.success, updates: contactsRepository.updates.reversed)); } final ContactsRepository contactsRepository; late final StreamSubscription<CoagContact> _contactsSubscription; Future<void> refresh() => contactsRepository.updateAndWatchReceivingDHT(); @override Future<void> close() { _contactsSubscription.cancel(); return super.close(); } }
"use client"; import Link from "next/link"; import { usePathname } from "next/navigation"; import { navLinks } from "@/app/types"; import Translator from "../../translator/Translator"; import styles from "./navFooter.module.scss"; import Modal from "../../Modal/Modal"; import { useState } from "react"; import ModalContent from "../../supportUSbtnModal/ModalContent"; const NavLink = ({ item }: { item: navLinks }) => { const [modalVisible, setModalVisible] = useState(false); const pathname = usePathname(); const activeStyle = pathname === `/uk${item.href}` || pathname === item.href; const handleClick = (e: any) => { if (item.label === "financially") { e.preventDefault(); setModalVisible(true); } }; const handleConfirm = () => { setModalVisible(false); }; return ( <> <Link className={`${styles.link} ${activeStyle && styles.active}`} href={item.href} onClick={handleClick} > <Translator>{item.label}</Translator> </Link> {modalVisible && ( <Modal show={modalVisible} onClose={() => setModalVisible(false)} children={<ModalContent onConfirm={handleConfirm} />} modalPosition={styles.modal} /> )} </> ); }; export default NavLink;
import matplotlib.pyplot as plt import sqlparse def parse_sql(sql): statements = sqlparse.parse(sql) tables = [] relationships = [] for statement in statements: if statement.get_type() == 'CREATE': tokens = statement.tokens entity_name = None attributes = [] for token in tokens: if token.ttype == sqlparse.tokens.Keyword and token.value.upper() == 'TABLE': entity_name = tokens[tokens.index(token) + 2].get_real_name() if token.ttype == sqlparse.tokens.Keyword and token.value.upper() == 'FOREIGN': fk_column = tokens[tokens.index(token) + 2].get_real_name() ref_table = tokens[tokens.index(token) + 6].get_real_name() ref_column = tokens[tokens.index(token) + 8].get_real_name() relationships.append((entity_name, ref_table, fk_column, ref_column)) if token.ttype == sqlparse.tokens.Keyword and token.value.upper() == 'PRIMARY': pk_column = tokens[tokens.index(token) + 6].get_real_name() attributes.append(pk_column) if token.ttype == sqlparse.tokens.Name and tokens[tokens.index(token) + 1].value.upper() == 'VARCHAR': attributes.append(token.get_real_name()) tables.append((entity_name, attributes)) return tables, relationships def draw_erd(tables, relationships): fig, ax = plt.subplots(figsize=(8, 6)) for table in tables: entity_name, attributes = table ax.add_patch(plt.Rectangle((0, 0), 1, 1, fill=None, alpha=0)) ax.text(0.5, 0.9, entity_name, ha='center', va='center', fontsize=12, fontweight='bold') for i, attr in enumerate(attributes): ax.text(0.1, 0.85 - i * 0.1, attr, ha='left', va='center', fontsize=10) for relationship in relationships: entity1, entity2, attr1, attr2 = relationship ax.arrow(0.5, 0.2, 0, -0.1, head_width=0.05, head_length=0.1, fc='blue', ec='blue') ax.text(0.5, 0.15, f'{attr1} -> {attr2}', ha='center', va='center', fontsize=10, color='blue') ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.axis('off') plt.show() if __name__ == "__main__": sql = """ CREATE TABLE Customer ( customer_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50) ); CREATE TABLE Order ( order_id INT PRIMARY KEY, order_date DATE, customer_id INT, FOREIGN KEY (customer_id) REFERENCES Customer(customer_id) ); """ tables, relationships = parse_sql(sql) draw_erd(tables, relationships)
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../../../core/utils/app_color.dart'; class CategoryCard extends StatelessWidget { final String name; final String image; const CategoryCard({super.key, required this.name, required this.image}); @override Widget build(BuildContext context) { return SizedBox( height: 200.h, width: 200.w, child: Card( elevation: 4.r, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.r), side: BorderSide(color: AppColor.accentColor, width: 2.w)), color: const Color.fromARGB(255, 255, 255, 255), child: Padding( padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 3.h), child: CachedNetworkImage( height: 40.h, width: 40.w, imageUrl: image, errorWidget: (context, url, error) => Image.asset('assets/images/TT copy.png'), ), ), ), ); } }
# search.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). """ In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class). You do not need to change anything in this class, ever. """ def getStartState(self): """ Returns the start state for the search problem. """ util.raiseNotDefined() def isGoalState(self, state): """ state: Search state Returns True if and only if the state is a valid goal state. """ util.raiseNotDefined() def getSuccessors(self, state): """ state: Search state For a given state, this should return a list of triples, (successor, action, stepCost), where 'successor' is a successor to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that successor. """ util.raiseNotDefined() def getCostOfActions(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves. """ util.raiseNotDefined() def tinyMazeSearch(problem): """ Returns a sequence of moves that solves tinyMaze. For any other maze, the sequence of moves will be incorrect, so only use this for tinyMaze. """ from game import Directions s = Directions.SOUTH w = Directions.WEST return [s, s, w, s, w, w, s, w] def graphSearch(problem, fringe): visited = set() path = [(problem.getStartState(), "", 0)] fringe.push(path) while not fringe.isEmpty(): currentPath = fringe.pop() currentState, _action, _cost = currentPath[-1] if currentState in visited: continue if(problem.isGoalState(currentState)): return currentPath else: for (successor, cost, action) in problem.getSuccessors(currentState): fringe.push(currentPath + [(successor, cost, action)]) visited.add(currentState) def getListOfActions(path): actions = [] for (state, action, cost) in path: if action is not "": actions.append(action) return actions def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" fringe = util.Stack() path = graphSearch(problem, fringe) return getListOfActions(path) def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" fringe = util.Queue() path = graphSearch(problem, fringe) return getListOfActions(path) def nullHeuristic(state, problem=None): """ A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. """ return 0 class SearchState: def __init__(self, coordinates, plan, accumulative_cost): self.coordinates = coordinates self.plan = plan self.accumulative_cost = accumulative_cost def add(self, coordinates, action, cost): return SearchState(coordinates, self.plan + [action], self.accumulative_cost + cost) def prioritySearch(problem, heuristic=nullHeuristic): state = problem.getStartState() fringe = util.PriorityQueue() plan = [] visited = set() currentState = SearchState(problem.getStartState(), [], 0) fringe.push(currentState, currentState.accumulative_cost) while(True): currentState = fringe.pop() if currentState.coordinates in visited: continue if(problem.isGoalState(currentState.coordinates)): return currentState.plan else: for (successor, action, cost) in problem.getSuccessors(currentState.coordinates): newState = currentState.add(successor, action, cost) fringe.push(newState, newState.accumulative_cost + heuristic(newState.coordinates, problem)) visited.add(currentState.coordinates) def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" return prioritySearch(problem) def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" return prioritySearch(problem, heuristic) # Abbreviations bfs = breadthFirstSearch dfs = depthFirstSearch astar = aStarSearch ucs = uniformCostSearch
<canvas id="canvas" style="margin: -8px"></canvas> <script type="text/javascript"> const BLOCK = 20; const MARGIN = 1; const FREQUENCY = 10; let interval; let status = { pause: false }; let snake = []; let apple = {}; let direction = {x: 1, y: 0}; window.onload = function() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; snake = [ { x: Math.floor(canvas.width / BLOCK / 2 - 1) * BLOCK, y: Math.floor(canvas.height / BLOCK / 2) * BLOCK }, { x: Math.floor(canvas.width / BLOCK / 2) * BLOCK, y: Math.floor(canvas.height / BLOCK / 2) * BLOCK } ]; apple = getRandomPosition(); document.addEventListener("keydown", keyDown); interval = setInterval(game, 1000 / FREQUENCY); } function game() { ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "lime"; // draw snake body for (var i = snake.length - 2; i >= 1; i--) { ctx.fillRect(snake[i].x + MARGIN, snake[i].y + MARGIN, BLOCK - MARGIN * 2, BLOCK - MARGIN * 2); } // draw snake tail ctx.beginPath(); ctx.moveTo((snake[0].x * (BLOCK * 3 / 2 - MARGIN) - snake[1].x * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2, (snake[0].y * (BLOCK * 3 / 2 - MARGIN) - snake[1].y * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2); ctx.lineTo((snake[0].x * (BLOCK / 2 + MARGIN) + snake[1].x * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2 + (snake[0].y - snake[1].y) * (BLOCK / 2 - MARGIN) / BLOCK, (snake[0].y * (BLOCK / 2 + MARGIN) + snake[1].y * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2 + (snake[0].x - snake[1].x) * (BLOCK / 2 - MARGIN) / BLOCK); ctx.lineTo((snake[0].x * (BLOCK / 2 + MARGIN) + snake[1].x * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2 - (snake[0].y - snake[1].y) * (BLOCK / 2 - MARGIN) / BLOCK, (snake[0].y * (BLOCK / 2 + MARGIN) + snake[1].y * (BLOCK / 2 - MARGIN)) / BLOCK + BLOCK / 2 - (snake[0].x - snake[1].x) * (BLOCK / 2 - MARGIN) / BLOCK); ctx.fill(); // draw snake head if (direction.x == 1) { ctx.fillRect(snake[snake.length - 1].x + MARGIN, snake[snake.length - 1].y + MARGIN, BLOCK / 2 - MARGIN, BLOCK - MARGIN * 2); ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 2, BLOCK / 2 - MARGIN, Math.PI / 2, Math.PI * 3 / 2, true); ctx.closePath(); ctx.fill(); } if (direction.x == -1) { ctx.fillRect(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + MARGIN, BLOCK / 2 - MARGIN, BLOCK - MARGIN * 2); ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 2, BLOCK / 2 - MARGIN, Math.PI / 2, Math.PI * 3 / 2, false); ctx.closePath(); ctx.fill(); } if (direction.y == 1) { ctx.fillRect(snake[snake.length - 1].x + MARGIN, snake[snake.length - 1].y + MARGIN, BLOCK - MARGIN * 2, BLOCK / 2 - MARGIN); ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 2, BLOCK / 2 - MARGIN, Math.PI, 0, true); ctx.closePath(); ctx.fill(); } if (direction.y == -1) { ctx.fillRect(snake[snake.length - 1].x + MARGIN, snake[snake.length - 1].y + BLOCK / 2, BLOCK - MARGIN * 2, BLOCK / 2 - MARGIN); ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 2, BLOCK / 2 - MARGIN, Math.PI, 0, false); ctx.closePath(); ctx.fill(); } // draw eyes if (direction.y == 0) { ctx.fillStyle = "white"; ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 4, BLOCK / 4 - MARGIN / 2, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); ctx.fillStyle = "black"; ctx.beginPath() ctx.arc(snake[snake.length - 1].x + BLOCK / 2, snake[snake.length - 1].y + BLOCK / 4, BLOCK / 8 - MARGIN / 4, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } // if (direction.x == 0) { // ctx.fillStyle = "white"; // ctx.ellipse(snake[snake.length - 1].x + BLOCK / 8 + MARGIN, snake[snake.length - 1].y + BLOCK / 2, BLOCK / 8, BLOCK / 4, 0, 0, Math.PI * 2); // ctx.fill(); // } // draw apple ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(apple.x + BLOCK / 2, apple.y + BLOCK / 2, BLOCK / 2 - MARGIN, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); let head = { x: snake[snake.length - 1].x, y: snake[snake.length - 1].y }; head.x += direction.x * BLOCK; head.y += direction.y * BLOCK; for (let i = snake.length - 1; i >= 0; i--) { if (snake[i].x == head.x && snake[i].y == head.y || head.x < 0 || head.x > canvas.width || head.y < 0 || head.y > canvas.height) { window.location.reload(); } } snake.push(head); let tail = snake.shift(); if (snake[snake.length - 1].x == apple.x && snake[snake.length - 1].y == apple.y) { snake.splice(0, 0, tail); let badApple = true; while (badApple) { apple = getRandomPosition(); for (var i = snake.length - 1; i >= 0; i--) { if (snake[i].x != apple.x || snake[i].y != apple.y) { badApple = false; } } } } } function keyDown(e) { switch (e.keyCode) { case 32: if (status.pause) { interval = setInterval(game, 1000 / FREQUENCY); } else { clearInterval(interval); } status.pause = !status.pause; break; case 37: if (direction.x == 0) { direction.x = -1; direction.y = 0; } break; case 38: if (direction.y == 0) { direction.x = 0; direction.y = -1; } break; case 39: if (direction.x == 0) { direction.x = 1; direction.y = 0; } break; case 40: if (direction.y == 0) { direction.x = 0; direction.y = 1; } break; } } function getRandomPosition() { return { x: Math.floor(Math.random() * Math.floor(canvas.width / 20)) * 20, y: Math.floor(Math.random() * Math.floor(canvas.height / 20)) * 20 }; } </script>
import React from 'react'; import styled from "styled-components"; import Rating from "@material-ui/lab/Rating"; import { useStateValue } from '../../StateProvider'; function Card({id,image,title,price,rating}) { const [{basket},dispatch]= useStateValue(); console.log('basket',basket); const addToBasket = (e)=>{ e.preventDefault(); dispatch({ type: "ADD_TO_BASKET", item:{ title,price,image,rating }, }); }; return ( <Container> <Image> <img src={image} alt='img'/> </Image> <Description> <h3>{title}</h3> <Rating name='half-rating-read' defaultValue={rating} precision={0.5} readOnly/> <p>₹ {price}</p> <button onClick={addToBasket}>Add to Cart</button> </Description> </Container> ); } const Container=styled.div` width:100%; height:100%; display:flex; flex-direction:column; background-color:#fff; z-index:10; `; const Image=styled.div` width:100%; display:flex; flex-direction:column; justify-content:center; align-items:center; margin-top:20px; flex:0.3; img{ width:180px; height:180px; } `; const Description=styled.div` width:90%; margin:auto; display:flex; flex-direction:column; justify-content:space-evenly;flex:0.7; h3{ font-size:16px; font-weight:600; } p{ font-weight:600; } button{ width:100%; height:33px; background-color:#fa8900; border:none; border-radius:10px; cursor:pointer; } `; export default Card;
import GetIfAuthenticationTokenIsValid from "../../../context/user-account/application/GetIfAuthenticationTokenIsValid" import AuthenticationToken from "../../../context/user-account/domain/entity/AuthenticationToken" import User from "../../../context/user-account/domain/entity/User" import AuthenticationTokenRepository from "../../../context/user-account/domain/repository/AuthenticationTokenRepository" class MockAuthenticationTokenRepository implements AuthenticationTokenRepository { async registerAuthenticationToken(authenticationToken: AuthenticationToken): Promise<void> { throw new Error("Method not implemented.") } async getByToken(authenticationToken: string): Promise<AuthenticationToken> { let threeHoursAgo = new Date() threeHoursAgo.setTime(threeHoursAgo.getTime() + (-3 * 60 * 60 * 1000)) if (authenticationToken == "valid-token") { // Will expire after 4 hours, so OK return new AuthenticationToken("valid-token", new User("user-id", "user-username", "user-encripted-pass"), threeHoursAgo, 4) } else if (authenticationToken == "invalid-token") { // Will expire after 1 hour, so NOT OK return new AuthenticationToken("invalid-token", new User("user-id", "user-username", "user-encripted-pass"), threeHoursAgo, 1) } throw new Error("Authentication token not found: " + authenticationToken) } } let authenticationTokenRepository: AuthenticationTokenRepository let getIfAuthenticationTokenIsValid: GetIfAuthenticationTokenIsValid beforeAll(() => { authenticationTokenRepository = new MockAuthenticationTokenRepository() getIfAuthenticationTokenIsValid = new GetIfAuthenticationTokenIsValid(authenticationTokenRepository) }) describe("GetIfAuthenticationTokenIsValid", () => { it("should authenticate a valid token", async () => { const token = "valid-token" const tokenIsValid = await getIfAuthenticationTokenIsValid.execute(token) expect(tokenIsValid).toEqual(true) }) it("should NOT authenticate an invalid token", async () => { const token = "invalid-token" const tokenIsValid = await getIfAuthenticationTokenIsValid.execute(token) expect(tokenIsValid).toEqual(false) }) })
import cls from './PostList.module.css'; import { PostItem } from '../PostItem/PostItem'; import { TransitionGroup, CSSTransition } from 'react-transition-group'; export const PostList = (props) => { const {posts, remove, title} = props if(!posts.length) { return <h1 style={{textAlign: 'center'}}>Посты не найдены</h1> } return ( <div className={cls.PostList}> <h1 style={{textAlign: 'center'}}>{title}</h1> <TransitionGroup> {posts.map((post, index) => <CSSTransition key={post.id} timeout={500} classNames="post" > <PostItem number={index + 1} post={post} remove={remove}/> </CSSTransition>)} </TransitionGroup> </div> ); };
# Build a very basic Pokémon class that allows you to simulate battles # in a Rock-Paper-Scissors game mechanic, as well as feed your Pokémon. # # The class should follow these specifications: # # - Each Pokemon should have a `name`, `primary_type`, `max_hp` and `hp` # - Primary types should be limited to `water`, `fire` and `grass` # - Implement a `battle()` method based on rock-paper-scissors that # decides who wins based only on the `primary_type`: # water > fire > grass > water # - Display messages that explain who won or lost a battle # - If a Pokemon loses a battle, they lose some of their `hp` # - If you call the `feed()` method on a Pokemon, they regain some `hp` horizontal_line = "________________________" class Pokemon: def __init__(self, name, primary_type, max_hp, hp) -> None: self.name = name possible_primary_types = ["water", "fire", "grass"] while primary_type not in possible_primary_types: print(f"The 'primary_type' of the pokemon {self.name} can only be 'water', 'fire' or 'grass.") primary_type = input(f"What is the primary type of the pokemon: ") self.primary_type = primary_type self.max_hp = max_hp self.hp = hp def __str__(self) -> str: return f"{self.name} ({self.primary_type}) | healthpoints: {self.hp}" def feed(self, food, amount): if food.amount >= amount: if self.hp + food.hp_increase * amount < self.max_hp: self.hp += food.hp_increase * amount food.amount -= amount else: print(f'Watch out, {self.name} can only have {self.max_hp} liefpoints. This meands {(self.hp + food.hp_increase * amount) - self.max_hp} healthpoints would be lost.') user_input = input('Type in "feed anyway", if you want to still proceed:') if user_input == "feed anyway": self.hp += food.hp_increase * amount food.amount -= amount else: print("Ok, nothing has been fed.") else: print(f"You dont have enough {food.name} in your pocket") def battle_pokemon(self, other_pokemon): outcome = self.check_winner(self.primary_type, other_pokemon.primary_type) # Substract hp in case of loss if outcome == "win": other_pokemon.hp -= 10 print(f"{self.name} won the battle \n{other_pokemon.name} got defeated and has only {other_pokemon.hp} healthpoints left.") elif outcome == "loose": self.hp -= 10 print(f"{other_pokemon.name} won the battle \n{self.name} got defeated and has only {self.hp} healthpoints left.") else: print(f"{self.name} and {other_pokemon.name} fought each other, but no one was winnig – they tied and lost no healthpoints.") @staticmethod def check_winner(type1, type2): result = {0: "loose", 1: "win", -1: "tie"} game_map = {"water": 0, "fire": 1, "grass":2} win_loose_matrix = [ [-1, 1, 0], # water [0, -1, 1], # fire [1, 0, -1] # grass ] return result[win_loose_matrix[game_map[type1]][game_map[type2]]] class Food: def __init__(self, name, amount, hp_increase) -> None: self.name = name self.amount = amount self.hp_increase = hp_increase def add_food_item(self, amount): self.amount += amount class User: def __init__(self, pokemons: list, foods: list) -> None: self.pokenmons = pokemons self.foods = foods
import { View, Text, FlatList, Alert } from 'react-native' import React, { useState } from 'react' import { styles } from './styles' import Input from '../Input' import Button from '../Button' import { MaterialIcons } from '@expo/vector-icons'; import { Feather } from '@expo/vector-icons'; import { theme } from '../../styles/theme' import Task, { TaskType } from '../Task' export default function TodoList() { const [tasks, setTasks] = useState<TaskType[]>([]); const [newTask, setNewTask] = useState('') const handleAddTask = (text: string) => { setNewTask('') if (tasks.some(task => task.text === text)) { return Alert.alert("Task already exists.", "You can't create duplicated tasks."); } setTasks(prev => [...prev, { text, isCompleted: false }]) } const handleDeleteTask = (text: string) => { Alert.alert("Remove task", `Are you sure you want to remove "${text}" from the list?`, [ { text: "Cancel", style: "cancel" }, { text: "Remove", onPress: () => setTasks(prev => prev.filter(task => task.text !== text)), style: "destructive" } ]); } const handleCompleteTask = (newValue: boolean, text: string) => { setTasks(prev => prev.map(task => { if (task.text === text) { return { ...task, isCompleted: newValue } } return task; })) } const completedTasks = tasks.filter(task => task.isCompleted).length ?? 0; return ( <View style={styles.container}> <View style={styles.inputContainer}> <Input value={newTask} onChange={setNewTask} placeholder='Add a new task' /> <Button onPress={() => handleAddTask(newTask)}> <MaterialIcons name="add-circle-outline" size={24} color={theme.colors.gray100} /> </Button> </View> <View style={[styles.statusContainer, tasks.length === 0 && { borderBottomColor: theme.colors.gray400 }]}> <View style={styles.status}> <Text style={[styles.statusText, { color: theme.colors.blue }]}>Created</Text> <View style={styles.statusNumberContainer}> <Text style={styles.statusNumber}>{tasks.length}</Text> </View> </View> <View style={styles.status}> <Text style={[styles.statusText, { color: theme.colors.purple }]}>Finished</Text> <View style={styles.statusNumberContainer}> <Text style={styles.statusNumber}>{completedTasks}</Text> </View> </View> </View> <FlatList data={tasks} keyExtractor={(item) => item.text} renderItem={({ item }) => ( <Task task={item} handleComplete={handleCompleteTask} handleDelete={handleDeleteTask} /> )} ListEmptyComponent={() => <View style={styles.emptyStateContainer}> <Feather name="clipboard" size={56} color={theme.colors.gray300} /> <View> <Text style={[styles.emptyStateText, { fontFamily: theme.typography.boldText }]}> You don't have any tasks. </Text> <Text style={[styles.emptyStateText, { fontFamily: theme.typography.regularText }]}> Create your tasks and get organized. </Text> </View> </View> } showsVerticalScrollIndicator={false} /> </View> ) }
import React from "react"; import "css/Display.scss" let stateNames = ["Система остановлена", "Запуск калорифера", "Запуск вентилятора", "Система заблокированна", "Система в работе", "Продув электрокалорифера", "Останов вентилятора"]; class Display extends React.Component { constructor(props) { super(props); } render() { let dataToDisplay = { state: (this.props.stats.state === null ? "Не определено" : stateNames[this.props.stats.state]), targetTemperature: (this.props.stats.targetTemperature === null ? "Не определено" : this.props.stats.targetTemperature.toFixed(2) + " °С"), airTemperature: (this.props.stats.airTemperature === null ? "Не определено" : this.props.stats.airTemperature.toFixed(2) + " °С"), heaterCapacity: (this.props.stats.heaterCapacity === null ? "Не определено" : this.props.stats.heaterCapacity.toFixed(2) + " Вт"), failures: { heater: (this.props.stats.failures.heater === null ? "Не определено" : (this.props.stats.failures.heater ? "Неисправность" : "В норме")), fan: (this.props.stats.failures.fan === null ? "Не определено" : (this.props.stats.failures.fan ? "Неисправность" : "В норме")), frequencyConverter: (this.props.stats.failures.frequencyConverter === null ? "Не определено" : (this.props.stats.failures.frequencyConverter ? "Неисправность" : "В норме")) } }; return (<div className="display"> <div className="title">Состояние системы</div> <div>Статус: <span>{dataToDisplay.state}</span></div> <div>Уставка: <span>{dataToDisplay.targetTemperature}</span></div> <div>Температура притока: <span>{dataToDisplay.airTemperature}</span></div> <div>Мощность калорифера: <span>{dataToDisplay.heaterCapacity}</span></div> <div>Калорифер: <span>{dataToDisplay.failures.heater}</span></div> <div>Вентилятор: <span>{dataToDisplay.failures.fan}</span></div> <div>Частотник: <span>{dataToDisplay.failures.frequencyConverter}</span></div> </div>); } } export default Display;
#include <stdio.h> #include <stdarg.h> #include "variadic_functions.h" /** * print_numbers - function that prints numbers, followed by a new line * @separator: the string to be printed between numbers * @n: is the number of integers passed to the function * * Return: 0 */ void print_numbers(const char *separator, const unsigned int n, ...) { unsigned int i; va_list args; va_start(args, n); for (i = 0; i < n; i++) { printf("%d", va_arg(args, int)); if (separator != NULL && i < n - 1) { printf("%s", separator); } } printf("\n"); va_end(args); }
import * as express from "express"; import crypto from "crypto"; function base64decode(data: string) { while (data.length % 4 !== 0) { data += "="; } data = data.replace(/-/g, "+").replace(/_/g, "/"); return Buffer.from(data, "base64").toString("utf-8"); } export const deleteDataController = async ( req: express.Request, res: express.Response ) => { const { signed_request } = req.body; const secret = process.env.FACEBOOK_APP_SECRET; try { const encodedData = signed_request.split(".", 2); // decode the data const sig = encodedData[0]; const json = base64decode(encodedData[1]); const data = JSON.parse(json); if (secret === undefined) { throw Error("FB app secret is missing"); } if (!data.algorithm || data.algorithm.toUpperCase() != "HMAC-SHA256") { secret; throw Error( "Unknown algorithm: " + data.algorithm + ". Expected HMAC-SHA256" ); } const expected_sig = crypto .createHmac("sha256", secret) .update(encodedData[1]) .digest("base64") .replace(/\+/g, "-") .replace(/\//g, "_") .replace("=", ""); if (sig !== expected_sig) { throw Error("Invalid signature: " + sig + ". Expected " + expected_sig); } const url = `https://musicserver.izmus.cz/delete-data/check?id=${data.user_id}`; const confirmationCode = data.user_id; console.log(`{ url: '${url}', confirmation_code: '${confirmationCode}' }`); res.send(`{ url: '${url}', confirmation_code: '${confirmationCode}' }`); } catch (err) { res.status(400).json({ error: "Something went wrong..." }); } };
import React, { useEffect, useState } from "react"; import { animated, useSpring } from "@react-spring/web"; import { flexRender } from "@tanstack/react-table"; import DeleteButton from "@components/table/buttons/DeleteButton"; import { RowProps } from "@components/table/Table.types"; const Row: <T>(props: RowProps<T>) => React.ReactElement = ({ rowData, meta }) => { const [isHovering, setIsHovering] = useState(false); const styles = useSpring({ opacity: isHovering ? 1 : 0, x: isHovering ? 0 : 5, config: { duration: 300, }, }); const elemId = `tr_${rowData.id}`; useEffect(() => { const handleMouseMove = (e: MouseEvent) => { const container = document.getElementById(elemId); const rect = container?.getBoundingClientRect(); if (rect) { const isInside = e.clientY >= rect.top + 10 && e.clientY <= rect.bottom - 10 && e.clientX >= rect.left - 60 && e.clientX <= rect.right + 60; setIsHovering(isInside); } }; document.addEventListener("mousemove", handleMouseMove); return () => { document.removeEventListener("mousemove", handleMouseMove); }; }, [elemId]); return ( <div key={rowData.id} className="tr" id={elemId}> <animated.span style={styles} className="row-option delete"> <DeleteButton onClick={() => meta?.removeRow(rowData.index)} /> </animated.span> {rowData.getVisibleCells().map((cell) => ( <div key={cell.id} className="td" style={{ width: `calc(var(--col-${cell.column.id}-size) * 1px)`, }} > {flexRender(cell.column.columnDef.cell, cell.getContext())} </div> ))} </div> ); }; export default Row;
package com.leyou.order.service; import com.leyou.auth.entity.UserInfo; import com.leyou.common.dto.CartDTO; import com.leyou.common.enums.ExceptionEnum; import com.leyou.common.exception.LyException; import com.leyou.common.utils.IdWorker; import com.leyou.item.pojo.Sku; import com.leyou.order.client.AddressClient; import com.leyou.order.client.GoodsClient; import com.leyou.order.dto.AddressDTO; import com.leyou.order.dto.OrderDTO; import com.leyou.order.enums.OrderStatusEnum; import com.leyou.order.enums.PayState; import com.leyou.order.interceptor.UserInterceptor; import com.leyou.order.mapper.OrderDetailMapper; import com.leyou.order.mapper.OrderMapper; import com.leyou.order.mapper.OrderStatusMapper; import com.leyou.order.pojo.Order; import com.leyou.order.pojo.OrderDetail; import com.leyou.order.pojo.OrderStatus; import com.leyou.order.utils.PayHelper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.*; import java.util.stream.Collectors; /** * @description: * @data: 2020/5/24 16:57 * @author: xiaoNan */ @Slf4j @Service public class OrderService { @Autowired private OrderMapper orderMapper; @Autowired private OrderDetailMapper orderDetailMapper; @Autowired private OrderStatusMapper orderStatusMapper; @Autowired private IdWorker idWorker; @Autowired private GoodsClient goodsClient; @Autowired private PayHelper payHelper; @Transactional public Long createOrder(OrderDTO orderDTO) { // 1 新增订单 Order order = new Order(); // 1.1 订单编号,基本信息 long orderId = idWorker.nextId(); order.setOrderId(orderId); order.setCreateTime(new Date()); order.setPaymentType(orderDTO.getPaymentType()); // 1.2 用户信息 UserInfo user = UserInterceptor.getUser(); order.setUserId(user.getId()); order.setBuyerNick(user.getUsername()); order.setBuyerRate(false); // 1.3 收货人地址 // 获取收货人信息 AddressDTO address = AddressClient.findById(orderDTO.getAddressId()); order.setReceiver(address.getName()); order.setReceiverAddress(address.getAddress()); order.setReceiverCity(address.getCity()); order.setReceiverDistrict(address.getDistrict()); order.setReceiverMobile(address.getPhone()); order.setReceiverState(address.getState()); order.setReceiverZip(address.getZip()); // 1.4 金额 // 把CartDTO转为一个map,key是sku的id,值是 num Map<Long, Integer> numMap = orderDTO.getCarts().stream() .collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum)); Set<Long> cartIds = numMap.keySet(); List<Sku> skus = goodsClient.querySkusBySkuIds(new ArrayList<>(cartIds)); // 准备orderDetail集合 List<OrderDetail> details = new ArrayList<>(); long totalPay = 0L; for (Sku sku: skus) { // 计算商品总价 totalPay += sku.getPrice() * numMap.get(sku.getId()); // 封装orderDetail OrderDetail detail = new OrderDetail(); detail.setImage(StringUtils.substringBefore(sku.getImages(), ",")); detail.setNum(numMap.get(sku.getId())); detail.setOrderId(orderId); detail.setOwnSpec(sku.getOwnSpec()); detail.setPrice(sku.getPrice()); detail.setSkuId(sku.getId()); detail.setTitle(sku.getTitle()); details.add(detail); } order.setTotalPay(totalPay); // 实付金额:总金额 + 邮费 - 优惠金额 order.setActualPay(totalPay + order.getPostFee() - 0); // 1.5 order写入数据库 if(orderMapper.insertSelective(order) != 1) { log.error("【创建订单】创建订单失败,orderId:{}", orderId); throw new LyException(ExceptionEnum.CREATE_ORDER_ERROR); } // 2 新增订单详情 if (orderDetailMapper.insertList(details) != details.size()) { log.error("【创建订单详情】创建订单详情失败,order:{}", orderId); throw new LyException(ExceptionEnum.CREATE_DETAIL_ORDER_ERROR); } // 3 新增订单状态 OrderStatus orderStatus = new OrderStatus(); orderStatus.setCreateTime(new Date()); orderStatus.setOrderId(orderId); orderStatus.setStatus(OrderStatusEnum.UN_PAY.value()); if (orderStatusMapper.insertSelective(orderStatus) != 1) { log.error("【创建订单】订单创建失败,orderId:{}", orderId); throw new LyException(ExceptionEnum.CREATE_ORDER_ERROR); } // 4 减库存 // 同步机制:远程调用,取巧,放到最后,如果放在其他位置,出现异常,两个事务会不一致 // 异步机制:rabbitmq消息队列,但是需要解决分布式事务问题 List<CartDTO> cartDTOS = orderDTO.getCarts(); goodsClient.decreaseStock(cartDTOS); return orderId; } public Order queryOrderById(Long id) { // 查询订单 Order order = orderMapper.selectByPrimaryKey(id); if (order == null) { // 不存在 throw new LyException(ExceptionEnum.ORDER_NOT_FOUND); } // 查询订单详情 OrderDetail detail = new OrderDetail(); detail.setOrderId(id); List<OrderDetail> details = orderDetailMapper.select(detail); if (CollectionUtils.isEmpty(details)) { throw new LyException(ExceptionEnum.ORDER_DETAIL_NOT_FOUND); } order.setOrderDetails(details); // 查询订单状态 OrderStatus orderStatus = orderStatusMapper.selectByPrimaryKey(id); if (orderStatus == null) { throw new LyException(ExceptionEnum.ORDER_STATUS_NOT_FOUND); } order.setOrderStatus(orderStatus); return order; } public String createPayUrl(Long orderId) { // 查询订单 Order order = queryOrderById(orderId); // 判断订单状态 Integer status = order.getOrderStatus().getStatus(); if (status != OrderStatusEnum.UN_PAY.value()) { throw new LyException(ExceptionEnum.ORDER_STATUS_ERROR); } // 支付金额 // Long actualPay = order.getActualPay(); // 测试用 Long actualPay = 1L; // 商品描述 OrderDetail detail = order.getOrderDetails().get(0); String desc = detail.getTitle(); return payHelper.createOrder(orderId, actualPay, desc); } public void handleNotify(Map<String, String> result) { // 1. 数据校验 payHelper.isSuccess(result); // 2. 验证签名 payHelper.isValidSign(result); // 3. 校验金额 String totalFeeStr = result.get("total_fee"); String tradeNo = result.get("out_trade_no"); if (StringUtils.isEmpty(totalFeeStr) || StringUtils.isEmpty(tradeNo)) { throw new LyException(ExceptionEnum.INVALID_ORDER_PARAM); } // 3.1 获取结果中的金额 long totalFee = Long.valueOf(totalFeeStr); // 3.2 获取订单金额 Long orderId = Long.valueOf(tradeNo); Order order = orderMapper.selectByPrimaryKey(orderId); if (totalFee != /*order.getActualPay()*/ 1) { // 金额不符合 throw new LyException(ExceptionEnum.INVALID_ORDER_PARAM); } // 4. 修改订单状态 OrderStatus orderStatus = new OrderStatus(); orderStatus.setStatus(OrderStatusEnum.PAYED.value()); orderStatus.setOrderId(orderId); orderStatus.setPaymentTime(new Date()); if (orderStatusMapper.updateByPrimaryKeySelective(orderStatus) != 1) { throw new LyException(ExceptionEnum.UPDATE_ORDER_STATUS_ERROR); } log.info("【订单回调】订单支付成功!订单编号:{}", orderId); } public PayState queryOrderState(Long orderId) { // 查询订单状态 OrderStatus orderStatus = orderStatusMapper.selectByPrimaryKey(orderId); Integer status = orderStatus.getStatus(); // 判断是否支付 if (status != OrderStatusEnum.UN_PAY.value()) { // 如果是已支付,真的是已支付 return PayState.SUCCESS; } // 如果未支付,但其实不一定是未支付,必须去微信查询支付状态 return payHelper.queryPayState(orderId); } }
#!/usr/bin/env python from tornado.options import define as opt opt("config", default=None, help= "Config file name to load") opt("daemon", default=False, type=bool, help= "Run as daemon") opt("host", default="", help= "Listen to the specified host") opt("port", default=11002, type=int, help= "Run on the given port") opt("db_name", default="blafio", help= "DB Name") opt("db_host", default=None, help= "DB server address") opt("db_port", default=None, type=int, help= "DB server port") opt("db_usr", default=None, help= "DB username") opt("db_pwd", default=None, help= "DB password") if __name__ == "__main__": import sys from tornado.options import options ignored_options = ['help', 'config'] outf = sys.stdout by_file = {} for option in options.itervalues(): by_file.setdefault(option.file_name, []).append(option) print >> outf, """\ # All the rules for this config file are the same with the command line options. # The options available could be found out by passing `--help` to the main.py """ print >> outf, "#- buit-in options -\n" for filename, o in sorted(by_file.items()): if filename: print >> outf, "\n#- " + filename + " -\n" o.sort(key=lambda option: option.name) for option in o: if option.name in ignored_options: continue prefix = option.name suffix = "" if option.metavar: suffix = " # " + option.metavar if option.value() is None: print >> outf, "%s = None %s" % (prefix, suffix) elif option.type in [str, unicode]: #TODO: escape unicode print >> outf, "%s = \"%s\" %s" % (prefix, option.value() or "", suffix) elif option.type == bool: print >> outf, "%s = %s %s" % (prefix, "True" if option.value() else "False", suffix) else: print >> outf, "%s = %s %s" % (prefix, option.value() or "", suffix) print >> outf, "\n"
import React from 'react'; import {NavLink} from "react-router-dom"; import ava_user from "../../assets/img/ava_person.svg.png"; import styles from "./Users.module.css"; import {usersType} from "../../redux/users-reducer"; type UserPropsType = { users: Array<usersType> followingInProgress: Array<number> unfollow: (id: number) => void follow: (id: number) => void } const User = (props: UserPropsType) => { return ( <> { props.users.map(user => <div key={user.id}> <span> <div> <NavLink to={'/profile/' + user.id}> <img src={user.photos.small != null ? user.photos.small : ava_user} className={styles.userPhoto} alt={'ava user'}/> </NavLink> </div> <div> {user.followed ? <button disabled={props.followingInProgress.some(id=> id === user.id)} onClick={() => {props.unfollow(user.id)}}>Unfollow</button> : <button disabled={props.followingInProgress.some(id=> id === user.id)} onClick={() => {props.follow(user.id)}}>Follow</button>} </div> </span> <span> <span> <div>{user.name}</div> <div>{user.status}</div> </span> <span> <div>{"user.location.country"}</div><div>{"user.location.city"}</div> </span> </span> </div>) } </> ); }; export {User};
import React, { useState } from 'react'; import classNames from 'classnames'; import { SectionProps } from '../../utils/SectionProps'; import ButtonGroup from '../elements/ButtonGroup'; import Button from '../elements/Button'; import Image from '../elements/Image'; import Modal from '../elements/Modal'; import HeroImg from './../../assets/images/thumbnail.png' const propTypes = { ...SectionProps.types } const defaultProps = { ...SectionProps.defaults } const Hero = ({ className, topOuterDivider, bottomOuterDivider, topDivider, bottomDivider, hasBgColor, invertColor, ...props }) => { // import('../assets/scss/style.scss'); const [videoModalActive, setVideomodalactive] = useState(false); const openModal = (e) => { e.preventDefault(); setVideomodalactive(true); } const closeModal = (e) => { e.preventDefault(); setVideomodalactive(false); } const outerClasses = classNames( 'hero section center-content', topOuterDivider && 'has-top-divider', bottomOuterDivider && 'has-bottom-divider', hasBgColor && 'has-bg-color', invertColor && 'invert-color', className ); const innerClasses = classNames( 'hero-inner section-inner', topDivider && 'has-top-divider', bottomDivider && 'has-bottom-divider' ); return ( <section {...props} className={outerClasses} > <div className="container-sm"> <div className={innerClasses}> <div className="hero-content"> <h1 className="mt-0 mb-16 reveal-from-bottom" data-reveal-delay="200"> HAVA <span className="text-color-primary">Router?</span> </h1> <div className="container-xs"> <p className="m-0 mb-32 reveal-from-bottom" data-reveal-delay="400"> A decentralized and open internet for everyone. </p> <div className="reveal-from-bottom" data-reveal-delay="600"> <ButtonGroup> <Button tag="a" color="primary" wideMobile href="#swap"> Swap now </Button> </ButtonGroup> </div> </div> </div> <div className="hero-figure reveal-from-bottom illustration-element-01" data-reveal-value="20px" data-reveal-delay="800"> <a data-video="https://www.youtube.com/embed/nw9KwqRjy-c" href="#0" aria-controls="video-modal" onClick={openModal} > <Image className="has-shadow" src={HeroImg} alt="Hero" width={896} height={504} /> </a> </div> <Modal id="video-modal" show={videoModalActive} handleClose={closeModal} video="https://www.youtube.com/embed/nw9KwqRjy-c" videoTag="iframe" /> </div> </div> </section> ); } Hero.propTypes = propTypes; Hero.defaultProps = defaultProps; export default Hero;
const helpers = require("../config/helpers"); const visitorService = require("../services/visitorService"); const getAllVisitors = async (req, res, next) => { try { const response = await visitorService.getAllVisitors(); return res .status(200) .json( helpers.sendSuccess("all visitors successfully retrived!!!", response) ); } catch (error) { if (error.status) { return res .status(error.status) .json(helpers.sendError("couldn't get all visitors!!!", error.status)); } return res.status(500).json(helpers.sendError(error.message, 500)); } }; const getSingleVisitor = async (req, res) => { try { const response = await visitorService.getSingleVisitor(req); return res .status(200) .json( helpers.sendSuccess("visitor successfully retrived!!!", response) ); } catch (error) { if (error.status) { return res .status(error.status) .json(helpers.sendError("couldn't get visitor!!!", error.status)); } return res.status(500).json(helpers.sendError(error.message, 500)); } } const addVisitor = async (req, res) => { try { const response = await visitorService.addVisitor(req); return res .status(200) .json(helpers.sendSuccess("visitor successfully added!!!", response)); } catch (error) { if (error.status) { return res .status(error.status) .json(helpers.sendError(error.message, error.status)); } return res.status(500).json(helpers.sendError(error.message, 500)); } }; const getSingleVisitorQRCode = async (req, res) => { console.log(req.params.id); try { const response = await visitorService.getSingleVisitorQRCode(req); return res .status(200) .json( helpers.sendSuccess( "Visitor's QRCode successfully generated!!!", response ) ); } catch (error) { if (error.status) { return res .status(error.status) .json(helpers.sendError(error.message, error.status)); } return res.status(500).json(helpers.sendError(error.message, 500)); } }; module.exports = { getAllVisitors, getSingleVisitor, getSingleVisitorQRCode, addVisitor };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <app-menu></app-menu> <form #form="ngForm"> <h1>Ajouter Un nouveau Genre</h1> <hr> <div class="form-group"> <label class="col-form-label col-form-label" for="inputLarge">Identifiant:</label> <input class="form-control form-control-lg" type="text" placeholder="Tapez votre commentaire ..." id="inputLarge" name="id" [(ngModel)]="commentaire.id" #id="ngModel" required> <div *ngIf="id.invalid && id.touched"> Ce champ est obligatoire </div> </div> <div class="form-group"> <label class="col-form-label col-form-label" for="inputLarge">Message:</label> <input class="form-control form-control-lg" type="text" placeholder="Tapez votre commentaire ..." id="inputLarge" name="message" [(ngModel)]="commentaire.message" #message="ngModel" required> <div *ngIf="message.invalid && message.touched"> Ce champ est obligatoire </div> </div> <div class="form-group"> <label class="col-form-label col-form-label" for="inputLarge">Evaluation:</label> <ng5-slider [(value)]="value" [options]="options" name="evaluation" [(ngModel)]="commentaire.evaluation" #evaluation="ngModel"></ng5-slider> <div *ngIf="evaluation.invalid && evaluation.touched"> Ce champ est obligatoire </div> </div> <label class="col-form-label col-form-label" for="inputLarge">Type du Jeu:</label> <select id="jeux_id" name="jeux_id" [(ngModel)]="commentaire.jeux_id" #jeux_id="ngModel" class="form-control"> <option value="" disabled>Sélectionnez votre Jeu</option> <option *ngFor="let item of listJeux" [value]="item.nom"> {{item.nom}} </option> </select> <button (click)="update()" type="submit" class="btn btn-outline-info btn-lg btn-block">Mettre à jour</button> </form> </body> </html>
import { h, Host } from '@stencil/core'; export class BalDocDownload { constructor() { this.link = ''; this.iconLeft = 'document'; this.iconRight = 'download'; this.subject = ''; this.subtitle = ''; } render() { return (h(Host, { class: "bal-app" }, h("a", { href: this.link, style: { textDecoration: 'none' } }, h("bal-card", null, h("bal-card-content", null, h("bal-list", { disabled: true }, h("bal-list-item", null, h("bal-list-item-icon", null, h("bal-icon", { name: this.iconLeft })), h("bal-list-item-content", null, h("bal-list-item-title", null, this.subject), h("bal-list-item-subtitle", null, this.subtitle)), h("bal-list-item-icon", { right: true }, h("bal-icon", { name: this.iconRight }))))))))); } static get is() { return "bal-doc-download"; } static get properties() { return { "link": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "link", "reflect": false, "defaultValue": "''" }, "iconLeft": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "icon-left", "reflect": false, "defaultValue": "'document'" }, "iconRight": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "icon-right", "reflect": false, "defaultValue": "'download'" }, "subject": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "subject", "reflect": false, "defaultValue": "''" }, "subtitle": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "subtitle", "reflect": false, "defaultValue": "''" } }; } }
#+TITLE: İlave Kurallar ----- - [[./index.org][Ana Sayfaya Dön]] Oyunda kullanacağımız bazı ilave kurallar aşağıdadır. * Karakter Takdimi FRP, söze dayalı bir oyun olduğu için, karakterlerin fiziksel özellikleri kolayca akıldan çıkabilir. Buna engel olmak için karakterini belli periyotlarda yeniden takdim etmeni isteyebilirim. Bunu ezberden yapmak her zaman kolay olmadığından, fiziksel özelliklerini kısaca not alman gerekebilir. Bunun için karakterinin dışarıdan bakınca algılanan özelliklerine odaklan, ve aşağıdaki beş maddeye, bir iki cümleyle kısaca değin. 1. *Genel Fizik.* Irk, cinsiyet, etnisite, vücut yapın, ve göründüğü kadarıyla yaşın. 2. *Silah, Zırh ve Kıyafetler.* Görünen silahların, ve onları taşıdığın yerler. Giydiğin zırh veya kıyafetlerin genel özellikleri. 3. *Semboller ve Süsler.* Üzerinde bulunan kutsal semboller, takılar, kalkanındaki armalar, vs. Ve bunların oyun dünyasındaki anlamları. 4. *Özgün Nitelik.* Karakterini diğerlerinden ayıran önemli bir detay. Bu fiziksel bir özelliğin, taşıdığın bir şey, kendine has duruşun, tutumun vb. bir niteliği kapsayabilir. 5. *Yeni Detay.* Karakterinin yakın zamanda, oyun esnasında ortaya çıkan bir detayı. Bu herhangi bir şey olabilir: Kullandığın bir hünerin, geçmişine dair ortaya çıkan yeni bir bilgi, veya birayı şaraba tercih etmen, gibi. Anlatımın sırasında, niteliğe dayalı tariflerden çok, hayal gücünde çağrışımlar yapabilen anlam yüklü kelimeler tercih et. Örneğin kılığını anlatırken, "çizgili, saten bir pantolon; yeşil, dökümlü bir bluz; ve bağcıklı mor bir korse" yerine, "gezgin bir göstericinin cafcaflı kostümü" ifadesini kullanmak, tarifini daha etkili ve kolay kavranır hale getirir. Örnek bir karakter takdimi aşağıdadır: 1. *Genel Fizik.* Karpin, narin yapılı, genç bir erkek. Tipik bir Radovyalı gibi esmer, köşeli yüz hatlarına sahip ve bıyıklı. 2. *Silah, Zırh ve Kıyafetler.* Sırtında beceriksizce taşıdığı arbaletine ilaveten yanından sarkan bir sopası var. Sonbahar renklerinde soylu kıyafetleri ve uzun bir pelerin giyiyor. 3. *Semboller ve Süsler.* Yüzüğünde çok da ihtişamlı görünmeyen bir soylu mührü taşıyor. 4. *Özgün Nitelik.* Sıkça avcunda gezdirdiği bir altın sikkeye sahip. 5. *Yeni Detay.* Kirli çıkı bir yönü var. Son macerada çantasından soylu babasından habersizce aldığı şifa iksirleri çıktı. * Seans Katılımı ve XP Eğer bir sebepten ötürü oyun seansına katılamazsan, karakterinin idaresini bana devretmiş sayılırsın. Bu durumda, öncelikle o seans için, karakterini gruptan ayırmaya çalışırım. Elbette bunun için grubun elverişli bir yerde olması gerekir. Örneğin bir yerleşim yerindeyseniz, karakterinin kendi başına bir şeyler yapıyor olması akla yatkındır. Ancak bu hep mümkün olmaz. Zindanın ortasındayken, karakterinin bir seanslığına ortadan kaybolup gelmesi, hikaye devamlılığına zarar verir. Dolayısıyla bu gibi durumlarda, karakterini tıpkı bir NPC gibi ben kontrol ederim. Mekanik özelliklerinin idaresini ise bir başka oyuncuya devredebilirim. Bu hepimize ekstra bir yük teşkil ettiğinden, karakterini yukarıda anlattığım şekilde ayırmak önceliğimdir. Karakterin, mevcut olmadığı Encounter’lardan XP almaz. * Seviye Atlama Karakterin, maceralarda kazandığı tecrübeleri, yerleşim yerlerinde yaptığı çalışmalarla birleştirerek seviye atlar. ** Çalışma Türleri ve Fasiliteler :PROPERTIES: :UNNUMBERED: notoc :END: Bunun için karakter yaratımı esnasında, ana ve yan olacak şekilde iki çalışma türü seçersin. Genellikle karakterin ilk mesleği ana çalışma türünü, ikinci mesleği ise yan türünü belirler. Karakterlerin çalışma türlerinde nihai karar bana aittir. Çalışma türleri şunlardır: - *Akademik Çalışma (20 gp):* Araştırma, inceleme, deney, eğitim, danışma ve uzmanlığı kapsar. Genellikle bilginler ve alimler eşliğinde, kütüphanelerde, laboratuvarlarda veya arşivlerde yapılır. - *Pratik Çalışma (10 gp):* Uzmanlığa dayalı pek çok dalı içerir. Yabanda hayatta kalma, zanaatkârlık, hırsızlık veya dolandırıcılık gibi bir hünerin gelişimine dayalı aktivitelerdir. Genellikle yerleşim yerlerinde veya yakın civarlarında, benzer meslek dallarından uzmanlarla bir arada çalışarak yapılır. - *Ritüel Çalışması (20 gp):* Törenler, ayinler, meditasyon, tasavvur, gizli ilimler ve diğer ruhani pratikleri içerir. Bir şeylerle bağ kurmaya dayanır. Rahipler, falcılar, büyücüler, şövalyeler, keşişler bu yöntemleri kullanır. - *Savaş Çalışması (10 gp):* Egzersiz, direnç, karşılıklı dövüş, hedef talimi, ve benzeri fiziksel idmanları kapsar. Kas, refleks ve kondisyona dayalı meslekler için gereklidir. Genellikle askeri talim alanları, dövüş kulüpleri, manastırlar, idman salonları vb. yerlerde yapılır. - *Sosyal Çalışma (20 gp):* Mesleğine uygun çevrelerle temasta bulunmaya dayalı bir çalışma türüdür. Zanaatkârlar, dolandırıcılar, sanatçılar, kanaat önderleri vb. profesyoneller, benzer toplulukların içerisinde bulunarak meziyetlerini geliştirir. Çalışma türleri, doğaları gereği farklı dinamikler ortaya çıkarır. Örneğin, hırsızlık yeteneklerini geliştirmek riskli olabileceği gibi, kazançlı da olabilir. Ritüellerin ruhani bağları kuvvetlendirmesi, beklenenden uzun zaman alabilir. Her fasilitenin, bunun dışında da kendine has nitelikleri olabilir. Bu gibi durumlar, oyun esnasında ortaya çıkacaktır. ** Çalışma Periyotları :PROPERTIES: :UNNUMBERED: notoc :END: Çalışma fasiliteleri, ekstrem durumlar dışında çoğu yerleşim yerinde mevcuttur. Karakterin yeterli XP’ye ulaştığında, seviye atlamak için buralarda çalışma yapması gerekir. Bu çalışma zamanı, 4 saatlik periyotlardan oluşur. Karakterin ana çalışma türünde eğitim yapıyorsa, harcaman gereken periyot sayısı, ulaştığın seviyenin iki katıdır. Yan türünde çalışma yapıyorsan, harcaman gereken periyot sayısı, ulaştığın seviyenin iki buçuk (yukarı yuvarla) katıdır. Örneğin 3. seviyeye atladığında, ana türünde, 4 saatlik 6 periyotta çalışma yaparsın. Yan türünde ise 8 periyotta çalışma yaparsın. Yan türde çalışma daha uzun olsa da, bazı koşullarda daha elverişli olabilir. Fasiliteye erişememe, farklı faydalar gözetme, gibi. Eğitim süresi boyunca ortaya çıkan masrafları ödemen gerekir. Bunlar, türlerin yanında belirtilmiştir. Bu sürenin sonunda seviye atlamayı tamamlarsın. ** Rehberlik :PROPERTIES: :UNNUMBERED: notoc :END: Seviye atlarken tek başına çalışabileceğin gibi, bir rehbere de danışabilirsin. Rehberler, alanlarında uzman NPC’lerdir. Kendi başına çalışırken mevcut sınıfında seviye atlayabilir, mevcut skill'lerine yeni kademe ekleyebilir, mesleğinin getirdiği gelişim özelliklerini alabilirsin. Ayrıca mevcut özelliklerinin devamı olan, veya ön koşullarını tamamladığın feat'leri edinebilirsin. Yeni bir meslekte ilk seviyeni almak, yeni bir skill'e giriş yapmak, karakter özelliklerinin devamı niteliğinde olmayan bir feat'i almak için rehberlik gerekir. Karakter gelişiminde rehberlik gerekip gerekmediğini belirlerken son karar bana aittir. Rehberlik yapacak NPC’lere ulaşman her zaman kolay olmayabilir. Çoğu zaman eğitim karşılığında karakterinin bu kişilere bir şeyler sunması gerekir. Dolayısıyla oyun sırasında bu gibi karakterleri teşhis edip, onlardan istifade etme yollarını gözetmek, lehine olur. Rehberler, karakterine ana kitapta olmayan feat'ler, meslekler, büyüler veya özellikler sunabilir. İlaveten seni seviye atlarken attığın düşük HP zarlarına karşı korur. Son olarak da, rehber eşliğinde çalışarak seviye atlarsan, o seviye boyunca %10 XP bonusu kazanırsın. * Yaşam Tarzı Giderleri Yerleşim yerinde geçirdiğin her gün; konaklama, beslenme, dinlenme, ekipman bakımı, eğlence, sosyalleşme gibi ihtiyaçlarını karşılarsın. Bunlar masada oynanmasa dahi, arka planda gerçekleşmiş sayılır. Bu gibi giderleri karşılamak için gün sonunda DM'in yerleşim yeri koşullarına göre belirlediği bir miktar parayı ödemen gerekir. Bunu karşılayamazsan hastalık, yaralanma, ekipman hasarı gibi komplikasyonlar gerçekleşebilir. Öte yandan kalburüstü bir yaşam tarzı benimser, ve bunun ilave giderlerini karşılarsan; sosyal interaksiyonlarda bonuslar, hediyeler, özel bağlantılar gibi cazip fırsatlar elde edebilirsin. ------ - [[./index.org][Ana Sayfaya Dön]]
from WineQuality.constant import * from WineQuality.utils.common import read_yaml, create_directories from WineQuality.entity.config_entity import (DataIngestionConfig, DataValidationConfig, DataTransformationConfig, ModelTrainingConfig, ModelEvaluationConfig ) class ConfigurationManager: def __init__(self, config_filepath = CONFIG_FILE_PATH, params_filepath = PARAMS_FILE_PATH, schema_filepath = SCHEMA_FILE_PATH ): self.config = read_yaml(config_filepath) self.params = read_yaml(params_filepath) self.schema = read_yaml(schema_filepath) create_directories([self.config.artifacts_root]) def get_data_ingestion_config(self) ->DataIngestionConfig: config = self.config.data_ingestion create_directories([config.root_dir]) data_ingestion_config = DataIngestionConfig( root_dir=config.root_dir, source_url=config.source_url, local_data_file=config.local_data_file, unzip_dir=config.unzip_dir ) return data_ingestion_config def get_data_validation_config(self) -> DataValidationConfig: config = self.config.data_validation schema = self.schema.COLUMNS create_directories([config.root_dir]) data_validation_config = DataValidationConfig( root_dir=config.root_dir, status_file=config.status_file, unzip_data_dir=config.unzip_data_dir, all_schema=schema ) return data_validation_config def get_data_transformation_config(self) ->DataIngestionConfig: config = self.config.data_transformation create_directories([config.root_dir]) data_transform_config = DataTransformationConfig( root_dir=config.root_dir, data_path=config.data_path, ) return data_transform_config def get_model_training_config(self) ->ModelTrainingConfig: config = self.config.model_trainer params = self.params.ElasticNet schema = self.schema.TARGET_COLUMNS create_directories([config.root_dir]) model_trainer_config = ModelTrainingConfig( root_dir=config.root_dir, train_data_path=config.train_data_path, test_data_path=config.test_data_path, model_name=config.model_name, alpha = params.alpha, l1_ratio = params.l1_ratio, target_column = schema.name ) return model_trainer_config # def get_model_evaluation_config(self) ->ModelEvaluationConfig: # config = self.config.model_evaluation # params = self.params.ElasticNet # schema = self.schema.TARGET_COLUMNS # create_directories([config.root_dir]) def get_model_evaluation_config(self) ->ModelEvaluationConfig: config = self.config.model_evaluation params = self.params.ElasticNet schema = self.schema.TARGET_COLUMNS create_directories([config.root_dir]) model_evaluation_config = ModelEvaluationConfig( root_dir = config.root_dir, test_data_path = config.test_data_path, model_path = config.model_path, metric_file_name = config.metric_file_name, all_params = params, target_column = schema.name, mlflow_uri = "https://dagshub.com/AnilKumar-06/Wine_Quality_End_To_End.mlflow" ) return model_evaluation_config
<?php require __DIR__ . '/vendor/autoload.php'; use GuzzleHttp\Client; function fetchData() { $client = new Client(); $response = $client->get('https://public.opendatasoft.com/api/records/1.0/search/?dataset=georef-united-states-of-america-state&q=&rows=56&facet=ste_name'); $data = json_decode($response->getBody(), true); return $data; } // Cache the API data using a simple file-based cache function getCachedData() { $cacheFile = __DIR__ . '/cached_data.json'; if (file_exists($cacheFile)) { $data = json_decode(file_get_contents($cacheFile), true); if ($data && time() - $data['timestamp'] < 3600) { return $data['data']; } } $data = fetchData(); file_put_contents($cacheFile, json_encode(['data' => $data, 'timestamp' => time()])); return $data; } $statesJSON = getCachedData(); // PAINT THE STATES DATA foreach ($statesJSON['records'] as $record) { $state = $record['fields']['ste_name']; echo "<li>$state</li>"; }
<template> <div class="tw-flex tw-grow tw-justify-center tw-my-8 tw-transition-all" :class="[ {'tw-items-center': !expandedView}, {'tw-items-start tw-overflow-auto': expandedView} ]"> <div> <div class="tw-sticky tw-top-0 tw-z-10 tw-bg-gray-50 tw-font-noto-sans"> <h1 class="tw-text-3xl tw-text-slate-800 tw-text-center tw-font-black"> Pre-loved {{ search.product.name }}, </h1> <h2 class="tw-text-xl tw-text-slate-500 tw-text-center tw-pb-6 tw-mb-8 tw-font-light"> looking for new owners </h2> </div> <div class="tw-grid tw-grid-cols-3 tw-gap-16 tw-px-3"> <ResultCard v-for="result in topMatches" :key="result.url" :title="result.title" :price="result.price" :location="result.location" :cover-image="result.coverImage" :link="result.link" /> <template v-if="expandedView"> <ResultCard v-for="result in matches.slice(3)" :key="result.url" :title="result.title" :price="result.price" :location="result.location" :cover-image="result.coverImage" :link="result.link" /> <ResultCard v-for="result in suggestions" :key="result.url" :title="result.title" :price="result.price" :location="result.location" :cover-image="result.coverImage" :link="result.link" /> </template> </div> <button @click="expandView" v-if="!expandedView" class="tw-flex tw-justify-evenly tw-items-center tw-px-3 tw-py-2 tw-bg-slate-200 tw-rounded-full tw-text-medium tw-font-medium tw-text-slate-500 tw-mx-auto tw-mt-7 tw-w-36"> Show more <unicon name="arrow-down" class="tw-fill-slate-500 tw-animate-bounce"/> </button> </div> </div> <div class="tw-flex tw-justify-center" v-if="expandedView"> <router-link to="/modal/about" class="tw-flex tw-justify-between tw-items-center tw-bg-green-100 tw-px-4 tw-py-3 tw-cursor-pointer tw-rounded-full hover:tw-no-underline"> <unicon name="trees" class="tw-fill-green-500 tw-mr-2"/> <span class="tw-text-green-500"> Buying local pre-loved items helps preserving our environment. <em class="tw-underline tw-not-italic">Learn how</em> </span> </router-link> </div> </template> <script> import { mapState } from 'vuex'; import ResultCard from '@/components/app/ResultCard.vue'; export default { name: 'ResultsView', components: { ResultCard }, props: { expandedView: Boolean, }, emits: ['expand'], computed: { ...mapState(['search', 'matches', 'suggestions', 'userScore']), topMatches() { return this.matches.slice(0, 3); }, }, methods: { expandView() { this.$emit('expand'); }, }, }; </script> <style scoped> </style>
type NotasDeProva = [number, number, number, number] type NotasDeTrabalho = [number, number]; class Estudante { matricula: string; nome: string; notasDeProva: NotasDeProva; notasDeTrabalho: NotasDeTrabalho; constructor(matricula: string, nome: string, notasDeProva: NotasDeProva, notasDeTrabalho: NotasDeTrabalho) { this.matricula = matricula; this.nome = nome; this.notasDeProva = notasDeProva; this.notasDeTrabalho = notasDeTrabalho } calculaNotaTotal(): number { let notaTotal = 0; this.notasDeProva.forEach((nota: number) => notaTotal += nota); this.notasDeTrabalho.forEach((nota: number) => notaTotal += nota); return notaTotal; } calculaNotaMedia(): number { const notaTotal = this.calculaNotaTotal(); const quantidadeDeNotas = this.notasDeProva.length + this.notasDeTrabalho.length; const notaMedia = notaTotal / quantidadeDeNotas; return notaMedia; } }
package test_model; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import javax.swing.tree.ExpandVetoException; import junit.framework.TestFailure; import impl_model.GKAModel; import impl_model.NamedWeightedEdge; import interface_model.FloydWarshallModel; import org.jgrapht.Graph; import org.jgrapht.graph.DirectedPseudograph; import org.jgrapht.graph.DirectedWeightedMultigraph; import org.jgrapht.graph.DirectedWeightedPseudograph; import org.jgrapht.graph.Pseudograph; import org.junit.Before; import org.junit.Test; public class TestFloydWarshall { Graph<String, NamedWeightedEdge> _simple_directed_graph; FloydWarshallModel _sm; Graph<String, NamedWeightedEdge> _klaucks_graph; FloydWarshallModel _km; Graph<String, NamedWeightedEdge> _undirected_graph; FloydWarshallModel _um; @Before public void setUp() { // simple directed graph _simple_directed_graph = new DirectedWeightedPseudograph(NamedWeightedEdge.class); _simple_directed_graph.addVertex("a"); _simple_directed_graph.addVertex("b"); _simple_directed_graph.addVertex("c"); NamedWeightedEdge edgeAtoB; edgeAtoB = new NamedWeightedEdge(); edgeAtoB.setWeight(2.0); NamedWeightedEdge edgeBtoC; edgeBtoC = new NamedWeightedEdge(); edgeBtoC.setWeight(3.0); _simple_directed_graph.addEdge("a", "b", edgeAtoB); _simple_directed_graph.addEdge("b", "c", edgeBtoC); _sm = GKAModel.floydWarshall(_simple_directed_graph); // klaucks graph _klaucks_graph = new DirectedWeightedPseudograph(NamedWeightedEdge.class); _klaucks_graph.addVertex("v1"); _klaucks_graph.addVertex("v2"); _klaucks_graph.addVertex("v3"); _klaucks_graph.addVertex("v4"); NamedWeightedEdge edgeV1toV2; edgeV1toV2 = new NamedWeightedEdge(); edgeV1toV2.setWeight(1.0); NamedWeightedEdge edgeV1toV4; edgeV1toV4 = new NamedWeightedEdge(); edgeV1toV4.setWeight(3.0); NamedWeightedEdge edgeV4toV1; edgeV4toV1 = new NamedWeightedEdge(); edgeV4toV1.setWeight(2.0); NamedWeightedEdge edgeV4toV3; edgeV4toV3 = new NamedWeightedEdge(); edgeV4toV3.setWeight(2.0); NamedWeightedEdge edgeV2toV4; edgeV2toV4 = new NamedWeightedEdge(); edgeV2toV4.setWeight(1.0); NamedWeightedEdge edgeV2toV3; edgeV2toV3 = new NamedWeightedEdge(); edgeV2toV3.setWeight(2.0); NamedWeightedEdge edgeV3toV2; edgeV3toV2 = new NamedWeightedEdge(); edgeV3toV2.setWeight(2.0); _klaucks_graph.addEdge("v1", "v2", edgeV1toV2); _klaucks_graph.addEdge("v1", "v4", edgeV1toV4); _klaucks_graph.addEdge("v4", "v1", edgeV4toV1); _klaucks_graph.addEdge("v4", "v3", edgeV4toV3); _klaucks_graph.addEdge("v2", "v4", edgeV2toV4); _klaucks_graph.addEdge("v2", "v3", edgeV2toV3); _klaucks_graph.addEdge("v3", "v2", edgeV3toV2); _km = GKAModel.floydWarshall(_klaucks_graph); } @Test public void testDistanceMatrixInit() { ArrayList<Double> asource = new ArrayList<>(); asource.add(0.0); asource.add(2.0); asource.add(5.0); ArrayList<Double> bsource = new ArrayList<>(); bsource.add(Double.POSITIVE_INFINITY); bsource.add(0.0); bsource.add(3.0); ArrayList<Double> csource = new ArrayList<>(); csource.add(Double.POSITIVE_INFINITY); csource.add(Double.POSITIVE_INFINITY); csource.add(0.0); ArrayList expected = new ArrayList<>(); expected.addAll(Arrays.asList(asource, bsource, csource)); assertEquals(expected, _sm.getDistanceMatrix()); } @Test public void testGetTransitValue() { assertEquals(Integer.valueOf(4), _km.getTransitValue("v3", "v1")); assertEquals(Integer.valueOf(2), _km.getTransitValue("v3", "v4")); assertEquals(Integer.valueOf(0), _km.getTransitValue("v1", "v1")); } @Test public void testGetDistanceValue() { assertEquals(Double.valueOf(3.0), _km.getDistanceValue("v1", "v3")); assertEquals(Double.valueOf(5.0), _km.getDistanceValue("v3", "v1")); assertEquals(Double.valueOf(0.0), _km.getDistanceValue("v4", "v4")); } @Test public void testTransitMatrixSimple() { ArrayList<Integer> asource = new ArrayList<>(); asource.add(0); asource.add(0); asource.add(2); ArrayList<Integer> bsource = new ArrayList<>(); bsource.add(0); bsource.add(0); bsource.add(0); ArrayList<Integer> csource = new ArrayList<>(); csource.add(0); csource.add(0); csource.add(0); ArrayList<ArrayList<Integer>> expected = new ArrayList<>(); expected.addAll(Arrays.asList(asource, bsource, csource)); assertEquals(expected, _sm.getTransitMatrix()); } @Test public void testDistanceMatrixKlauck() { ArrayList<Double> asource = new ArrayList<>(); asource.add(0.0); asource.add(1.0); asource.add(3.0); asource.add(2.0); ArrayList<Double> bsource = new ArrayList<>(); bsource.add(3.0); bsource.add(0.0); bsource.add(2.0); bsource.add(1.0); ArrayList<Double> csource = new ArrayList<>(); csource.add(5.0); csource.add(2.0); csource.add(0.0); csource.add(3.0); ArrayList<Double> dsource = new ArrayList<>(); dsource.add(2.0); dsource.add(3.0); dsource.add(2.0); dsource.add(0.0); ArrayList<ArrayList<Double>> expected; expected = new ArrayList<>(); expected.addAll(Arrays.asList(asource, bsource, csource, dsource)); assertEquals(expected, _km.getDistanceMatrix()); } @Test public void testTransitMatrxKlauck() { ArrayList<Integer> asource = new ArrayList<>(); asource.add(0); asource.add(0); asource.add(2); asource.add(2); ArrayList<Integer> bsource = new ArrayList<>(); bsource.add(4); bsource.add(0); bsource.add(0); bsource.add(0); ArrayList<Integer> csource = new ArrayList<>(); csource.add(4); csource.add(0); csource.add(0); csource.add(2); ArrayList<Integer> dsource = new ArrayList<>(); dsource.add(0); dsource.add(1); dsource.add(0); dsource.add(0); ArrayList<ArrayList<Integer>> expected = new ArrayList<>(); expected.addAll(Arrays.asList(asource, bsource, csource, dsource)); assertEquals(expected, _km.getTransitMatrix()); } @Test public void testSimplePaths() { assertEquals(Arrays.asList("a", "b"), _sm.start("a", "b")); assertEquals(Arrays.asList("a", "b", "c"), _sm.start("a", "c")); } @Test public void testKlauckPaths() { assertEquals(Arrays.asList("v4", "v1", "v2"), _km.start("v4", "v2")); assertEquals(Arrays.asList("v3", "v2", "v4", "v1"), _km.start("v3", "v1")); } }
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io> // SPDX-License-Identifier: MIT package handler import ( "context" "crypto/rand" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "github.com/dipdup-io/celestia-indexer/pkg/types" "github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses" ws "github.com/dipdup-io/celestia-indexer/cmd/api/handler/websocket" "github.com/dipdup-io/celestia-indexer/internal/storage" "github.com/dipdup-io/celestia-indexer/internal/storage/mock" "github.com/goccy/go-json" "github.com/gorilla/websocket" "github.com/labstack/echo/v4" "github.com/lib/pq" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) func TestWebsocket(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() listenerFactory := mock.NewMockListenerFactory(ctrl) headListener := mock.NewMockListener(ctrl) txListener := mock.NewMockListener(ctrl) listenerFactory.EXPECT().CreateListener().Return(headListener).MaxTimes(1) listenerFactory.EXPECT().CreateListener().Return(txListener).MaxTimes(1) ctx, cancel := context.WithCancel(context.Background()) headChannel := make(chan *pq.Notification, 10) headListener.EXPECT().Listen().Return(headChannel).AnyTimes() txChannel := make(chan *pq.Notification, 10) txListener.EXPECT().Listen().Return(txChannel).AnyTimes() headListener.EXPECT().Subscribe(gomock.Any(), storage.ChannelHead).Return(nil).MaxTimes(1) txListener.EXPECT().Subscribe(gomock.Any(), storage.ChannelTx).Return(nil).MaxTimes(1) headListener.EXPECT().Close().Return(nil).MaxTimes(1) txListener.EXPECT().Close().Return(nil).MaxTimes(1) blockMock := mock.NewMockIBlock(ctrl) for i := 0; i < 10; i++ { hash := make([]byte, 32) _, err := rand.Read(hash) require.NoError(t, err) blockMock.EXPECT().ByIdWithRelations(ctx, uint64(i)).Return(storage.Block{ Id: uint64(i), Height: types.Level(i), Time: time.Now(), Hash: hash, }, nil).MaxTimes(1) } go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() var id uint64 for { select { case <-ctx.Done(): return case <-ticker.C: id++ headChannel <- &pq.Notification{ Channel: storage.ChannelHead, Extra: strconv.FormatUint(id, 10), } } } }() manager := ws.NewManager(listenerFactory, blockMock, nil) manager.Start(ctx) server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { e := echo.New() c := e.NewContext(r, w) err := manager.Handle(c) require.NoError(t, err, "handle") <-ctx.Done() }, )) defer server.Close() wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws" dialed, _, err := websocket.DefaultDialer.Dial(wsURL, nil) require.NoError(t, err, "dial") body, err := json.Marshal(ws.Subscribe{ Channel: ws.ChannelHead, }) require.NoError(t, err, "marshal subscribe") err = dialed.WriteJSON(ws.Message{ Method: ws.MethodSubscribe, Body: body, }) require.NoError(t, err, "send subscribe message") ticker := time.NewTicker(time.Second * 5) defer ticker.Stop() for { select { case <-ticker.C: body, err := json.Marshal(ws.Unsubscribe{ Channel: ws.ChannelHead, }) require.NoError(t, err, "marshal unsubscribe") err = dialed.WriteJSON(ws.Message{ Method: ws.MethodUnsubscribe, Body: body, }) require.NoError(t, err, "send unsubscribe message") err = dialed.Close() require.NoError(t, err, "closing connection") time.Sleep(time.Second) cancel() err = manager.Close() require.NoError(t, err, "closing manager") close(headChannel) close(txChannel) return default: err := dialed.SetReadDeadline(time.Now().Add(time.Second * 3)) require.NoError(t, err) _, msg, err := dialed.ReadMessage() require.NoError(t, err, err) var block responses.Block err = json.Unmarshal(msg, &block) require.NoError(t, err, err) require.Greater(t, block.Id, uint64(0)) require.Greater(t, block.Height, uint64(0)) require.False(t, block.Time.IsZero()) require.Len(t, block.Hash, 32) log.Info(). Uint64("height", block.Height). Time("block_time", block.Time). Msg("new block") } } }
import Motorcycle from '../Domains/Motorcycle'; import IMotorcycle from '../Interfaces/IMotorcycle'; import MotorcycleODM from '../Models/Motorcycle.ODM'; class MotorcycleService { private createMotorcycleDomain(motorcycle: IMotorcycle | null): Motorcycle | null { if (motorcycle) { return new Motorcycle(motorcycle); } return null; } public async create(motorcycle: IMotorcycle) { const motorcycleODM = new MotorcycleODM(); const newMotorcycle = await motorcycleODM.create(motorcycle); return this.createMotorcycleDomain(newMotorcycle); } public async getAll() { const motorcycleODM = new MotorcycleODM(); const motorcycles = await motorcycleODM.getAll(); return motorcycles.map((motorcycle) => this.createMotorcycleDomain(motorcycle)); } public async getById(id: string): Promise<Motorcycle | null | undefined> { const motorcycleODM = new MotorcycleODM(); const motorcycle = await motorcycleODM.getById(id); if (motorcycle === undefined) { return undefined; } return this.createMotorcycleDomain(motorcycle); } public async update(id: string, motorcycle: IMotorcycle): Promise<Motorcycle | null | undefined> { const motorcycleODM = new MotorcycleODM(); const updatedMotorcycle = await motorcycleODM.update(id, motorcycle); if (updatedMotorcycle === undefined) { return undefined; } return this.createMotorcycleDomain(updatedMotorcycle); } public async delete(id: string): Promise<Motorcycle | null | undefined> { const motorcycleODM = new MotorcycleODM(); const deletedMotorcycle = await motorcycleODM.delete(id); if (deletedMotorcycle === undefined) { return undefined; } return this.createMotorcycleDomain(deletedMotorcycle); } } export default MotorcycleService;
package com.resrun.service.image; import com.resrun.utils.Base64; import org.apache.pdfbox.io.IOUtils; import org.springframework.stereotype.Service; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; /** * @Description: 企业签章业务 * @Package: com.resrun.service.image * @ClassName: EntSealGenerateService * @copyright 北京资源律动科技有限公司 */ @Service public class EntSealGenerateService { /** * @Description #生成企业签章 * @Param [topText, middleText] * @return byte[] **/ public byte[] generateEntSeal(String topText,String middleText){ byte[] bytes = export2pic("png", middleText,topText); return bytes; } /** * 印章名称距中心点偏移量,按照y轴方向 */ private int nameOffset = 50; /** * 印章宽度 */ private int width = 200; /** * 印章高度 */ private int height = 200; /** * 印章中心标志(默认为五角星)外接圆半径 */ private float radius = 30; /** * 印章名称颜色 */ private Color nameColor = Color.RED; /** * 印章所属单位 */ // private String firm; /** * 印章所属单位颜色 */ private Color firmColor = Color.RED; private float firmScale = 0.7F; /** * 边框线宽 */ private float borderWidth = 5F; /** * 边框颜色 */ private Color borderColor = Color.RED; /** * 印章标记(默认为五角星)线宽 */ private float signBorderWidth = 3F; /** * 印章标记颜色 */ private Color signBorderColor = Color.RED; /** * 印章标记填充颜色 */ private Color signFillColor = Color.RED; public void draw(Graphics2D g2d,String middleText,String topText) { // 把绘制起点挪到圆中心点 g2d.translate(width / 2, height / 2); Stroke stroke = g2d.getStroke();// 旧的线性 // 填充五角星 Polygon polygon = getPentaclePoints(radius); if (signFillColor != null) { g2d.setColor(signFillColor); g2d.fill(polygon); } // 绘制五角星边框 g2d.setStroke(new BasicStroke(signBorderWidth)); g2d.setColor(signBorderColor); g2d.draw(polygon); // 绘制印章边框 g2d.setFont(nameFont); g2d.setColor(borderColor); g2d.setStroke(new BasicStroke(borderWidth)); g2d.drawOval(-width / 2, -height / 2, width, height); g2d.setStroke(stroke); // 绘制印章名称 g2d.setFont(nameFont); g2d.setColor(nameColor); //g2d.setStroke(new BasicStroke(10F)); FontMetrics fm = g2d.getFontMetrics(); int w = fm.stringWidth(middleText);// 名称宽度 int h = fm.getHeight();// 名称高度 int y = fm.getAscent() - h / 2;// 求得中心线经过字体的高度的一半时的字体的起绘点 g2d.drawString(middleText, -w / 2, y + nameOffset); // 绘制印章单位 g2d.setFont(getFirmFont(topText)); g2d.setColor(firmColor); fm = g2d.getFontMetrics(); h = fm.getHeight();// 字高度 int count = topText.length();// 字数 int r = width / 2;// 半径,就假设此印章是个矩形,方便计算 float angle; float start; if(count>1 && count <=10){ angle = 20f;// 字间角度 start = 90+(360 - angle*(count-1))/2;// 以x轴正向为0,顺时针旋转 }else if(count > 10){ angle = (360 - firmAngle) / (count-1);// 字间角度 start = 90+(360 - angle*(count-1))/2;// 以x轴正向为0,顺时针旋转 }else{ angle = 0f;// 字间角度 start = 90+(360 - angle*(2-1))/2;// 以x轴正向为0,顺时针旋转 } double vr = Math.toRadians(90);// 垂直旋转弧度 char[] chars = topText.toCharArray(); for (int i = 0; i < count; i++) { char c = chars[i];// 需要绘制的字符 int cw = fm.charWidth(c);// 此字符宽度 float a = start + angle * i;// 现在角度 double radians = Math.toRadians(a); g2d.rotate(radians);// 旋转坐标系,让要绘制的字符处于x正轴 float x = r - h;// 绘制字符的x坐标为半径减去字高度 g2d.translate(x, 0);// 移动到此位置,此时字和x轴垂直 g2d.rotate(vr);// 旋转90度,让字平行于x轴 g2d.scale(firmScale, 1);// 缩放字体宽度 g2d.drawString(String.valueOf(c), -cw / 2, 0);// 此点为字的中心点 // 将所有设置还原,等待绘制下一个 g2d.scale(1 / firmScale, 1); g2d.rotate(-vr); g2d.translate(-x, 0); g2d.rotate(-radians); } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } /** * 获取具有指定半径外接圆的五角星顶点 * * @param radius * 圆半径 */ private Polygon getPentaclePoints(float radius) { if (radius <= 0) return null; float lradius = radius * 0.381966f;// 根据radius求内圆半径 double halfpi = Math.PI / 180f; Point[] points = new Point[10]; for (int i = 0; i < points.length; i++) { if (i % 2 == 1) points[i] = new Point( (int) (Math.sin(halfpi * 36 * i) * radius), (int) (Math.cos(halfpi * 36 * i) * radius)); else points[i] = new Point( (int) (Math.sin(halfpi * 36 * i) * lradius), (int) (Math.cos(halfpi * 36 * i) * lradius)); } Polygon polygon = new Polygon(); for (Point p : points) { polygon.addPoint(p.x, p.y); } return polygon; } public int getWidth() { return width; } public int getHeight() { return height; } private Font nameFont = new Font("宋体", Font.PLAIN, 19); private Font getFirmFont(String topText){ Font font = null; int len = topText.length(); System.out.println(len); if(len==1){ setFirmAngle(355); font = new Font("宋体", Font.PLAIN, 25); }else if(len>1 && len<=3){ setFirmAngle(310); font = new Font("宋体", Font.PLAIN, 25); }else if(len>3 && len<=6){ setFirmAngle(250); font = new Font("宋体", Font.PLAIN, 25); }else if(len>6 && len <=10){ setFirmAngle(200); font = new Font("宋体", Font.PLAIN, 25); }else if(len>10 && len<=13){ setFirmAngle(180); font = new Font("宋体", Font.PLAIN, 25); } else if(len>13 && len<=20){ font = new Font("宋体", Font.PLAIN, 25); setFirmAngle(120); }else if(len>20 && len <= 25){ font = new Font("宋体", Font.PLAIN, 23); setFirmAngle(80); }else if(len>25 && len < 30){ setFirmAngle(80); font = new Font("宋体", Font.PLAIN, 19); }else if(len>=30 && len <= 40){ setFirmAngle(80); font = new Font("宋体", Font.PLAIN, 19); }else{ setFirmAngle(10); font = new Font("宋体", Font.PLAIN, 17); } return font; } private int firmAngle; public void setFirmAngle(int firmAngle){ this.firmAngle = firmAngle; } /** * 导出此印章为透明背景的图片字节数组. * * @param format * 图片类型,如果为null,则默认为png * @return 数组 * @throws FileNotFoundException * @throws IOException * 写出图像数据出现问题 */ public byte[] export2pic(String format,String middleText,String topText) { int fix = 5;// 宽高修正,如果宽高就为图片宽高,可能边框线被切割 BufferedImage bi = new BufferedImage(getWidth() + fix * 2, getHeight() + fix * 2, 3); Graphics2D g2d = bi.createGraphics(); //防锯齿状毛刺算法 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.translate(fix, fix); draw(g2d,middleText,topText); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(bi, format == null ? "png" : format, baos); return baos.toByteArray(); } catch (IOException e) { throw new RuntimeException(topText+":生成企业签章失败",e); }finally { try { if(baos!=null) baos.close(); } catch (IOException e) { } } } }
// // ViewController.swift // CourseDisplayApp2 // // Created by Ajay Bandi on 3/16/23. // import UIKit class ViewController: UIViewController { @IBOutlet weak var displayImage: UIImageView! @IBOutlet weak var crsNum: UILabel! @IBOutlet weak var crsTitle: UILabel! @IBOutlet weak var semOffered: UILabel! @IBOutlet weak var prevBtn: UIButton! @IBOutlet weak var nextBtn: UIButton! let courses = [ ["img01", "44555", "Network Security", "Fall2022"], ["img02", "44643", "iOS", "Spring 2023"], ["img03", "44656", "Streaming Data", "Summer 2023"]] var imageNum = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //Update the details of the first course. (image, num, tile, sem) UpdateCourse(imageNum) //Disable the previous button prevBtn.isEnabled = false //Enable the next button nextBtn.isEnabled = true } @IBAction func prevBtnClicked(_ sender: UIButton) { //Decrement image number imageNum -= 1 // Update Previous course details UpdateCourse(imageNum) //Enable NextButton nextBtn.isEnabled = true //When you reach starting of array disable previous button if(imageNum == 0) { prevBtn.isEnabled = false } } @IBAction func nextBtnClicked(_ sender: UIButton) { //Increment my image number imageNum += 1 //Update the next course details UpdateCourse(imageNum) //Previous button should be enabled prevBtn.isEnabled = true //When you reach end of array, next button should be disabled. if(imageNum == courses.count-1) { nextBtn.isEnabled = false } } func UpdateCourse(_ imageNumber:Int) { displayImage.image = UIImage(named: courses[imageNum][0]) crsNum.text = courses[imageNum][1] crsTitle.text = courses[imageNum][2] semOffered.text = courses[imageNum][3] } }
<?php // Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); include_once '../../config/Database.php'; include_once '../../models/Post.php'; // Instantiate DB & connect $database = new Database(); $db = $database->connect(); // Instantiate blog post object $post = new Post($db); // Blog post query $result = $post->read(); // Get rows count $num = $result->rowCount(); // Check if any posts if($num > 0) { // Posts array $posts_arr = array(); $posts_arr['data'] = array(); while($row = $result->fetch(PDO::FETCH_ASSOC)) { extract($row); $posts_item = array( 'id' => $id, 'title' => $title, 'body' => html_entity_decode($body), 'author' => $author, 'category_id' => $category_id, 'category_name' => $category_name ); // Push to "data" array_push($posts_arr['data'], $posts_item); } // Turn to JSON & output echo json_encode($posts_arr); } else { // No Posts echo json_encode(array( 'message' => 'No Posts Found' )); }
/************************************************************************************* * Description : * Version : 1.0 * Author : huzhenhong * Date : 2022-10-19 11:00:55 * LastEditors : huzhenhong * LastEditTime : 2023-01-06 20:00:24 * FilePath : \\FmtLog\\src\\FileSink.h * Copyright (C) 2022 huzhenhong. All rights reserved. *************************************************************************************/ #pragma once #include "ISink.h" #include "TSCNS.h" class FileSink : public ISink { public: FileSink(const char* filename, bool truncate) { Open(filename, truncate); } ~FileSink() {} void Sink(LogLevel level, fmt::string_view msg) override { // std::cout << msg.data() << std::endl; if (level >= m_flushLevel) { m_membuf.append(msg); m_membuf.push_back('\n'); if (m_membuf.size() >= m_flushBufSize) { // 保护磁盘 int64_t tsc = TimeStampCounterWarpper::impl.Rdtsc(); int64_t now = TimeStampCounterWarpper::impl.Tsc2ns(tsc); if (now > m_nextFlushTime) { Flush(); } else if (m_nextFlushTime == std::numeric_limits<int64_t>::max()) // 首次执行 { m_nextFlushTime = now + m_flushDelay; } } } } void SetFlushDelay(int64_t ns) noexcept { m_flushDelay = ns; } void SetFlushLevel(LogLevel flushLevel) noexcept { m_flushLevel = flushLevel; } void SetFlushBufSize(uint32_t bufSize) noexcept { m_flushBufSize = bufSize; } private: bool Open(const char* filename, bool truncate) { FILE* newFp = fopen(filename, truncate ? "w" : "a"); if (!newFp) { std::string err = fmt::format("Unable to open file: {}: {}", filename, strerror(errno)); fmt::detail::throw_format_error(err.c_str()); } setbuf(newFp, nullptr); m_fpos = ftell(newFp); Close(); // ? m_outputFp = newFp; m_isManageFp = true; } void Close() { if (m_membuf.size()) { Flush(); } if (m_isManageFp) { fclose(m_outputFp); } m_outputFp = nullptr; m_isManageFp = false; } void Flush() { if (m_membuf.size() == 0) return; if (m_outputFp) { fwrite(m_membuf.data(), 1, m_membuf.size(), m_outputFp); if (!m_isManageFp) fflush(m_outputFp); else m_fpos += m_membuf.size(); } m_membuf.clear(); m_nextFlushTime = (std::numeric_limits<int64_t>::max)(); } private: LogLevel m_flushLevel; fmt::basic_memory_buffer<char, 10000> m_membuf; uint32_t m_flushBufSize = 8 * 1024; FILE* m_outputFp = nullptr; bool m_isManageFp = false; size_t m_fpos = 0; // file position of membuf, used only when manageFp == true // int64_t m_flushDelay = 3000'000'000; // ns int64_t m_flushDelay = 30'000'000; // ns int64_t m_nextFlushTime = (std::numeric_limits<int64_t>::max)(); };
import numpy as np import torch import torch.nn.functional as F def perform_qlearning_step(policy_net, target_net, optimizer, replay_buffer, batch_size, gamma, device): """ Perform a deep Q-learning step Parameters ------- policy_net: torch.nn.Module policy Q-network target_net: torch.nn.Module target Q-network optimizer: torch.optim.Adam optimizer replay_buffer: ReplayBuffer replay memory storing transitions batch_size: int size of batch to sample from replay memory gamma: float discount factor used in Q-learning update device: torch.device device on which to the models are allocated Returns ------- float loss value for current learning step """ # TODO: Run single Q-learning step """ Steps: 1. Sample transitions from replay_buffer 2. Compute Q(s_t, a) 3. Compute \max_a Q(s_{t+1}, a) for all next states. 4. Mask next state values where episodes have terminated 5. Compute the target 6. Compute the loss 7. Calculate the gradients 8. Clip the gradients 9. Optimize the model """ """ loss function is: Expectation[ (reward + gamma * max_a'(Q(s', s'; theta_i)) - Q(s, a; theta) )^2 ] """ obs_batch, act_batch, rew_batch, next_obs_batch, done_mask = replay_buffer.sample(batch_size) # print("act_batch : ", act_batch) q_values = policy_net.forward(obs_batch) # print("q_val: ", q_values) # ref: https://discuss.pytorch.org/t/selecting-element-on-dimension-from-list-of-indexes/36319 q_values = q_values[torch.arange(q_values.size(0)), torch.from_numpy(act_batch)].unsqueeze(1) # print("q_val: ", q_values) max_target_q = target_net(next_obs_batch).max(1)[0].detach() # detach is also like making a copy ''' print("max target: ", max_target_q.shape) [N,4] print("gamma: ",gamma) print("rew: ", rew_batch.shape) (N) numpy print("mask: ", torch.from_numpy(done_mask==0).shape) [N] print("q_val: ", q_values) ''' max_target_q *= torch.from_numpy(done_mask==0).to(device) q_target = torch.from_numpy(rew_batch).to(device) + gamma*max_target_q loss = F.smooth_l1_loss(q_values, q_target.unsqueeze(1)) optimizer.zero_grad() loss.backward() # clips the gradient, check how this works torch.nn.utils.clip_grad_value_(policy_net.parameters(),1) optimizer.step() return loss def update_target_net(policy_net, target_net): """ Update the target network Parameters ------- policy_net: torch.nn.Module policy Q-network target_net: torch.nn.Module target Q-network """ # TODO: Update target network target_net.load_state_dict(policy_net.state_dict())
package main import ( "log" "time" ) const numJobs = 10 func main() { jobs := make(chan int, numJobs) results := make(chan int, numJobs) for w := 1; w <= 5; w++ { go worker(w, jobs, results) } for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) for a := 1; a <= numJobs; a++ { log.Println("Result:", <-results) } } func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { log.Printf("Worker %d processing job %d\n", id, j) time.Sleep(time.Second) results <- j } }
import { memo } from 'react' import IconEdit from '@/assets/image/icon_edit.svg' import IconView from '@/assets/image/icon_view.svg' import style from '@/common.module.scss' import { URL } from '@/utils/constants' import { renderDateStringYear } from '@/utils/helper' import { Button, ConfigProvider, Space, Table } from 'antd' import { Link } from 'react-router-dom' const TableListBlog = ({ listBlog, loading, currentPage, perPage, setSelectedRowKeys, }: any) => { const columns = [ { title: 'STT', dataIndex: 'STT', align: 'center', width: 45, fixed: true, render: (_: any, record: any, row: any) => { return ( <div> {(perPage * (currentPage - 1) + (row + 1))?.toLocaleString()} </div> ) }, }, { title: 'Ảnh', dataIndex: 'img', align: 'center', width: '80px', render: (_: any, record: any) => { return <img className="w-[60px] h-[60px]" src={record?.img} alt="img" /> }, }, { title: 'Tiêu đề bài viết', dataIndex: 'title', align: 'center', width: '200px', }, { title: 'Người đăng', dataIndex: 'author', align: 'center', width: '130px', }, { title: 'Ngày tạo', dataIndex: 'created_at', align: 'center', width: '100px', render: (row: any, record: any) => ( <div>{renderDateStringYear(record?.created_at, '-')}</div> ), }, { title: 'Ngày cập nhật', dataIndex: 'updated_at', align: 'center', width: '100px', render: (row: any, record: any) => ( <div>{renderDateStringYear(record?.updated_at, '-')}</div> ), }, { title: 'Hành động', key: 'action', align: 'center', width: 100, fixed: 'right', render: (_: any, record: any) => ( <Space className="flex justify-center items-center"> <Link to={`${URL.ADMIN_BLOG}/view/${record.id}`}> <Button className="flex items-center justify-center border-none" icon={<img src={IconView} width={30} height={17} />} ></Button> </Link> <Link to={`${URL.ADMIN_BLOG}/edit/${record.id}`}> <Button className="flex items-center justify-center border-none" icon={<img src={IconEdit} width={22} height={20} />} ></Button> </Link> </Space> ), }, ] const rowSelection = { onChange: (selectedRowKeys: any) => { setSelectedRowKeys(selectedRowKeys) }, } return ( <div className={style.disableRrowTableCheckbox}> <ConfigProvider theme={{ token: { // controlOutline: 'rgba(5, 145, 255, 0.1)', colorPrimary: '#1677ff', }, components: { Table: { rowSelectedBg: '#e6f4ff', rowSelectedHoverBg: '#bae0ff', rowHoverBg: '#e6e6e6', }, }, }} > <Table className={style.disableRrowTableCheckbox} rowSelection={rowSelection} columns={columns as any} dataSource={listBlog} scroll={{ x: 1200, y: 430 }} pagination={false} rowKey="id" rowClassName={style.removeRowSelected} bordered loading={loading} // refetch={refetch} /> </ConfigProvider> </div> ) } export default memo(TableListBlog)
import React from "react"; import { screen } from "@testing-library/react"; import { createMockPopularItem } from "metabase-types/api/mocks"; import { renderWithProviders } from "__support__/ui"; import { setupPopularItemsEndpoints } from "__support__/server-mocks"; import { PopularItem } from "metabase-types/api"; import HomePopularSection from "./HomePopularSection"; const setup = (items: PopularItem[]) => { setupPopularItemsEndpoints(items); renderWithProviders(<HomePopularSection />); }; describe("HomePopularSection", () => { it("should render a list of items of the same type", async () => { setup([ createMockPopularItem({ model: "dashboard", model_object: { name: "Metrics", }, }), createMockPopularItem({ model: "dashboard", model_object: { name: "Revenue", }, }), ]); expect(await screen.findByText(/popular dashboards/)).toBeInTheDocument(); }); it("should render a list of items of different types", async () => { setup([ createMockPopularItem({ model: "dashboard", model_object: { name: "Metrics", }, }), createMockPopularItem({ model: "card", model_object: { name: "Revenue", }, }), ]); expect(await screen.findByText(/popular items/)).toBeInTheDocument(); }); });
<?php /** * The template for displaying all single posts * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post * * @package cyt */ get_header(); ?> <div class="site-wrapper"> <div class="row justify-content-center"> <main id="main" class="single"> <?php while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_type() ); the_post_navigation( array( 'prev_text' => '<span class="nav-subtitle">' . esc_html__( 'Previous:', 'cyt' ) . '</span> <span class="nav-title">%title</span>', 'next_text' => '<span class="nav-subtitle">' . esc_html__( 'Next:', 'cyt' ) . '</span> <span class="nav-title">%title</span>', ) ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. ?> </main><!-- #main --> <?php get_sidebar(); ?> </div> </div> <?php get_footer(); ?>