text
stringlengths
184
4.48M
package com.llmcu.imooc.mybatisplus.basic.environment.mapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.llmcu.imooc.mybatisplus.basic.environment.entity.SysUser; import com.llmcu.imooc.mybatisplus.basic.environment.entity.SysUser2; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import java.util.*; @SpringBootTest @Transactional public class SysUserMapperDeleteTest { @Autowired private SysUserMapper sysUserMapper; @Autowired private SysUserMapper2 sysUserMapper2; /** * 如果id不存在,deleteById返回结果为0,表示影响了0条记录 */ @Test @Rollback public void deleteById() { int i = sysUserMapper.deleteById(new SysUser().setId(9L)); Assertions.assertEquals(0,i); sysUserMapper.selectList(null).forEach(System.out::println); } /** * 只有deleteById会自动填充更新时间,自动填充内容由该方法入参实体获取,后续可由MyMetaObjectHandler覆盖 */ @Test @Rollback public void deleteById2() { int i = sysUserMapper2.deleteById(new SysUser2().setId(9L).setUpdateTime(new Date())); Assertions.assertEquals(0,i); sysUserMapper.selectList(null).forEach(System.out::println); } /** * DELETE FROM sys_user WHERE (name = ? AND id = ?) */ @Test @Rollback public void deleteByMap() { Map<String,Object> map = new HashMap<>(); map.put("id",1L); map.put("name","Jone"); int i = sysUserMapper.deleteByMap(map); Assertions.assertEquals(1,i); } /** * deleteByMap不会自动填充,因为map只会影响where中的条件,哪怕开启MyMetaObjectHandler * UPDATE sys_user2 SET deleted=1 WHERE deleted=0 AND (name = ? AND id = ?) */ @Test @Rollback public void deleteByMap2() { Map<String,Object> map = new HashMap<>(); map.put("id",1L); map.put("name","Jone"); int i = sysUserMapper2.deleteByMap(map); Assertions.assertEquals(1,i); } @Test @Rollback public void deleteByQueryWrapper() { int delete = sysUserMapper.delete(Wrappers.<SysUser>lambdaQuery().between(SysUser::getId, 1L, 3L)); Assertions.assertEquals(3,delete); } /** * deleteByQueryWrapper也不会自动填充,因为wrapper只会影响where中的条件,哪怕开启MyMetaObjectHandler * UPDATE sys_user2 SET deleted=1 WHERE deleted=0 AND (id BETWEEN ? AND ?) */ @Test @Rollback public void deleteByQueryWrapper2() { int delete = sysUserMapper2.delete(Wrappers.<SysUser2>lambdaQuery().between(SysUser2::getId, 1L, 3L)); Assertions.assertEquals(3,delete); } /** * 用updateWrapper也无防,只不过方法参数名为queryWrapper */ @Test @Rollback public void deleteByUpdateWrapper() { int delete = sysUserMapper.delete(Wrappers.<SysUser>lambdaUpdate().between(SysUser::getId, 1L, 3L)); Assertions.assertEquals(3,delete); } @Test @Rollback public void deleteByUpdateWrapper2() { // int delete = sysUserMapper2.delete(Wrappers.<SysUser2>lambdaUpdate().between(SysUser2::getId, 1L, 3L)); int delete = sysUserMapper2.delete(Wrappers.lambdaUpdate(new SysUser2()).between(SysUser2::getId, 1L, 3L)); Assertions.assertEquals(3,delete); } /** * DELETE FROM sys_user WHERE id IN ( ? , ? ) */ @Test @Rollback public void deleteBatchIds() { int i = sysUserMapper.deleteBatchIds(Arrays.asList(1L, 2L)); Assertions.assertEquals(2,i); } /** * deleteBatchIds也不会自动填充,哪怕开启MyMetaObjectHandler */ @Test @Rollback public void deleteBatchIds2() { int i = sysUserMapper2.deleteBatchIds(Arrays.asList(1L, 2L)); Assertions.assertEquals(2,i); } }
package project2 import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.sql.SparkSession import org.apache.spark.sql.Row import org.apache.spark.sql.types._ import org.apache.spark.sql.functions._ import scala.io.Source object obj13 { def main (args:Array[String]): Unit={ println("====started=====") println("====started=====") val conf = new SparkConf().setAppName("first").setMaster("local[*]") val sc = new SparkContext(conf) sc.setLogLevel("ERROR") val spark = SparkSession .builder() .config(conf) .getOrCreate() import spark.implicits._ val html = Source.fromURL("https://randomuser.me/api/0.8/?results=5") val urldata= html.mkString println(urldata) // url datafetch val rdd = sc.parallelize(List(urldata)) // rdd conversion val df = spark.read.json(rdd) // dataframe conversion df.show() df.printSchema() val flattendf = df.withColumn("results",explode(col("results"))) val flattendf2= flattendf.select( col("nationality"), col("results.user.cell"), col("results.user.dob"), col("results.user.email"), col("results.user.gender"), col("results.user.location.*"), col("results.user.md5"), col("results.user.name.*"), col("results.user.password"), col("results.user.phone"), col("results.user.picture.*"), col("results.user.registered"), col("results.user.salt"), col("results.user.sha1"), col("results.user.sha256"), col("results.user.username"), col("seed"), col("version") ) flattendf2.show(false) flattendf2.printSchema() flattendf2.write.format("csv").option("header","true").partitionBy("nationality") .mode("append").save("file:///C:/data/urldata1") } }
<?php namespace App\Repositories\FinancialDeposit; use App\Http\Requests\FinancialDeposit\FinancialDepositRequest; use App\Models\FinancialDeposit; use Exception; use Illuminate\Database\Eloquent\Collection; class FinancialDepositRepository implements FinancialDepositRepositoryInterface { /** * Construct function * * @param FinancialDeposit $financialDeposit */ public function __construct( protected FinancialDeposit $model ) {} /** * Get deposits function * * @param integer $walletId * @return Collection */ public function get(int $walletId): Collection { return $this->model->where('wallet_id', $walletId)->get(); } /** * Deposit to wallet function * * @param FinancialDepositRequest $request * @return FinancialDeposit|Exception */ public function deposit(FinancialDepositRequest $request): FinancialDeposit|Exception { try { return $this->model->create( [ 'wallet_id' => $request?->wallet_id, 'value' => $request?->value, 'status' => FinancialDeposit::STATUS_WAITING, ] ); } catch (\Exception $e) { return $e; } } /** * Update to completed status function * * @param integer $id * @return boolean */ public function updateCompleted(int $id): FinancialDeposit { $get = $this->model->find($id); $get->status = FinancialDeposit::STATUS_COMPLETED; $get->save(); return $get; } /** * Update to failed status function * * @param integer $id * @return boolean */ public function updateFailed(int $id): FinancialDeposit { $get = $this->model->find($id); $get->status = FinancialDeposit::STATUS_FAILED; $get->save(); return $get; } }
<ion-header> <ion-navbar color="primary"> <ion-title>LIB HUNTER</ion-title> </ion-navbar> </ion-header> <ion-content padding> <div class="search-area"> <ion-toolbar> <ion-searchbar [(ngModel)]="search" animated mode="ios" color="tertiary" placeholder="Pesquisar livros e prod. acadêmicas"> </ion-searchbar> </ion-toolbar> <ion-item> <ion-label>Documento</ion-label> <ion-select [(ngModel)]="filtro" okText="OK" cancelText="Cancelar"> <ion-option [value]="1" selected>Todos</ion-option> <ion-option [value]="2">Título</ion-option> <ion-option [value]="3">Autor</ion-option> <ion-option [value]="4">Assunto</ion-option> </ion-select> </ion-item> <button class="searchbtn" ion-button (click)="getSearch()"> Pesquisar </button> </div> <div id="result" *ngIf="documentos.length > 0"> <ion-scroll scrollY="true"> <ion-list> <ion-item *ngFor="let documento of documentos"> <div class="doc"> <h1 class="titulo">{{documento.titulo}}</h1> <span class="autor">{{documento.autor}}</span> <span class="assunto">{{documento.assunto}}</span> <span class="distarnce">{{documento.biblioteca.distance | number:'1.0-0' }}m</span> </div> <button (click)="presentDetailsModal(documento)" ion-button color="primary">Ver</button> </ion-item> </ion-list> </ion-scroll> </div> <button class="mapButon" ion-button block (click)="presentMapModal()"> Ver Mapa </button> </ion-content>
use std::{env, fs::{self, File}, io::{Read, Write}, net::TcpStream, path::{Path, PathBuf}}; use serde::Serialize; use ssh2::Session; use tauri::{api::path::download_dir, command, AppHandle, Manager}; use zip::{write::FileOptions, ZipWriter}; use chrono::Utc; /// Struct to represent a file on the Raspberry Pi. #[derive(Debug, Serialize)] pub struct FileInfo { pub name: String, pub file_type: String, pub size: u64, pub last_modified: String, } const CHUNK_SIZE: usize = 1 * 1024 * 1024; // 1MB // Commands for SSH connection /// Uses a .env file to load the IP address, username, and password of the Raspberry Pi. /// /// * `Input`: User's name and optional path /// * `Output`: List of files in the specified directory on the Raspberry Pi #[command] pub async fn connect_to_pi(user_name: String, path: Option<String>) -> Result<Vec<FileInfo>, String> { let mut session = get_ssh_session().await?; let home_dir = get_home_directory(&mut session)?; let base_dir = verify_base_directory(&mut session, &home_dir)?; let remote_dir = create_user_directory(&mut session, &base_dir, &user_name)?; let target_dir = if let Some(path) = path { format!("{}/{}", remote_dir, path) } else { remote_dir }; let files = list_files_in_directory(&mut session, &target_dir)?; Ok(files) } /// Command called by the frontend to get the file sizes of the specified files on the Raspberry Pi. /// /// * `Input`: List of file paths /// * `Output`: List of file sizes in bytes #[command] pub async fn get_file_sizes(file_paths: Vec<String>) -> Result<Vec<u64>, String> { let mut file_sizes = Vec::new(); for path in file_paths { let metadata = fs::metadata(&path).map_err(|e| format!("Failed to get metadata for {}: {}", path, e))?; file_sizes.push(metadata.len()); } Ok(file_sizes) } /// Command called by the frontend to download files from the Raspberry Pi. /// Uses a .env file to load the IP address, username, and password of the Raspberry Pi. /// Downloads the file to the user's Downloads directory in chunks to prevent memory issues. /// /// * `Input`: User's name, current path, file names, and app handle for emitting events /// * `Output`: None #[command] pub async fn download_files(user_name: String, current_path: Vec<String>, file_names: Vec<String>, app_handle: AppHandle) -> Result<(), String> { let (mut session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; if file_names.len() == 1 { let file_name = &file_names[0]; let remote_file_path = format!("{}/{}", current_remote_dir, file_name); let file_stat = sftp.stat(Path::new(&remote_file_path)) .map_err(|e| format!("Failed to stat remote file '{}': {}", remote_file_path, e))?; if file_stat.is_file() { // Download single file directly let local_file_path = download_single_file(&mut session, &remote_file_path, &app_handle)?; println!("File downloaded to: {}", local_file_path.display()); } else if file_stat.is_dir() { // Download single directory as zip download_files_as_zip(&mut session, &current_remote_dir, vec![file_name.clone()], &app_handle)?; } } else { // Download multiple files as zip download_files_as_zip(&mut session, &current_remote_dir, file_names, &app_handle)?; } Ok(()) } /// Command called by the frontend to upload files to the Raspberry Pi. /// * `Input`: User's name, current path, local file paths, and app handle for emitting events /// * `Output`: None #[command] pub async fn upload_files(user_name: String, current_path: Vec<String>, local_file_paths: Vec<String>, app_handle: AppHandle) -> Result<(), String> { let (mut session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; for local_file_path in local_file_paths { let file_name = Path::new(&local_file_path).file_name().unwrap().to_str().unwrap(); let remote_file_path = format!("{}/{}", current_remote_dir, file_name); upload_file_in_chunks(&mut session, &remote_file_path, Path::new(&local_file_path), &app_handle)?; } Ok(()) } /// Command to create a new folder in the current directory. /// * `Input`: User's name, current path, folder name /// * `Output`: None #[command] pub async fn create_folder(user_name: String, current_path: Vec<String>, folder_name: String) -> Result<(), String> { let (session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let remote_folder_path = format!("{}/{}", current_remote_dir, folder_name); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; sftp.mkdir(Path::new(&remote_folder_path), 0o755).map_err(|e| format!("Failed to create folder '{}': {}", remote_folder_path, e))?; Ok(()) } /// Command to rename a file or folder in the current directory. /// * `Input`: User's name, current path, old name, new name /// * `Output`: None #[command] pub async fn rename_file(user_name: String, current_path: Vec<String>, old_name: String, new_name: String) -> Result<(), String> { let (session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let old_file_path = format!("{}/{}", current_remote_dir, old_name); let new_file_path = format!("{}/{}", current_remote_dir, new_name); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; sftp.rename(Path::new(&old_file_path), Path::new(&new_file_path), None) .map_err(|e| format!("Failed to rename '{}': {}", old_file_path, e))?; Ok(()) } /// Command to delete files or folders in the current directory. /// * `Input`: User's name, current path, file names /// * `Output`: None #[command] pub async fn delete_files(user_name: String, current_path: Vec<String>, file_names: Vec<String>) -> Result<(), String> { let (session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; for file_name in file_names { let remote_file_path = format!("{}/{}", current_remote_dir, file_name); let path = Path::new(&remote_file_path); if sftp.stat(path).map_err(|e| format!("Failed to stat '{}': {}", remote_file_path, e))?.is_dir() { recursive_delete(&sftp, path)?; } else { sftp.unlink(path).map_err(|e| format!("Failed to delete file '{}': {}", remote_file_path, e))?; } } Ok(()) } /// Command to read the content of a file. /// * `Input`: User's name, current path, file name /// * `Output`: File content as a string #[command] pub async fn read_file(user_name: String, current_path: Vec<String>, file_name: String) -> Result<String, String> { let (session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let remote_file_path = format!("{}/{}", current_remote_dir, file_name); let path = Path::new(&remote_file_path); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let mut remote_file = sftp.open(path).map_err(|e| format!("Failed to open file '{}': {}", remote_file_path, e))?; let mut contents = String::new(); remote_file.read_to_string(&mut contents).map_err(|e| format!("Failed to read file '{}': {}", remote_file_path, e))?; Ok(contents) } /// Command to save the content to a file. /// * `Input`: User's name, current path, file name, file content /// * `Output`: None #[command] pub async fn save_file(user_name: String, current_path: Vec<String>, file_name: String, file_content: String) -> Result<(), String> { let (session, _, current_remote_dir) = get_remote_dirs_and_session(user_name, current_path).await?; let remote_file_path = format!("{}/{}", current_remote_dir, file_name); let path = Path::new(&remote_file_path); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let mut remote_file = sftp.create(path).map_err(|e| format!("Failed to create file '{}': {}", remote_file_path, e))?; remote_file.write_all(file_content.as_bytes()).map_err(|e| format!("Failed to write to file '{}': {}", remote_file_path, e))?; Ok(()) } /// Command to get the storage used by the user in the base remote directory. /// * `Input`: User's name /// * `Output`: Storage used in bytes #[command] pub async fn get_storage_used(user_name: String) -> Result<u64, String> { let mut session = get_ssh_session().await?; let home_dir = get_home_directory(&mut session)?; let remote_dir = format!("{}/{}/{}", home_dir, "pi-interface", user_name); let mut channel = session.channel_session().map_err(|e| format!("Failed to open channel: {}", e))?; channel.exec(&format!("du -sb \"{}\"", remote_dir)).map_err(|e| format!("Failed to execute command: {}", e))?; let mut s = String::new(); channel.read_to_string(&mut s).map_err(|e| format!("Failed to read from channel: {}", e))?; channel.close().map_err(|e| format!("Failed to close channel: {}", e))?; channel.wait_close().map_err(|e| format!("Failed to wait for channel close: {}", e))?; let parts: Vec<&str> = s.split_whitespace().collect(); if parts.len() < 1 { return Err("Unexpected output from du command".to_string()); } let size: u64 = parts[0].parse().map_err(|e| format!("Failed to parse size: {}", e))?; Ok(size) } // Helper functions for SSH connection /// Gets the remote directories and session for the user. /// /// * `Input`: User's name and current path /// * `Output`: SSH session, remote directory, and current remote directory pub async fn get_remote_dirs_and_session(user_name: String, current_path: Vec<String>) -> Result<(Session, String, String), String> { let mut session = get_ssh_session().await?; let home_dir = get_home_directory(&mut session)?; let remote_dir = format!("{}/{}/{}", home_dir, "pi-interface", user_name); let current_remote_dir = if current_path.is_empty() { remote_dir.clone() } else { format!("{}/{}", remote_dir, current_path.join("/")) }; Ok((session, remote_dir, current_remote_dir)) } /// Gets an SSH session with the Raspberry Pi. /// /// * `Output`: SSH session pub async fn get_ssh_session() -> Result<Session, String> { dotenv::dotenv().ok(); // Load environment variables let pi_ip = env::var("VITE_PI_IP").map_err(|e| format!("Failed to load VITE_PI_IP: {}", e))?; let pi_username = env::var("VITE_PI_USERNAME").map_err(|e| format!("Failed to load VITE_PI_USERNAME: {}", e))?; let pi_password = env::var("VITE_PI_PASSWORD").map_err(|e| format!("Failed to load VITE_PI_PASSWORD: {}", e))?; let session = establish_ssh_session(pi_ip, pi_username, pi_password)?; Ok(session) } /// Establishes an SSH session with the Raspberry Pi. /// /// * `Input`: IP address, username, and password of the Raspberry Pi /// * `Output`: SSH session fn establish_ssh_session(pi_ip: String, pi_username: String, pi_password: String) -> Result<Session, String> { let mut attempts = 0; loop { let tcp = TcpStream::connect(format!("{}:22", pi_ip)).map_err(|e| format!("Failed to connect to {}:22: {}", pi_ip, e)); let session = Session::new().map_err(|e| format!("Failed to create SSH session: {}", e)); if let (Ok(tcp), Ok(mut session)) = (tcp, session) { session.set_tcp_stream(tcp); if let Ok(_) = session.handshake() { if let Ok(_) = session.userauth_password(&pi_username, &pi_password) { if session.authenticated() { return Ok(session); } } } } attempts += 1; if attempts >= 3 { // Retry 3 times before giving up return Err("Authentication failed".into()); } } } /// Gets the home directory of the Raspberry Pi. /// /// * `Input`: SSH session /// * `Output`: Home directory fn get_home_directory(session: &mut Session) -> Result<String, String> { let mut channel = session.channel_session().map_err(|e| format!("Failed to create channel session: {}", e))?; channel.exec("echo $HOME").map_err(|e| format!("Failed to execute command to get home directory: {}", e))?; let mut home_dir = String::new(); channel.read_to_string(&mut home_dir).map_err(|e| format!("Failed to read home directory: {}", e))?; channel.wait_close().map_err(|e| format!("Failed to close channel: {}", e))?; let exit_status = channel.exit_status().map_err(|e| format!("Failed to get exit status: {}", e))?; if exit_status != 0 { return Err(format!("Command to get home directory failed with exit status: {}", exit_status)); } Ok(home_dir.trim().to_string()) // Remove any trailing newline or whitespace } /// Verifies the existence of the base directory on the Raspberry Pi. /// If the base directory does not exist, it is created. /// /// * `Input`: SSH session and home directory /// * `Output`: Base directory fn verify_base_directory(session: &mut Session, home_dir: &str) -> Result<String, String> { let base_dir = format!("{}/pi-interface", home_dir); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; if sftp.stat(Path::new(&base_dir)).is_err() { sftp.mkdir(Path::new(&base_dir), 0o755).map_err(|e| format!("Failed to create base directory {}: {}", base_dir, e))?; } Ok(base_dir) } /// Creates a directory for the user on the Raspberry Pi. /// /// * `Input`: SSH session, base directory, and user's name /// * `Output`: User's directory fn create_user_directory(session: &mut Session, base_dir: &str, user_name: &str) -> Result<String, String> { let remote_dir = format!("{}/{}", base_dir, user_name); let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; if sftp.stat(Path::new(&remote_dir)).is_err() { sftp.mkdir(Path::new(&remote_dir), 0o755).map_err(|e| format!("Failed to create user directory {}: {}", remote_dir, e))?; } Ok(remote_dir) } /// Lists the files in a directory on the Raspberry Pi. /// /// * `Input`: SSH session and directory /// * `Output`: List of files in the directory fn list_files_in_directory(session: &mut Session, remote_dir: &str) -> Result<Vec<FileInfo>, String> { let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let mut files = vec![]; let entries = sftp.readdir(Path::new(remote_dir)).map_err(|e| format!("Failed to read directory {}: {}", remote_dir, e))?; for (path, stat) in entries { if let Some(file_name) = path.file_name() { let file_type = if stat.is_file() { path.extension() .map_or_else(|| "Unknown".to_string(), |ext| ext.to_string_lossy().into_owned()) } else { "Folder".to_string() }; files.push(FileInfo { name: file_name.to_string_lossy().to_string(), file_type, size: stat.size.unwrap_or(0), last_modified: stat.mtime.unwrap_or(0).to_string(), }); } } Ok(files) } /// Downloads a single file from the Raspberry Pi. /// /// * `Input`: SSH session, remote file path, and app handle for emitting events /// * `Output`: Local file path fn download_single_file(session: &mut Session, remote_file_path: &str, app_handle: &AppHandle) -> Result<PathBuf, String> { let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let file_stat = sftp.stat(Path::new(remote_file_path)) .map_err(|e| format!("Failed to stat remote file '{}': {}", remote_file_path, e))?; let total_size = file_stat.size.ok_or("Failed to get file size")?; app_handle.emit_all("total-size", total_size).unwrap(); let mut remote_file = sftp.open(Path::new(remote_file_path)) .map_err(|e| format!("Failed to open remote file '{}': {}", remote_file_path, e))?; let downloads_dir = download_dir().ok_or("Failed to find the Downloads directory")?; let local_file_path = downloads_dir.join(Path::new(remote_file_path).file_name().unwrap()); let mut local_file = File::create(&local_file_path) .map_err(|e| format!("Failed to create local file at '{}': {}", local_file_path.display(), e))?; let mut buffer = [0; CHUNK_SIZE]; // Buffer for holding file chunks let mut total_bytes_read = 0; while let Ok(n) = remote_file.read(&mut buffer) { if n == 0 { break; } local_file.write_all(&buffer[..n]) .map_err(|e| format!("Failed to write to local file at '{}': {}", local_file_path.display(), e))?; total_bytes_read += n as u64; // Emit progress event app_handle.emit_all("download-progress", total_bytes_read).unwrap(); } remote_file.close().map_err(|e| format!("Failed to close remote file '{}': {}", remote_file_path, e))?; local_file.flush().map_err(|e| format!("Failed to flush local file at '{}': {}", local_file_path.display(), e))?; Ok(local_file_path) } /// Downloads multiple files from the Raspberry Pi as a zip file. /// /// * `Input`: SSH session, remote directory, list of file names, and app handle for emitting events /// * `Output`: None fn download_files_as_zip(session: &mut Session, remote_dir: &str, file_names: Vec<String>, app_handle: &AppHandle) -> Result<(), String> { let tmp_dir = tempfile::tempdir().map_err(|e| format!("Failed to create temporary directory: {}", e))?; let zip_path = tmp_dir.path().join("files.zip"); let zip_file = File::create(&zip_path).map_err(|e| format!("Failed to create zip file: {}", e))?; let mut zip = ZipWriter::new(zip_file); // Calculate total size let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let mut total_size = 0; for file_name in &file_names { let remote_file_path = format!("{}/{}", remote_dir, file_name); let file_stat = sftp.stat(Path::new(&remote_file_path)) .map_err(|e| format!("Failed to stat remote file '{}': {}", remote_file_path, e))?; total_size += file_stat.size.unwrap_or(0); } app_handle.emit_all("total-size", total_size).unwrap(); for file_name in file_names { let remote_file_path = format!("{}/{}", remote_dir, file_name); let file_stat = sftp.stat(Path::new(&remote_file_path)) .map_err(|e| format!("Failed to stat remote file '{}': {}", remote_file_path, e))?; if file_stat.is_file() { add_file_to_zip(session, &mut zip, &remote_file_path, &file_name, app_handle)?; } else if file_stat.is_dir() { add_directory_to_zip(session, &mut zip, &remote_file_path, &file_name, app_handle)?; } } zip.finish().map_err(|e| format!("Failed to finalize zip file: {}", e))?; let downloads_dir = download_dir().ok_or("Failed to find the Downloads directory")?; let now = Utc::now(); let filename = format!("downloaded_files_{}.zip", now.format("%Y%m%d%H%M%S")); let local_zip_path = downloads_dir.join(filename); fs::rename(zip_path, &local_zip_path).map_err(|e| format!("Failed to move zip file to Downloads: {}", e))?; tmp_dir.close().map_err(|e| format!("Failed to clean up temporary files: {}", e))?; Ok(()) } /// Adds a file to the zip archive. /// /// * `Input`: SSH session, zip writer, remote file path, and file name /// * `Output`: None fn add_file_to_zip(session: &mut Session, zip: &mut ZipWriter<File>, remote_file_path: &str, file_name: &str, app_handle: &AppHandle) -> Result<(), String> { let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let file_stat = sftp.stat(Path::new(remote_file_path)) .map_err(|e| format!("Failed to stat remote file '{}': {}", remote_file_path, e))?; let total_size = file_stat.size.ok_or("Failed to get file size")?; app_handle.emit_all("total-size", total_size).unwrap(); let mut remote_file = sftp.open(Path::new(remote_file_path)) .map_err(|e| format!("Failed to open remote file '{}': {}", remote_file_path, e))?; zip.start_file::<&str, (), &str>(file_name, FileOptions::default()) .map_err(|e| format!("Failed to add file to zip: {}", e))?; let mut buffer = [0; CHUNK_SIZE]; // Buffer for holding file chunks let mut total_bytes_read = 0; while let Ok(n) = remote_file.read(&mut buffer) { if n == 0 { break; } zip.write_all(&buffer[..n]) .map_err(|e| format!("Failed to write to zip: {}", e))?; total_bytes_read += n as u64; // Emit progress event app_handle.emit_all("zip-progress", total_bytes_read).unwrap(); } Ok(()) } /// Adds a directory and its contents to the zip archive. /// /// * `Input`: SSH session, zip writer, remote directory path, and directory name /// * `Output`: None fn add_directory_to_zip(session: &mut Session, zip: &mut ZipWriter<File>, remote_dir_path: &str, dir_name: &str, app_handle: &AppHandle) -> Result<(), String> { let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let entries = sftp.readdir(Path::new(remote_dir_path)) .map_err(|e| format!("Failed to read directory '{}': {}", remote_dir_path, e))?; // Calculate total size of the directory let total_size: u64 = entries.iter().map(|(_, stat)| stat.size.unwrap_or(0)).sum(); app_handle.emit_all("total-size", total_size).unwrap(); for (path, stat) in entries { let file_name = path.file_name().ok_or_else(|| format!("Failed to get file name in directory '{}'", remote_dir_path))? .to_string_lossy().to_string(); let full_remote_path = format!("{}/{}", remote_dir_path, file_name); let zip_file_name = format!("{}/{}", dir_name, file_name); if stat.is_file() { add_file_to_zip(session, zip, &full_remote_path, &zip_file_name, app_handle)?; } else if stat.is_dir() { add_directory_to_zip(session, zip, &full_remote_path, &zip_file_name, app_handle)?; } } Ok(()) } /// Uploads a file to the Raspberry Pi in chunks to avoid memory issues. /// * `Input`: SSH session, remote file path, local file path, and app handle for emitting events /// * `Output`: None fn upload_file_in_chunks(session: &mut Session, remote_file_path: &str, local_file_path: &Path, app_handle: &AppHandle) -> Result<(), String> { let sftp = session.sftp().map_err(|e| format!("Failed to create SFTP session: {}", e))?; let mut remote_file = sftp.create(Path::new(remote_file_path)) .map_err(|e| format!("Failed to create remote file '{}': {}", remote_file_path, e))?; let mut local_file = File::open(local_file_path) .map_err(|e| format!("Failed to open local file '{}': {}", local_file_path.display(), e))?; let file_size = local_file.metadata().map_err(|e| format!("Failed to get file metadata '{}': {}", local_file_path.display(), e))?.len(); app_handle.emit_all("total-size", file_size).unwrap(); let mut buffer = vec![0; CHUNK_SIZE]; let mut total_bytes_written = 0; loop { let n = local_file.read(&mut buffer).map_err(|e| format!("Failed to read from local file '{}': {}", local_file_path.display(), e))?; if n == 0 { break; } remote_file.write_all(&buffer[..n]) .map_err(|e| format!("Failed to write to remote file '{}': {}", remote_file_path, e))?; total_bytes_written += n as u64; app_handle.emit_all("upload-progress", total_bytes_written).unwrap(); } remote_file.close().map_err(|e| format!("Failed to close remote file '{}': {}", remote_file_path, e))?; Ok(()) } /// Recursively delete a directory and its contents. /// /// * `Input`: SFTP session and directory path /// * `Output`: None fn recursive_delete(sftp: &ssh2::Sftp, path: &Path) -> Result<(), String> { let entries = sftp.readdir(path).map_err(|e| format!("Failed to read directory '{}': {}", path.display(), e))?; for (entry_path, _) in entries { if sftp.stat(&entry_path).map_err(|e| format!("Failed to stat '{}': {}", entry_path.display(), e))?.is_dir() { recursive_delete(sftp, &entry_path)?; } else { sftp.unlink(&entry_path).map_err(|e| format!("Failed to delete file '{}': {}", entry_path.display(), e))?; } } sftp.rmdir(path).map_err(|e| format!("Failed to delete directory '{}': {}", path.display(), e))?; Ok(()) }
package com.harana.modules.stripe import com.outr.stripe.dispute.{Dispute, DisputeEvidence} import com.outr.stripe.{QueryConfig, ResponseError, StripeList, TimestampFilter} import zio.macros.accessible import zio.{Has, IO} @accessible object StripeDisputes { type StripeDisputes = Has[StripeDisputes.Service] trait Service { def byId(disputeId: String): IO[ResponseError, Dispute] def update(disputeId: String, evidence: Option[DisputeEvidence] = None, metadata: Map[String, String]): IO[ResponseError, Dispute] def close(disputeId: String): IO[ResponseError, Dispute] def list(created: Option[TimestampFilter] = None, config: QueryConfig = QueryConfig.default): IO[ResponseError, StripeList[Dispute]] } }
## 这里提供一种STL的写法 看到大多数是O(n^2)的打法,也有很多直接写二分的,但是表忘了还有两个叫做upper_bound()和lower_bound()的东西。 这道题目首先就应该想到要把长度进行排序,然后再继续处理重量,这样子其实就是在长度单调的时候,寻找重量上需要多长时间。 poj好像和这里是反的,但没有关系,并不影响结果,因为分离出来的不下降子序列和不上升子序列的数量是一样的。 这里普及一个知识点,最长不降序列的数量 == 最长下降子序列的长度 原理可以自己手摸一下。。。 将长度从小到大排序,这样子就转化成了在重量上求不下降子序列数量的问题了; 这里dp[i]用来存长度为i的下降子序列最后一个元素的最大值,由于dp[i]是严格递减的,所以我们就可以用二分来更新最大值,找到最后一个小于等于当前重量的木棍,更新dp值,就可以通过查询最后一个没被更新的元素来判断最长下降子序列长度,也就是不降子序列的数量 == 耗费的时间。 ```cpp #include <set> #include <map> #include <stack> #include <queue> #include <cmath> #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #define ll long long #define fir first #define sec second #define rep(i,a,b) for(int i=a;i<=b;++i) #define per(i,a,b) for(int i=a;i>=b;--i) //懒人 using namespace std; pair<int, int> lw[5011]; //pair可以直接排序,很方便 int dp[5011]; int main() { int n; cin >> n; rep(i, 1, n) { cin >> lw[i].fir >> lw[i].sec; } sort(lw + 1, lw + 1 + n); //从小到大排序(poj上是从小到大) memset(dp, -1, sizeof dp); rep(i, 1, n) { *lower_bound(dp + 1, dp + n + 1, lw[i].sec, greater<int>()) = lw[i].sec; //找到最后一个小于等于当前重量的木棍,更新dp值 } cout << lower_bound(dp + 1, dp + n + 1, -1, greater<int>()) - dp - 1 << endl; return 0; } ``` 相当简洁的代码。 [导弹拦截](https://www.luogu.org/problem/P1020) 这是一道类似的题,没有写的可以去练练手 :)
import Tabs from './tabs/analytics.md' # Adobe Mobile Library (v4) to Experience Platform Analytics migration ## Configuration The Adobe Experience Platform Analytics extension uses [tags](https://experience.adobe.com/#/data-collection/) to configure the Experience Platform SDKs. This replaces the ADBMobileConfig.json which the Mobile Services SDK used for configuration. To get started with the AEP SDKs: 1. Create a mobile property on tags. <br/>See [Set up a mobile property](../../home/getting-started/create-a-mobile-property.md) for more information. 2. Configure your mobile app with the create mobile property.<br/>The AEP Mobile Core extension provides general functionality required by all the Adobe AEP extensions. The Configuration extension is built into the Mobile Core and contains the configureWithAppId API. This API is used to link the tag mobile property with your mobile app. The documentation for this API can be seen at the [Configuration API Reference](../../home/base/mobile-core/configuration/api-reference.md#configurewithappid) page. A code sample showing the usage of this API is provided below. 3. Once all the Platform extensions are imported and configured correctly, remove the v4 Mobile SDK dependency. <br/>This step is mandatory and a mix of v4 and AEP API calls is not supported. <TabsBlock orientation="horizontal" slots="heading, content" repeat="2"/> Android <Tabs query="platform=android&task=config"/> iOS <Tabs query="platform=ios&task=config"/> ## Analytics Migration Overview For an overview of the API mapping between the Mobile Services SDK and Adobe Experience Platform SDKs, see the [API Change Log](./api-changelog.md). This section describes the Analytics-specific changes made with the AEP Analytics extension. ### Deprecated API | API | Notes | |---|---| | trackActionFromBackground | Deprecated | | trackLocation:data: | This functionality is available in the [Places extension](../../solution/places/index.md). | | trackBeacon:Data: | Support modified. [See guide](../../solution/adobe-analytics/track-beacon.md). | | trackingClearCurrentBeacon | Support modified. [See guide](../../solution/adobe-analytics/track-beacon.md). | | trackLifetimeValueIncrease:data: | This functionality can be recreated using the [Analytics](../../solution/adobe-analytics/index.md) and [User Profile](../../home/base/profile/index.md) extensions. | | trackTimedActionStart: | This functionality can be recreated using the [Analytics](../../solution/adobe-analytics/index.md) and [User Profile](../../home/base/profile/index.md) extensions. | | trackTimedActionUpdate: | This functionality can be recreated using the [Analytics](../../solution/adobe-analytics/index.md) and [User Profile](../../home/base/profile/index.md) extensions. | | trackTimedActionEnd: | This functionality can be recreated using the [Analytics](../../solution/adobe-analytics/index.md) and [User Profile](../../home/base/profile/index.md) extensions. | | trackTimedActionExists: | This functionality can be recreated using the [Analytics](../../solution/adobe-analytics/index.md) and [User Profile](../../home/base/profile/index.md) extensions. | ## Experience Platform extensions installation and setup ### Register the extensions and link the app to the configuration created with Data Collection tags In your app's Application class add the mobile extension registration and configuration code: <TabsBlock orientation="horizontal" slots="heading, content" repeat="2"/> Android <Tabs query="platform=android&task=aep-install"/> iOS <Tabs query="platform=ios&task=aep-install"/> For more details, see [Add Analytics to your application](../../solution/adobe-analytics/index.md#add-analytics-to-your-application). ## API changes ### Track app states and actions #### Adobe Mobile Library (v4) <TabsBlock orientation="horizontal" slots="heading, content" repeat="2"/> Android <Tabs query="platform=android&task=api-changes-v4"/> iOS <Tabs query="platform=ios&task=api-changes-v4"/> #### Experience Platform Mobile SDKs <TabsBlock orientation="horizontal" slots="heading, content" repeat="2"/> Android <Tabs query="platform=android&task=api-changes-aep"/> iOS <Tabs query="platform=ios&task=api-changes-aep"/> ## Privacy status changes in the Experience Platform SDK The privacy APIs `setPrivacyStatus` and `getPrivacyStatus` can be found in the Mobile Core. Similar to the v4 SDK, the Analytics extension will follow these behaviors depending on the privacy status set: * **Opted in:** Analytics hits will be sent. * **Unknown:** Analytics hits will be queued. * **Opted out:** Analytics hits will be dropped. ### Experience Platform Mobile SDKs <TabsBlock orientation="horizontal" slots="heading, content" repeat="2"/> Android <Tabs query="platform=android&task=privacy-changes-aep"/> iOS <Tabs query="platform=ios&task=privacy-changes-aep"/>
import { ChronoUnit, LocalDate } from "@js-joda/core"; import { CycleWeek } from "./cycle-week"; import { Metadata } from "./metadata"; import { Requirements } from "./requirements"; export interface ICycle { id: number; title: string; alias: string; cycleStart: LocalDate; cycleEnd: LocalDate; cyclePreStart?: LocalDate; cyclePostEnd?: LocalDate; cycleWeekStart: number; requirements: Requirements; metadata?: Metadata; } export class Cycle implements ICycle { id: number; title: string; alias: string; cycleStart: LocalDate; cycleEnd: LocalDate; cyclePreStart?: LocalDate; cyclePostEnd?: LocalDate; cycleWeekStart: number; requirements: Requirements; metadata?: Metadata; constructor(cycle: ICycle) { this.id = cycle.id; this.title = cycle.title; this.alias = cycle.alias; this.cycleStart = cycle.cycleStart; this.cycleEnd = cycle.cycleEnd; this.cyclePreStart = cycle.cyclePreStart; this.cyclePostEnd = this.cyclePostEnd; this.cycleWeekStart = cycle.cycleWeekStart; this.requirements = cycle.requirements; this.metadata = cycle.metadata; console.log(`Cycle(${this.title}, ${this.cycleStart}, ${this.cycleEnd})`, this); } public get cycleWeeks(): number { return this.cycleStart.until(this.cycleEnd, ChronoUnit.WEEKS).valueOf(); } public get cycleWeek(): number { return this.cycleStart.until(LocalDate.now(), ChronoUnit.WEEKS).valueOf(); } public get cycleDays(): number { return this.cycleStart.until(this.cycleEnd.plusDays(1), ChronoUnit.DAYS).valueOf(); } public get cycleDay(): number { return this.cycleStart.until(LocalDate.now().plusDays(1), ChronoUnit.DAYS).valueOf(); } public get cycleDate(): LocalDate { return this.cycleStart.plusDays(this.cycleDay); } public get currentWeek(): number { return this.cycleStart.until(LocalDate.now(), ChronoUnit.WEEKS).valueOf(); } public get weekStarts(): LocalDate { return this.cycleStart.plusWeeks(this.currentWeek); } public get weekEnds(): LocalDate { return this.weekStarts.plusDays(6); } public validWeek(week?: number): number { return Math.min(Math.max(week || this.currentWeek, 0), this.cycleWeeks); } /** * Returns the week number of the cycle based on the passed CycleDate, LocalDate, week number or the current date (default). * * @param dateOrWeek * @returns */ public weekOf(dateOrWeek?: CycleWeek | LocalDate | string | number): number { const weekStart = (dateOrWeek instanceof CycleWeek) ? dateOrWeek.starts : (dateOrWeek instanceof LocalDate) ? dateOrWeek : this.cycleStart.plusWeeks(typeof(dateOrWeek) == 'string' ? parseInt(dateOrWeek || '0') : dateOrWeek || this.currentWeek); return this.cycleStart.until(weekStart, ChronoUnit.WEEKS).valueOf(); } public weekDaysOf(week?: string | number | null): CycleWeek { const weekStart = this.cycleStart.plusWeeks(typeof(week) == 'string' ? parseInt(week || '1') - 1 : week || this.currentWeek); return new CycleWeek({ days: Array(7).fill(LocalDate.now()).map((value, index) => weekStart.plusDays(index)) }); } public weekDays() { } public weekOfStarts(week?: number): LocalDate { return this.cycleStart.plusWeeks(week || this.currentWeek); } public weekOfEnds(week?: number): LocalDate { return this.cycleStart.plusWeeks(week || this.currentWeek).plusDays(6); } }
<template> <div :class="cn" :ph-progress="progress" :style="style"> <div class="ph-indicator-wrap"> <div class="ph-indicator" :style="transform"></div> </div> <circle-success type="success" class="ph-indicator-icon" v-if="status===1" /> <circle-danger type="danger" class="ph-indicator-icon" v-else-if="status===-1" /> <label v-else class="ph-progress-label">{{progress}}</label> </div> </template> <script lang="ts" setup> import { defineProps,computed,PropType } from 'vue' import { CircleSuccess,CircleDanger } from '../icon' const props = defineProps({ type:{type:String as PropType<'primary'|'success'|'info'|'warning'|'danger'>,default:"primary"}, value:{type:Number,default:0}, max:{type:Number,required:true}, animate:{type:Boolean,default:false}, striped:{type:Boolean,default:false}, strokeWidth:{type:Number,default:8}, format:{type:String,default:"v/m"/* % */}, fill:String,//填充的背景色 status:{type:Number,default:0}//1 success -1 error }) const m = computed(()=>{ return props.max; }) const v = computed(()=>{ return Math.max(0,props.value<m.value?props.value:m.value) }) const per = computed(()=>{ return v.value/m.value }) const style = computed(()=>{ const style = {} as Record<string,unknown> if(props.strokeWidth) style["--ph-pb-bh"]= props.strokeWidth+"px" if(props.fill) style['--ph-primary'] = props.fill return style }) const cn = computed(()=>{ let type = props.type||"primary" if(props.status===1)type = 'success' else if(props.status===-1)type= 'danger' const cns = ["ph-progress","ph-progress-bar","ph-progress-"+type] if(props.striped) cns.push("ph-progress-striped"); if(props.striped&&props.animate) cns.push("ph-progress-animate") return cns }) const transform = computed(()=>{ const v1 = (per.value-1)*100 return { transform:`translateX(${v1}%)` } }) const progress = computed(()=>{ if(props.format==="%") return (per.value*100).toFixed(0)+"%" return props.format.replace(/(v|m)/g,(a:string,b:string)=>{ return (b==="v"?v.value:m.value)+"" }) }) </script> <style lang="scss"> @import './progress.scss'; @keyframes phtransalways{ 0% {background-position-x: 50%;} 100% {background-position-x: 0%;} } .ph-progress-bar{ position: relative; flex-shrink: 0; height: 32px; display: flex; align-items: center; width: 100%; box-sizing: border-box; .ph-progress-label{ font-size: 12px; line-height: 22px; } .ph-progress-label, .ph-indicator-icon{ margin-left: 8px; } .ph-indicator-wrap{ flex:1; position: relative; height:var(--ph-pb-bh) ; overflow: hidden; border-radius: 10px; z-index: 2; background-color: var(--ph-progress-bg); } .ph-indicator{ transition: transform .3s linear; transform: translateX(-100%); border-radius: 10px; background-color: var(--ph-pb-indicator); } &.ph-progress-striped{ .ph-indicator:after{ content:""; position: absolute; border-radius: 10px; top:0; left:0px; bottom:0; right:1px; background-size: 20000% 100%; background-position-x: -10000%; background-image: repeating-linear-gradient(45deg,#FFFFFF33 0px,#FFFFFF33 10px,transparent 10px,transparent 20px); } } &.ph-progress-animate{ .ph-indicator:after{ animation: phtransalways 1000s linear infinite; } } } </style>
import { PublicKey } from "@solana/web3.js" // eslint-disable-line @typescript-eslint/no-unused-vars import BN from "bn.js" // eslint-disable-line @typescript-eslint/no-unused-vars import * as types from "../types" // eslint-disable-line @typescript-eslint/no-unused-vars import * as borsh from "@project-serum/borsh" export interface BalancedJSON { kind: "Balanced" } export class Balanced { static readonly discriminator = 0 static readonly kind = "Balanced" readonly discriminator = 0 readonly kind = "Balanced" toJSON(): BalancedJSON { return { kind: "Balanced", } } toEncodable() { return { Balanced: {}, } } } export interface UnbalancedJSON { kind: "Unbalanced" } export class Unbalanced { static readonly discriminator = 1 static readonly kind = "Unbalanced" readonly discriminator = 1 readonly kind = "Unbalanced" toJSON(): UnbalancedJSON { return { kind: "Unbalanced", } } toEncodable() { return { Unbalanced: {}, } } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function fromDecoded(obj: any): types.BalanceStatusKind { if (typeof obj !== "object") { throw new Error("Invalid enum object") } if ("Balanced" in obj) { return new Balanced() } if ("Unbalanced" in obj) { return new Unbalanced() } throw new Error("Invalid enum object") } export function fromJSON( obj: types.BalanceStatusJSON ): types.BalanceStatusKind { switch (obj.kind) { case "Balanced": { return new Balanced() } case "Unbalanced": { return new Unbalanced() } } } export function layout(property?: string) { const ret = borsh.rustEnum([ borsh.struct([], "Balanced"), borsh.struct([], "Unbalanced"), ]) if (property !== undefined) { return ret.replicate(property) } return ret }
import styled from "styled-components"; export const Body = styled.div` align-items: center; color: white; display: flex; flex-direction: column; font-size: calc(10px + 2vmin); justify-content: center; margin-top: 40px; `; interface ButtonProps { small?: boolean; borderless?: boolean; } export const Button = styled.button<ButtonProps>` background-color: ${p => p.borderless ? 'transparent' : 'white'}; border: ${p => p.borderless ? '0px' : '1px solid gray'}; border-radius: ${p => p.borderless ? 'none' : '8px'}; color: #282c34; cursor: pointer; font-size: 16px; margin: 0px 20px; padding: ${p => p.small ? '2px 4px' : '12px 24px'}; text-align: center; text-decoration: none; `; interface SelectorProps { isSelected: boolean; } export const Selector = styled(Button)<SelectorProps>` background-color: ${props => props.isSelected ? 'gray' : 'dark-gray'};}; `; export const Container = styled.div` background-color: #282c34; display: flex; flex-direction: column; height: calc(100vh); `; export const Header = styled.header` align-items: center; background-color: #282c34; color: white; display: flex; flex-direction: row; justify-content: space-between; min-height: 70px; `; export const Image = styled.img` height: 40vmin; margin-bottom: 16px; pointer-events: none; `; export const Link = styled.a.attrs({ target: "_blank", rel: "noopener noreferrer", })` color: #61dafb; text-decoration: underline; `; export const Item = styled.div` display: flex; justify-content: space-between; user-select: none; ` export const ItemContainer = styled.div` border: 1px solid white; border-radius: 10px; width: 90vw; max-width: 900px; padding: 10px; margin-top: 20px; ` export const ListContainer = styled.div` margin: 10px 10px 10px 50px; ` export const ListHeader = styled.div` display: flex; justify-content: space-between; margin: 10px; ` export const ListItem = styled.div` display: flex; justify-content: space-between; ` export const Flex = styled.div` display: flex; ` export const FlexAlignCenter = styled.div` display: flex; align-items: center; ` export const Label = styled.div` padding-right: 15px; ` export const Input = styled.input` ` export const Title = styled.h1` text-align: left; padding: 12px 24px; ` export const Indent = styled.div` width: 30px; height: 10px; margin-right: 10px; border-bottom: 1px solid white; border-left: 1px solid white; `
import { faker } from "@faker-js/faker"; import { Recommendation } from "@prisma/client"; import { prisma } from "../../src/database.js"; export type recommendationData = Omit<Recommendation, "id">; function createRecommendationData(id: number) : Recommendation { return { id, name: faker.lorem.words(3), youtubeLink: "https://www.youtube.com/watch?v=tMgi_Wlzgew", score: 0 } as Recommendation; } async function createRecommendation(){ const recommendation : recommendationData = { name: faker.lorem.words(3), youtubeLink: "https://www.youtube.com/watch?v=tMgi_Wlzgew", score: 0 }; return await prisma.recommendation.create({ data: recommendation }); } function createManyRecommendationData(limit : number ) { let recommendations: Recommendation[] = []; for (let i = 1; i <= limit; i++) { recommendations.push(createRecommendationData(i)); } return recommendations; } async function createManyRecommendation(limit : number ) { for (let i = 1; i <= limit; i++) { const recommendation : recommendationData = { name: faker.lorem.words(3), youtubeLink: "https://www.youtube.com/watch?v=tMgi_Wlzgew", score: parseInt(faker.random.numeric()) }; await prisma.recommendation.create({ data: recommendation }); } } const createRecommendationFactory = { createRecommendationData, createManyRecommendationData, createManyRecommendation, createRecommendation }; export default createRecommendationFactory;
$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" ); $(["p", "t"]).text("hello"); const tag = $( "ul li" ).addClass(function( index ) { return "item-" + index; }); $(tag).html(function (i: number) { console.log(this); return $(this).data('name') + '입니다'; }); // 타입에 대한 충돌이 생길 수 있기 때문에 네임스페이스로 묶어서 사용해준다. declare namespace Daeun { const a: string; } // Daeun.a interface zQuery<T> { text(param?: string | number | ((this: T, index: number) => string | number | boolean)): this; html(param: string | Document | DocumentFragment): void; } const $tag: zQuery<HTMLElement> = $(['p', 't']) as unknown as zQuery<HTMLElement>; $tag.text('123') $tag.text(123) $tag.text(function(index) { console.log(this, index); return true; }) $tag.text().html(document);
import React, { useEffect } from 'react' //сomponents import StackBlock from '../../components/StackBlock/StackBlock' import { LinearGradient } from 'react-text-gradients' import { motion, useAnimation } from 'framer-motion' //hooks import { useSelector } from 'react-redux' const infoStack = [ { name: 'HTML', time: '2 years', text: 'I am confident in my strong grasp of HTML. HTML is a fundamental language, and my proficiency with it has been instrumental in comprehending the core principles of web design and layout. It plays a pivotal role in structuring web content, and my deep understanding of HTML has empowered me in decomposing intricate designs.', }, { name: 'CSS', time: '2 years', text: 'CSS knowledge is indispensable in my journey, enabling me to breathe life into my web creations by crafting visually appealing and vibrant designs. Additionally, mastering CSS animations has enhanced my skills in creating engaging and dynamic web interfaces.', }, { name: 'JavaScript (JS)', time: '1.5 years', text: 'JS serves as the bedrock of my skill set. This versatile language has been a cornerstone in the development of user-friendly and captivating web applications. My proficiency in JS empowers me to bring interactive and responsive functionality to life, ensuring an enriched user experience.', }, { name: 'React.JS', time: '1 years', text: "My journey with React has been truly invigorating. This powerful library is the beating heart of modern web development, and my proficiency with it enables me to craft dynamic and responsive user interfaces. React's component-based architecture, combined with state management, has ushered me into the realm of interactive and state-of-the-art web applications.", }, { name: 'Redux | Redux TK', time: '1 years', text: "With a year of experience in Redux, I've harnessed the capabilities of this essential tool for state management. It empowers me to maintain global data consistency in complex applications, ensuring smooth interactions between components. My expertise in Redux is instrumental in delivering polished and efficient web solutions.", }, { name: 'SASS', time: '1 years', text: 'Sass has added a creative dimension to my styling journey. This preprocessor makes my stylesheets efficient, maintainable, and dynamic. It allows me to write clean and organized CSS code while employing advanced features like variables and mixins, thus streamlining the styling process.', }, { name: 'TailWind CSS', time: '0.5 years', text: "Tailwind CSS has been a recent but impactful addition to my toolkit. In just half a year of usage, it's become an integral part of my workflow. Its utility-first approach and customizable styling classes expedite the development process, resulting in stunning and highly maintainable user interfaces.", }, { name: 'Material UI', time: '0.5 years', text: "Material-UI offers an extensive set of ready-to-use components, enhancing my proficiency in web design. My half-year journey with MUI has honed my ability to create visually pleasing and intuitive interfaces. This library's elegant, material-inspired components have enriched my web applications with polished aesthetics.", }, { name: 'GIT', time: '1 years', text: 'My experience with Git extends over a year, and it plays an indispensable role in collaborative projects. Version control is crucial for maintaining code integrity and facilitating team collaboration. Git empowers me to track changes, manage code versions, and ensure a seamless development process.', }, { name: 'API Integration', time: '1 years', text: "With a year of experience in API integration, I've unlocked the potential of connecting web applications with external data sources. This proficiency allows me to build feature-rich and data-driven applications that interact seamlessly with external services.", }, ] const StackPage = () => { const activeIndex = useSelector(state => state.stackInfo?.activeIndex) const controls = useAnimation() const enterAnimation = { hidden: { y: 500, opacity: 0.2, }, visible: { y: 0, opacity: 1, transition: { type: 'spring', duration: 1.2, }, }, } useEffect(() => { controls.start('hidden') if (activeIndex !== null) { controls.start('visible') } }, [activeIndex, controls]) return ( <div className='h-full w-10/12 m-auto min-h-screen pt-20 2xl:flex 2xl:flex-col justify-evenly items-center 2xl:pt-0'> <StackBlock isAdaptive={true} /> {activeIndex !== null && ( <motion.article initial='hidden' animate={controls} variants={enterAnimation} key={activeIndex} className='flex flex-col justify-center items-center pt-32' > <LinearGradient gradient={['to right', '#6B46C1 ,#EC4899']} className='text-4xl 2xl:text-5xl font-bold font-dmsans mb-7' > {infoStack[activeIndex].name} </LinearGradient> <p className='w-full text-xl lg:w-9/12 md:text-2xl 2xl:text-3xl text-white font-poppins text-center leading-normal'> {infoStack[activeIndex].text} </p> </motion.article> )} </div> ) } export default StackPage
import { Fragment } from 'react'; import { Navbar, ActivityDashboard, HomePage, ActivityForm, ActivityDetail, TestError, NotFound, ServerError } from './components/index'; import classes from './App.module.css'; import { Route, Routes } from 'react-router-dom'; import { ToastContainer } from 'react-toastify'; function App() { return ( <Fragment> <ToastContainer position='bottom-right' hideProgressBar/> <Routes> <Route path='/' element={ <div> <HomePage /> </div> } /> <Route path='/*' element={ <> <Navbar /> <div className={classes.appContainer}> <Routes> <Route path='/activities' element={<ActivityDashboard />} /> <Route path='/activities/:id' element={<ActivityDetail />} /> <Route path='/createactivity' element={<ActivityForm />} /> <Route path='/manage/:id' element={<ActivityForm />} /> <Route path='/errors' element={<TestError/>}/> <Route path='/server-error' element={<ServerError/>}/> <Route path='/*' element={<NotFound/>} /> {/*If our route doesn't match any of the above, it will display NotFound component */} </Routes> </div> </> } /> </Routes> </Fragment> ); } export default App;
/* TypeScript - Array concat() Advertisements Previous Page Next Page concat() method returns a new array comprised of this array joined with two or more arrays. Syntax array.concat(value1, value2, ..., valueN); Parameter Details valueN − Arrays and/or values to concatenate to the resulting array. Return Value Returns a new array. Example */ var alpha = ["a", "b", "c"]; var numeric = [1, 2, 3]; var alphaNumeric = alpha.concat(numeric); console.log("alphaNumeric : " + alphaNumeric ); /* On compiling, it will generate the same code in JavaScript. Its output is as follows − alphaNumeric : a,b,c,1,2,3 */
import { ListKeyGenerater } from "@/utils/ListKeyGenerate"; import React, { Dispatch, SetStateAction } from "react"; import styled from "styled-components"; type SettingMenuButtonPropsType = { settingMenu: { menu: string; onClickFunc: () => void }[]; openMenu: boolean; setOpenMenu: Dispatch<SetStateAction<boolean>>; }; const SettingMenuContainer = styled.ul` position: absolute; z-index: 2000; top: 0; right: 0; background-color: white; padding: 15px 30px; border-radius: 5px; box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px; white-space: nowrap; & > li { cursor: pointer; margin: 10px 0; font-size: ${({ theme }) => theme.fontSize.m}; &:hover { text-decoration: underline; color: ${({ theme }) => theme.color.green}; } } `; export const ProjectCardSetting = styled.div` width: 100%; height: 100%; padding: 5px 0; align-items: center; border-radius: 50%; display: flex; flex-direction: column; justify-content: space-between; cursor: pointer; transition: 0.4s; &:hover { background-color: rgba(0, 0, 0, 0.3); } & span { display: block; width: 4px; height: 4px; border-radius: 50%; background-color: rgba(0, 0, 0, 0.6); } `; export const ProjectCardSettingContainer = styled.div` position: relative; width: 30px; height: 30px; `; const SettingBackground = styled.div` position: fixed; width: 100vw; height: 100vh; top: 0; left: 0; z-index: 1000; `; const SettingMenu = ({ menuList, onClickOff, }: { menuList: { menu: string; onClickFunc: () => void }[]; onClickOff: () => void; }) => { return ( <> <SettingBackground onClick={onClickOff}></SettingBackground> <SettingMenuContainer> {menuList.map( (menu: { menu: string; onClickFunc: () => void }, idx: number) => { return ( <li onClick={menu.onClickFunc} key={ListKeyGenerater(idx, menu.menu)} > {menu.menu} </li> ); } )} </SettingMenuContainer> </> ); }; const SettingMenuButton = ({ settingMenu, openMenu, setOpenMenu, }: SettingMenuButtonPropsType) => { return ( <ProjectCardSettingContainer> <ProjectCardSetting onClick={() => setOpenMenu(true)}> <span></span> <span></span> <span></span> </ProjectCardSetting> {openMenu && ( <SettingMenu menuList={settingMenu} onClickOff={() => setOpenMenu(false)} /> )} </ProjectCardSettingContainer> ); }; export default SettingMenuButton;
using System.IO; using System.Text; using System; namespace Scorpio.Library { public class LibraryIO { public static readonly Encoding DefaultEncoding = Encoding.UTF8; public const long BaseTime = 621355968000000000; //1970, 1, 1, 0, 0, 0, DateTimeKind.Utc public static long UnixNow => (DateTime.UtcNow.Ticks - BaseTime) / 10000; public static void Load(Script script) { var functions = new (string, ScorpioHandle)[] { ("unixNow", new unixNow()), ("toString", new toString()), ("toBytes", new toBytes()), ("readAll", new readAll()), ("writeAll", new writeAll()), ("readAllString", new readAllString()), ("writeAllString", new writeAllString()), ("readAllLines", new readAllLines(script)), ("writeAllLines", new writeAllLines()), ("appendAllText", new appendAllText()), ("appendAllLines", new appendAllLines()), ("fileExist", new fileExist()), ("pathExist", new pathExist()), ("createPath", new createPath()), ("deleteFile", new deleteFile()), ("deletePath", new deletePath()), ("copyFile", new copyFile()), ("moveFile", new moveFile()), ("movePath", new movePath()), ("getFiles", new getFiles()), ("getPaths", new getPaths()), ("getCreationTime", new getCreationTime()), ("getLastAccessTime", new getLastAccessTime()), ("getLastWriteTime", new getLastWriteTime()), ("setCreationTime", new setCreationTime()), ("setLastAccessTime", new setLastAccessTime()), ("setLastWriteTime", new setLastWriteTime()), ("getExtension", new getExtension()), ("getFileName", new getFileName()), ("getDirectoryName", new getDirectoryName()), ("changeExtension", new changeExtension()), ("combine", new combine()), ("getTempFileName", new getTempFileName()), ("getTempPath", new getTempPath()), ("md5", new md5()), ("md5Bytes", new md5Bytes()), ("md5HashToString", new md5HashToString()), ("toBase64", new toBase64()), ("fromBase64", new fromBase64()), ("workPath", new workPath()), ("lineArgs", new lineArgs()), }; script.AddLibrary("io", functions); } private class unixNow : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(UnixNow); } } private class toString : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var encoding = length > 1 ? Encoding.GetEncoding(args[1].ToString()) : DefaultEncoding; return new ScriptValue(encoding.GetString((byte[])args[0].Value)); } } private class toBytes : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var encoding = length > 1 ? Encoding.GetEncoding(args[1].ToString()) : DefaultEncoding; return ScriptValue.CreateValue(encoding.GetBytes(args[0].ToString())); } } private class readAll : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return ScriptValue.CreateValue(File.ReadAllBytes(args[0].ToString())); } } private class writeAll : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { File.WriteAllBytes(args[0].ToString(), args[1].Value as byte[]); return ScriptValue.Null; } } private class readAllString : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var encoding = length > 1 ? Encoding.GetEncoding(args[1].ToString()) : DefaultEncoding; return new ScriptValue(encoding.GetString(File.ReadAllBytes(args[0].ToString()))); } } private class writeAllString : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var encoding = length > 2 ? Encoding.GetEncoding(args[2].ToString()) : DefaultEncoding; File.WriteAllBytes(args[0].ToString(), encoding.GetBytes(args[1].ToString())); return ScriptValue.Null; } } private class readAllLines : ScorpioHandle { private readonly Script script; public readAllLines(Script script) { this.script = script; } public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var lines = File.ReadAllLines(args[0].ToString(), length > 1 ? Encoding.GetEncoding(args[1].ToString()) : DefaultEncoding); var array = new ScriptArray(script); foreach (var item in lines) { array.Add(ScriptValue.CreateValue(item)); } return new ScriptValue(array); } } private class writeAllLines : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { File.WriteAllLines(args[0].ToString(), args[1].Get<ScriptArray>().ToArray<string>(), length > 2 ? Encoding.GetEncoding(args[2].ToString()) : DefaultEncoding); return ScriptValue.Null; } } private class appendAllText : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { File.AppendAllText(args[0].ToString(), args[1].ToString(), length > 2 ? Encoding.GetEncoding(args[2].ToString()) : DefaultEncoding); return ScriptValue.Null; } } private class appendAllLines : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { File.AppendAllLines(args[0].ToString(), args[1].Get<ScriptArray>().ToArray<string>(), length > 2 ? Encoding.GetEncoding(args[2].ToString()) : DefaultEncoding); return ScriptValue.Null; } } private class fileExist : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return File.Exists(args[0].ToString()) ? ScriptValue.True : ScriptValue.False; } } private class pathExist : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return Directory.Exists(args[0].ToString()) ? ScriptValue.True : ScriptValue.False; } } private class createPath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); return ScriptValue.True; } return ScriptValue.False; } } private class deleteFile : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var file = args[0].ToString(); if (File.Exists(file)) { File.Delete(file); return ScriptValue.True; } return ScriptValue.False; } } private class deletePath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); if (Directory.Exists(path)) { Directory.Delete(path); return ScriptValue.True; } return ScriptValue.False; } } private class copyFile : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var source = args[0].ToString(); var target = args[1].ToString(); File.Copy(source, target, length > 2 ? args[2].IsTrue : false); return ScriptValue.Null; } } private class moveFile : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var source = args[0].ToString(); var target = args[1].ToString(); File.Move(source, target); return ScriptValue.Null; } } private class movePath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var source = args[0].ToString(); var target = args[1].ToString(); Directory.Move(source, target); return ScriptValue.Null; } } private class getFiles : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var searchPattern = length > 1 ? args[1].ToString() : "*"; var searchOption = length > 2 ? (args[2].IsTrue ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) : SearchOption.TopDirectoryOnly; return ScriptValue.CreateValue(Directory.GetFiles(path, searchPattern, searchOption)); } } private class getPaths : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var searchPattern = length > 1 ? args[1].ToString() : "*"; var searchOption = length > 2 ? (args[2].IsTrue ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) : SearchOption.TopDirectoryOnly; return ScriptValue.CreateValue(Directory.GetDirectories(path, searchPattern, searchOption)); } } private class getCreationTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var isDirectory = length > 1 ? args[1].IsTrue : false; if (length > 2 ? args[2].IsTrue : false) { return ScriptValue.CreateValue(isDirectory ? Directory.GetCreationTimeUtc(path) : File.GetCreationTimeUtc(path)); } else { return ScriptValue.CreateValue(isDirectory ? Directory.GetCreationTime(path) : File.GetCreationTime(path)); } } } private class getLastAccessTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var isDirectory = length > 1 ? args[1].IsTrue : false; if (length > 2 ? args[2].IsTrue : false) { return ScriptValue.CreateValue(isDirectory ? Directory.GetLastAccessTimeUtc(path) : File.GetLastAccessTimeUtc(path)); } else { return ScriptValue.CreateValue(isDirectory ? Directory.GetLastAccessTime(path) : File.GetLastAccessTime(path)); } } } private class getLastWriteTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var isDirectory = length > 1 ? args[1].IsTrue : false; if (length > 2 ? args[2].IsTrue : false) { return ScriptValue.CreateValue(isDirectory ? Directory.GetLastWriteTimeUtc(path) : File.GetLastWriteTimeUtc(path)); } else { return ScriptValue.CreateValue(isDirectory ? Directory.GetLastWriteTime(path) : File.GetLastWriteTime(path)); } } } private class setCreationTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var time = (DateTime)args[1].Value; var isDirectory = length > 2 ? args[2].IsTrue : false; if (length > 3 ? args[3].IsTrue : false) { if (isDirectory) { Directory.SetCreationTimeUtc(path, time); } else { File.SetCreationTimeUtc(path, time); } } else { if (isDirectory) { Directory.SetCreationTime(path, time); } else { File.SetCreationTime(path, time); } } return ScriptValue.Null; } } private class setLastAccessTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var time = (DateTime)args[1].Value; var isDirectory = length > 2 ? args[2].IsTrue : false; if (length > 3 ? args[3].IsTrue : false) { if (isDirectory) { Directory.SetLastAccessTimeUtc(path, time); } else { File.SetLastAccessTimeUtc(path, time); } } else { if (isDirectory) { Directory.SetLastAccessTime(path, time); } else { File.SetLastAccessTime(path, time); } } return ScriptValue.Null; } } private class setLastWriteTime : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var path = args[0].ToString(); var time = (DateTime)args[1].Value; var isDirectory = length > 2 ? args[2].IsTrue : false; if (length > 3 ? args[3].IsTrue : false) { if (isDirectory) { Directory.SetLastWriteTimeUtc(path, time); } else { File.SetLastWriteTimeUtc(path, time); } } else { if (isDirectory) { Directory.SetLastWriteTime(path, time); } else { File.SetLastWriteTime(path, time); } } return ScriptValue.Null; } } private class getExtension : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.GetExtension(args[0].ToString())); } } private class getFileName : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue((length > 1 ? args[1].IsTrue : true) ? Path.GetFileName(args[0].ToString()) : Path.GetFileNameWithoutExtension(args[0].ToString())); } } private class getDirectoryName : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.GetDirectoryName(args[0].ToString())); } } private class getFullPath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.GetFullPath(args[0].ToString())); } } private class changeExtension : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.ChangeExtension(args[0].ToString(), args[1].ToString())); } } private class combine : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { var paths = new string[length]; for (var i = 0; i < length; i++) { paths[i] = args[i].ToString(); } return new ScriptValue(Path.Combine(paths)); } } private class getTempFileName : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.GetTempFileName()); } } private class getTempPath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Path.GetTempPath()); } } private class md5 : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { if (args[0].valueType == ScriptValue.stringValueType) { if (length > 1 && args[1].IsTrue) { using (var fileStream = File.OpenRead(args[0].stringValue)) { return new ScriptValue(ScorpioMD5.GetMd5String(fileStream)); } } else { return new ScriptValue(ScorpioMD5.GetMd5String(args[0].stringValue)); } } else { var value = args[0].scriptValue.Value; if (value is Stream) { return new ScriptValue(ScorpioMD5.GetMd5String((Stream)value)); } else if (value is byte[]) { var bytes = (byte[])value; return new ScriptValue(ScorpioMD5.GetMd5String(bytes, length > 1 ? args[1].ToInt32() : 0, length > 2 ? args[2].ToInt32() : bytes.Length)); } else { return ScriptValue.Null; } } } } private class md5Bytes : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { if (args[0].valueType == ScriptValue.stringValueType) { if (length > 1 && args[1].IsTrue) { using (var fileStream = File.OpenRead(args[0].stringValue)) { return ScriptValue.CreateValue(ScorpioMD5.GetMd5Bytes(fileStream)); } } else { return ScriptValue.CreateValue(ScorpioMD5.GetMd5Bytes(args[0].stringValue)); } } else { var value = args[0].scriptValue.Value; if (value is Stream) { return ScriptValue.CreateValue(ScorpioMD5.GetMd5Bytes((Stream)value)); } else if (value is byte[]) { var bytes = (byte[])value; return ScriptValue.CreateValue(ScorpioMD5.GetMd5Bytes(bytes, length > 1 ? args[1].ToInt32() : 0, length > 2 ? args[2].ToInt32() : bytes.Length)); } else { return ScriptValue.Null; } } } } private class md5HashToString: ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(ScorpioMD5.HashToString((byte[])args[0].Value)); } } private class toBase64 : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { if (args[0].valueType == ScriptValue.stringValueType) { return new ScriptValue(Convert.ToBase64String(DefaultEncoding.GetBytes(args[0].stringValue))); } else { var bytes = args[0].scriptValue.Value as byte[]; return new ScriptValue(Convert.ToBase64String(bytes, length > 1 ? args[1].ToInt32() : 0, length > 2 ? args[2].ToInt32() : bytes.Length)); } } } private class fromBase64 : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return ScriptValue.CreateValue(Convert.FromBase64String(args[0].ToString())); } } private class workPath : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return new ScriptValue(Environment.CurrentDirectory); } } private class lineArgs : ScorpioHandle { public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length) { return ScriptValue.CreateValue(Environment.GetCommandLineArgs()); } } } }
import { useState } from 'react'; import { Header } from './components/Header/Header'; import { List } from './components/List/List'; import { Form } from './components/Form/Form'; import { Status } from './components/Status/Status'; import { Todo } from './types'; import styles from './App.module.css'; function App() { const [todoList, setTodoList] = useState([] as Todo[]); function handleNewTodo(todoText: string) { const newTodo: Todo = { id: todoList.length, text: todoText, completed: false }; setTodoList(currentList => [newTodo, ...currentList]); } function handleDeleteTodo(deleteTodoItem: Todo) { setTodoList((currentList: Todo[]) => currentList.filter(todo => todo.id !== deleteTodoItem.id)); } function handleToggleCompleteTodo(todoItem: Todo, completeStatus: boolean) { const updatedTodoList = todoList.map(todo => { if (todo.id === todoItem.id) { todo.completed = completeStatus; } return todo; }); // Sort, false values first updatedTodoList.sort((x, y) => (x.completed === y.completed) ? 0 : x.completed ? 1 : -1); setTodoList(updatedTodoList); } return ( <> <Header /> <main className={styles.container}> <Form onNewTodo={handleNewTodo} /> <Status items={todoList} /> <List items={todoList} onDeleteItem={handleDeleteTodo} onToggleComplete={handleToggleCompleteTodo} /> </main> </> ) } export default App;
import Route from 'Common/Types/API/Route'; import Page from 'CommonUI/src/Components/Page/Page'; import React, { FunctionComponent, ReactElement } from 'react'; import PageMap from '../../Utils/PageMap'; import RouteMap from '../../Utils/RouteMap'; import PageComponentProps from '../PageComponentProps'; import DashboardSideMenu from './SideMenu'; import ModelTable from 'CommonUI/src/Components/ModelTable/ModelTable'; import ApiKeyPermission from 'Model/Models/ApiKeyPermission'; import FormFieldSchemaType from 'CommonUI/src/Components/Forms/Types/FormFieldSchemaType'; import { IconProp } from 'CommonUI/src/Components/Icon/Icon'; import CardModelDetail from 'CommonUI/src/Components/ModelDetail/CardModelDetail'; import ApiKey from 'Model/Models/ApiKey'; import Navigation from 'CommonUI/src/Utils/Navigation'; import PermissionUtil from 'CommonUI/src/Utils/Permission'; import Label from 'Model/Models/Label'; import { JSONArray, JSONObject } from 'Common/Types/JSON'; import Permission, { PermissionHelper } from 'Common/Types/Permission'; import FieldType from 'CommonUI/src/Components/Types/FieldType'; import ModelDelete from 'CommonUI/src/Components/ModelDelete/ModelDelete'; import ObjectID from 'Common/Types/ObjectID'; import LabelsElement from '../../Components/Label/Labels'; import BadDataException from 'Common/Types/Exception/BadDataException'; import FormValues from 'CommonUI/src/Components/Forms/Types/FormValues'; const APIKeyView: FunctionComponent<PageComponentProps> = ( props: PageComponentProps ): ReactElement => { const modelId: ObjectID = new ObjectID( Navigation.getLastParam()?.toString().substring(1) || '' ); return ( <Page title={'Project Settings'} breadcrumbLinks={[ { title: 'Project', to: RouteMap[PageMap.HOME] as Route, }, { title: 'Settings', to: RouteMap[PageMap.SETTINGS] as Route, }, { title: 'API Keys', to: RouteMap[PageMap.SETTINGS_APIKEYS] as Route, }, { title: 'View API Key', to: RouteMap[PageMap.SETTINGS_APIKEY_VIEW] as Route, }, ]} sideMenu={<DashboardSideMenu />} > {/* API Key View */} <CardModelDetail cardProps={{ title: 'API Key Details', description: "Here's more details on this API Key.", icon: IconProp.Terminal, }} isEditable={true} formFields={[ { field: { name: true, }, title: 'Name', fieldType: FormFieldSchemaType.Text, required: true, placeholder: 'API Key Name', validation: { minLength: 2, }, }, { field: { description: true, }, title: 'Description', fieldType: FormFieldSchemaType.LongText, required: true, placeholder: 'API Key Description', }, { field: { expiresAt: true, }, title: 'Expires', fieldType: FormFieldSchemaType.Date, required: true, placeholder: 'Expires at', validation: { dateShouldBeInTheFuture: true, }, }, ]} modelDetailProps={{ modelType: ApiKey, id: 'model-detail-api-key', fields: [ { field: { name: true, }, title: 'Name', }, { field: { description: true, }, title: 'Description', }, { field: { expiresAt: true, }, title: 'Expires', fieldType: FieldType.Date, }, { field: { apiKey: true, }, title: 'API Key', fieldType: FieldType.HiddenText, opts: { isCopyable: true, }, }, ], modelId: modelId, }} /> {/* API Key Permisison Table */} <ModelTable<ApiKeyPermission> modelType={ApiKeyPermission} id="api-key-permission-table" isDeleteable={true} query={{ apiKeyId: modelId, projectId: props.currentProject?._id, }} onBeforeCreate={( item: ApiKeyPermission ): Promise<ApiKeyPermission> => { if (!props.currentProject || !props.currentProject.id) { throw new BadDataException('Project ID cannot be null'); } item.apiKeyId = modelId; item.projectId = props.currentProject.id; return Promise.resolve(item); }} isEditable={true} isCreateable={true} isViewable={false} cardProps={{ icon: IconProp.Lock, title: 'API Key Permissions', description: 'Add different permisisons to API keys to make it more granular.', }} noItemsMessage={ 'No permisisons created for this API Key so far.' } formFields={[ { field: { permission: true, }, onChange: async (_value: any, form: any) => { await form.setFieldValue('labels', [], true); }, title: 'Permission', fieldType: FormFieldSchemaType.Dropdown, required: true, placeholder: 'Permission', dropdownOptions: PermissionUtil.projectPermissionsAsDropdownOptions(), }, { field: { labels: true, }, title: 'Labels (Optional)', description: 'Labels on which this permissions will apply on. This is optional and an advanced feature.', fieldType: FormFieldSchemaType.MultiSelectDropdown, dropdownModal: { type: Label, labelField: 'name', valueField: '_id', }, required: false, placeholder: 'Labels', }, ]} showRefreshButton={true} showFilterButton={true} viewPageRoute={props.pageRoute} columns={[ { field: { permission: true, }, title: 'Permission', type: FieldType.Text, isFilterable: true, showIf: ( values: FormValues<ApiKeyPermission> ): boolean => { if (!values['permission']) { return false; } if ( values['permission'] && !PermissionHelper.isAccessControlPermission( values['permission'] as Permission ) ) { return false; } return true; }, getElement: (item: JSONObject): ReactElement => { return ( <p> {PermissionHelper.getTitle( item['permission'] as Permission )} </p> ); }, }, { field: { labels: { name: true, color: true, }, }, title: 'Labels', type: FieldType.EntityArray, isFilterable: true, filterEntityType: Label, filterQuery: { projectId: props.currentProject?._id, }, filterDropdownField: { label: 'name', value: '_id', }, getElement: (item: JSONObject): ReactElement => { if ( item && item['permission'] && !PermissionHelper.isAccessControlPermission( item['permission'] as Permission ) ) { return ( <p> Labels can not be attached to this permission. </p> ); } return ( <LabelsElement labels={ Label.fromJSON( (item['labels'] as JSONArray) || [], Label ) as Array<Label> } /> ); }, }, ]} /> <ModelDelete modelType={ApiKey} modelId={modelId} onDeleteSuccess={() => { Navigation.navigate( RouteMap[PageMap.SETTINGS_APIKEYS] as Route ); }} /> </Page> ); }; export default APIKeyView;
#include<iostream> #include<iomanip> void showBalance(double balance); double deposit(double balance); double withdraw(double balance); int main() { double balance = 0; int choice = 0; do { std::cout<<"******************\n"; std::cout<<"Enter your choice:\n"; std::cout<<"******************\n"; std::cout<<"1. Deposit money\n"; std::cout<<"2. Withdraw money\n"; std::cout<<"3. Show Balance\n"; std::cout<<"4. Exit\n"; std::cin>>choice; std::cin.clear(); fflush(stdin); switch(choice) { case 1: balance += deposit(balance); showBalance(balance); break; case 2: balance -= withdraw(balance); showBalance(balance); break; case 3:showBalance(balance); break; case 4: std::cout<<"Thanks for visiting\n"; break; default: std::cout<<"Select correct choice\n"; } } while(choice != 4); return 0; } void showBalance(double balance) { std::cout<<"Your current balance is: $"<<std::setprecision(2)<<std::fixed<<balance<<"\n"; } double deposit(double balance) { double amount = 0; std::cout<<"Your current balance is: $"<<std::setprecision(2)<<std::fixed<<balance<<"\n"; std::cout<<"Enter amount to be deposited: "; std::cin>>amount; if(amount > 0) { return amount; } else { std::cout<<"That's not a valid amount\n"; return 0; } } double withdraw(double balance) { double amount = 0; std::cout<<"Your current balance is: $"<<std::setprecision(2)<<std::fixed<<balance<<"\n"; std::cout<<"Enter amount to be withdrawn: "; std::cin>>amount; if(amount > balance) { std::cout<<"Not enough money to withdraw\n"; } else if(amount < 0) { std::cout<<"Not a valid amount\n"; } else { return amount; } }
// LetterDetail.jsx import React, { useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import styled from "styled-components"; import { useLetterContext } from "../context/LetterContext"; const LetterDetail = () => { const { letters, updateLetter, deleteLetter } = useLetterContext(); const { letterId } = useParams(); const navigate = useNavigate(); const [editing, setEditing] = useState(false); const [editedContent, setEditedContent] = useState(""); useEffect(() => { // letterId에 해당하는 편지를 찾아서 editedContent에 설정합니다. console.log("Letters in LetterDetail:", letters); console.log("Letter ID in useEffect:", letterId); if (letters && letters.length > 0) { const selectedLetter = letters.find( (letter) => letter.name === letterId ); if (selectedLetter) { setEditedContent(selectedLetter.content); } } }, [letters, letterId]); // if (!letters || (Array.isArray(letters) && letters.length === 0)) { // return <div>Loading...</div>; // } const selectedLetter = letters.find((letter) => letter.name === letterId); // const selectedLetter = letters.find((letter) => letter.name == letterId); // const selectedLetter = letters.find( // (letter) => String(letter.name) === String(letterId) // ); if (!selectedLetter) { return <div>편지를 찾을 수 없습니다.</div>; } const handleEdit = () => { setEditing(true); }; const handleSave = () => { updateLetter(selectedLetter.name, editedContent); setEditing(false); }; const handleDelete = () => { deleteLetter(selectedLetter.name); navigate("/"); }; return ( <DetailSection> <DetailSectionCont> <DetailSectionContHeader> <ListItemImg /> <h2>{selectedLetter.name}</h2> <p>{selectedLetter.time.toLocaleString()}</p> </DetailSectionContHeader> <DetailSectionContTo> To : {selectedLetter.recipient} </DetailSectionContTo> {editing ? ( <textarea value={editedContent} onChange={(e) => setEditedContent(e.target.value)} /> ) : ( <DetailSectionContContent> {selectedLetter.content} </DetailSectionContContent> )} {/* 작성 시간 추가 */} <DetailSectionBtnWrap> {editing ? ( <DetailSectionBtn onClick={handleSave}> 저장 </DetailSectionBtn> ) : ( <DetailSectionBtn onClick={handleEdit}> 수정 </DetailSectionBtn> )} <DetailSectionBtn onClick={handleDelete}> 삭제 </DetailSectionBtn> </DetailSectionBtnWrap> </DetailSectionCont> <Link to="/">홈으로 돌아가기</Link> </DetailSection> ); }; export default LetterDetail; const DetailSection = styled.section` position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: calc(100% - 1rem); height: calc(100% - 1rem); color: #fff; background-color: #111111cc; display: flex; flex-direction: column; justify-content: center; align-items: center; & > a { position: absolute; top: 1rem; left: 1rem; background-color: #eee; color: #212121; padding: 0.5rem; border-radius: 1rem; } `; const DetailSectionCont = styled.div` display: flex; flex-direction: column; width: 600px; border-radius: 1rem; padding: 1rem; background-color: #eee; color: #151515; `; const DetailSectionContHeader = styled.div` display: flex; align-items: center; margin-bottom: 1rem; & > h2 { font-size: 1.2rem; } & > p { margin-left: auto; font-size: 0.9rem; } `; const ListItemImg = styled.span` display: block; width: 3rem; height: 3rem; border-radius: 3rem; background-color: #ccc; margin-right: 1rem; overflow: hidden; position: relative; &::before { content: ""; position: absolute; top: 50%; left: 50%; width: 1.2rem; height: 1.2rem; border-radius: 1.2rem; transform: translate(-50%, -80%); background-color: #151515; } &::after { content: ""; position: absolute; bottom: 0%; left: 50%; width: 3rem; height: 3rem; border-radius: 3rem; transform: translate(-50%, 65%); background-color: #151515; } `; const DetailSectionContTo = styled.p` margin-bottom: 0.5rem; `; const DetailSectionContContent = styled.p` margin-bottom: 1rem; padding: 1rem; border-radius: 0.8rem; background-color: #151515; color: #ddd; line-height: 1.8rem; `; const DetailSectionBtnWrap = styled.div` display: flex; justify-content: flex-end; `; const DetailSectionBtn = styled.button` &:nth-child(1) { margin-right: 0.5rem; } `;
<!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>SignUp</title> <link rel="stylesheet" href="css/index.css"> <link rel="stylesheet" href="css/sign.css"> </head> <body style="background: url(images/foodorder.jpg); background-size: cover;"> <!-- Preloader --> <div class="preloader"> <img src="./images/preloader.gif" alt="" /> </div> <header class="header" style="position:absolute; background: transparent;"> <a href="" class="logo">Quic<span class="yellow">Bytes</span></a> <nav class="navbar"> <!-- <a id="logout" style="display: none;">LogOut</a> --> <a class="btn">&nbsp LogIn &nbsp</a> </nav> <!-- Hamburger --> <div class="hamburger"> <img src="./images/grid-outline.svg" alt="" /> </div> </header> <!--<div class="logo"></div>--> <div class="wrapper" style="margin-top: 120px; margin-bottom: 50px;"> <span class="icon-close"><ion-icon name="close-outline"></ion-icon></span> <div class="form-box login"> <h2>Login</h2> <form autocomplete="off" method="post" enctype="multipart/form-data"> <div class="input-box"> <span class="icon"><ion-icon name="mail-open-outline"></ion-icon></span> <input type="email" id="login_email" required> <label>Email</label> </div> <div class="input-box"> <span class="icon"><ion-icon name="lock-closed-outline"></ion-icon></span> <input type="password" id="login_password" required> <label>Password</label> </div> <button type="button" id="login" class="btns">Login </button> <div class="login-register"> <p> Don't Have An Account ? <a href="#" class="register-link"> Register </a></p> </div> </form> </div> <div class="form-box register"> <h2>Registration</h2> <form autocomplete="off"> <div class="input-box"> <span class="icon"><ion-icon name="mail-open-outline"></ion-icon></span> <input type="email" id="email" required> <label>Email</label> </div> <div class="input-box"> <span class="icon"><ion-icon name="lock-closed-outline"></ion-icon></span> <input type="password" id="password" required> <label>Password</label> </div> <!-- <div class="remember-forgot"> <label><input type="checkbox"> I agree to the terms and conditons</label> </div> --> <button type="submit" id="register" class="btns">Register </button> <div class="login-register"> <p> Already have an account ? <a href="#" class="login-link"> Login </a></p> </div> </form> </div> </div> <!-- Go To Top --> <div class="scroll-top"> <img src="./images/arrow-up-outline.svg" alt="" /> </div> <script src="js/index.js"></script> <script src="js/sign.js"></script> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> </body> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-app.js"; // import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.19.0/firebase-analytics.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-analytics.js"; import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-auth.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AIzaSyBWdERwNBNzPN_gfWfW_0dymHkL4mU3dCc", authDomain: "quicbytes-fdb21.firebaseapp.com", databaseURL: "https://quicbytes-fdb21-default-rtdb.firebaseio.com", projectId: "quicbytes-fdb21", storageBucket: "quicbytes-fdb21.appspot.com", messagingSenderId: "999586333759", appId: "1:999586333759:web:6621762c87deae313be48a", measurementId: "G-7J6W8460WQ" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); // Register Analytics component const auth = getAuth(); // analytics.logEvent('test_event'); console.log(app); //not needed //----- New Registration code start document.getElementById("register").addEventListener('click', function () { var email = document.getElementById('email').value; var password = document.getElementById('password').value; //For new registration createUserWithEmailAndPassword(auth, email, password) .then((userCredential) => { // Signed in const user = userCredential.user; console.log(user); alert("Registration successfully!!"); // ... window.location.href = "main.html"; }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; // .. console.log(errorMessage); alert("Try Registration Again"); }); }); //----- End //----- Login code start document.getElementById('login').addEventListener('click', function () { var email = document.getElementById('login_email').value; var password = document.getElementById('login_password').value; signInWithEmailAndPassword(auth, email, password) .then((userCredential) => { // Signed in const user = userCredential.user; console.log(user); alert(user.email + " Login successfully!!!"); // document.getElementById('logout').style.display = 'block'; // // ... window.location.href = "main.html"; }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; console.log(errorMessage); alert("Try Login Again"); }); }); //----- End // //----- Logout code start // document.getElementById('logout').addEventListener('click', function () { // signOut(auth).then(() => { // // Sign-out successful. // // console.log("Sign-out successful."); // alert("Sign-out successful."); // document.getElementById('logout').style.display = 'none'; // }).catch((error) => { // // An error happened. // console.log("An error happened."); // }); // }); //----- End </script> </html>
"use strict"; //https://learn.javascript.ru/private-protected-properties-methods //Свойствам-аксессорами называются методы внутри объекта, кот. используются для присвоения значения св-ву объекта и для получения его значения: сеттер (для присвоения), геттер (для получения). //Защищённые свойства обычно начинаются с префикса _. // class AutoMobile { // _horsePowers = 0; //объявление защищенного свойства _horsePowers со значением 0 // set horsePowers(value) { // //Определение сеттера для свойства horsePower // if (value < 0) throw new Error("Отрицательное количество сил"); //Проверка, что значение больше или равно 0, иначе выбрасывает исключение // this._horsePowers = value; //Установка значения свойства _horsePowers // } // get horsePowers() { // //Определение геттера для свойства _horsePowers // return this._horsePowers; // } // constructor(power) { // //Определение конструктора класса // this._horsePowers = power; //Установка значения свойства _horsePowers при создании объекта класса // } // } // //создаем новую машину // let auto = new AutoMobile(100); //создание нового объекта класса AutoMobile и передача значения 100 в конструктор // //устанавливаем количество сил // auto.horsePowers = -10;//Установка значения -10 вызывает исключение "Отрицательное количество сил". Благодаря защищенному полю _ значение контролируется //-----------приватные поля----------- class AutoMobile { #horsePowers = 0; set horsePowers(value) { if (value < 0) throw new Error("Отрицательное количество сил"); this.#horsePowers = value; } get horsePowers() { return this.#horsePowers; } constructor(power) { this.#horsePowers = power; } } //создаем новую машину let auto = new AutoMobile(100); //создание нового объекта класса AutoMobile и передача значения 100 в конструктор //устанавливаем количество сил auto.horsePowers = 50; console.log(auto.horsePowers); auto.#horsePower = 10; //Uncaught SyntaxError: Private field '#horsePower' must be declared in an enclosing class /// Приватные свойства и методы должны начинаться с #. Мы не можем получить к нему доступ извне или из наследуемых классов. Свойство недоступно вне класса бези использования свойств - аксессоров. //Защищенные свойства начинаются с _.защищённые поля наследуются. Свойство защищено от изменений вне класса. //В терминах ООП отделение внутреннего интерфейса от внешнего называется инкапсуляция.
import { gql } from 'graphql-tag' export default gql` type Domain { id: ID! name: String! createdAt: String! createdBy: User! updatedAt: String! } type Query { "get all domains" domains: [Domain!]! "get a domain by id" domain(id: ID!): Domain } type Mutation { "create new domain" createDomain(name: String!): Domain! "update a domain by id" updateDomain(id: ID!, name: String!): Domain! } type Subscription { "subscribe to domain creation" domainCreated: Domain! "subscribe to domain update" domainUpdated: Domain! } `
classdef DataWriter < matlab.System & ... matlab.system.mixin.CustomIcon % The block writes the input binary data to a file. % It uses the low-level I/O function "fwrite". % Writing is done over the existing file ("w" mode). % The block uses little-endian ordering by default. % The block can write real or complex data. % For more information, see the section "Exporting binary data using % low-level I/O" in the MATLAB documentation. properties(Nontunable) FileName = 'test.pcm'; % File name InputType = 'double'; % Input data type end properties(Hidden, Access = private) File; % File object end properties(Constant, Hidden) % StringSet is used for the list box of data types in block dialog. % This method will be removed in future MATLAB releases. InputTypeSet = matlab.system.StringSet(... {'double', 'single', 'int8', 'uint8', 'int16', 'uint16', ... 'int32', 'uint32', 'int64', 'uint64'}); end methods(Access = protected) function validateInputsImpl(obj, data) if ~strcmp(obj.InputType, class(data)) error('Input type mismatch!'); end end function setupImpl(obj) obj.File = fopen(obj.FileName, 'w'); if obj.File < 0 error('File can not be opened!'); end end function stepImpl(obj, data) if isreal(data) fwrite(obj.File, data, obj.InputType); else [r_num, c_num] = size(data); interleaved_data = zeros(r_num * 2, c_num); new_row = 1; for row = 1 : r_num interleaved_data(new_row, :) = real(data(row, :)); interleaved_data(new_row + 1, :) = imag(data(row, :)); new_row = new_row + 2; end fwrite(obj.File, interleaved_data, obj.InputType); % The writing of complex data is taken from the section % "Exporting binary data with low-level I/O" in the MATLAB % documentation with minor improvements. end end function releaseImpl(obj) fclose(obj.File); end function icon = getIconImpl(~) icon = 'Data Writer'; end function name = getInputNamesImpl(~) name = ''; end end methods(Static, Access = protected) function header = getHeaderImpl header = matlab.system.display.Header('DataWriter', ... 'Title', 'Data Writer'); end function group = getPropertyGroupsImpl group = matlab.system.display.Section(... 'Title', 'Parameters', ... 'PropertyList', {'FileName', 'InputType'}); end end end
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->bigInteger('role_id')->unsigned(); $table->bigInteger('uid')->unsigned(); $table->string('first_name'); $table->string('last_name'); $table->string('email',80)->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('mobile',15); $table->string('address')->nullable(); $table->string('user_img')->nullable()->default('https://www.pngitem.com/pimgs/m/581-5813504_avatar-dummy-png-transparent-png.png'); $table->boolean('status'); $table->text('notify_device_id')->nullable(); $table->boolean('is_notify_allowed' )->default(0); $table->dateTime('last_login')->nullable(); $table->ipAddress()->nullable(); $table->boolean('is_social_login')->default(0)->nullable(); $table->string('social',35)->nullable(); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); $table->foreign('role_id')->on('roles')->references('id')->cascadeOnDelete(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('users'); } };
package me.abel.qywechatapi.handlers; import com.alibaba.fastjson2.JSON; import me.abel.qywechatapi.autoconfigure.UrlDefinitionConstant; import me.abel.qywechatapi.utils.HttpClientUtil; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Component public class DepartmentHandler { private final AccessTokenHandler accessTokenHandler; private final ApiDefinitionHandler apiDefinitionHandler; private final HttpClientUtil httpClientUtil; public DepartmentHandler(AccessTokenHandler accessTokenHandler, ApiDefinitionHandler apiDefinitionHandler, HttpClientUtil httpClientUtil) { this.accessTokenHandler = accessTokenHandler; this.apiDefinitionHandler = apiDefinitionHandler; this.httpClientUtil = httpClientUtil; } public String getDepartments (String departId, String appType) throws IOException { String departmentsUrl = apiDefinitionHandler.getRealUrl(UrlDefinitionConstant.DEPARTMENTS); departmentsUrl = departmentsUrl.replaceAll("ACCESS_TOKEN", accessTokenHandler.getAccessToken(appType)); if (!"".equals(departId)) { departmentsUrl = departmentsUrl.replaceAll("ID", departId); } return httpClientUtil.getResponce(departmentsUrl); } public String departmentDelete (String departId, String appType) throws IOException { String departmentsUrl = apiDefinitionHandler.getRealUrl(UrlDefinitionConstant.DEPARTMENT_DELETE); departmentsUrl = departmentsUrl.replaceAll("ACCESS_TOKEN", accessTokenHandler.getAccessToken(appType)); if (!"".equals(departId)) { departmentsUrl = departmentsUrl.replaceAll("ID", departId); } return httpClientUtil.getResponce(departmentsUrl); } /** * * @param name 部门名称 * @param parentId 父部门ID * @return */ public String departmentCreate (String name, String parentId, String appType) throws IOException { String departmentsUrl = apiDefinitionHandler.getRealUrl(UrlDefinitionConstant.DEPARTMENT_CREATE); departmentsUrl = departmentsUrl.replaceAll("ACCESS_TOKEN", accessTokenHandler.getAccessToken(appType)); Map<String, String> params = new HashMap<>(); params.put("name", name); params.put("parentid", parentId); params.put("order", "1"); return httpClientUtil.postJson(departmentsUrl, JSON.toJSONString(params)); } /** * * @param name 部门名称 * @param parentId 父部门ID * @param order 部门顺序号 * @param departId 部门ID * @return */ public String departmentUpdate (String name, String parentId, int order, String departId, String appType) throws IOException { String departmentsUrl = apiDefinitionHandler.getRealUrl(UrlDefinitionConstant.DEPARTMENT_UPDATE); departmentsUrl = departmentsUrl.replaceAll("ACCESS_TOKEN", accessTokenHandler.getAccessToken(appType)); Map<String, String> params = new HashMap<>(); if (!"".equals(name)) { params.put("name", name); } if (!"".equals(parentId)) { params.put("parentid", parentId); } params.put("order", String.valueOf(order)); params.put("id", departId); return httpClientUtil.postJson(departmentsUrl, JSON.toJSONString(params)); } }
/* 使用postcss预编译器完成组件库样式的编写 postcss好处就是它是渐进式的,想用什么功能就安装插件,不像scss等预编译器一样臃肿 */ :root { /* colors */ --cw-color-white: #ffffff; --cw-color-black: #000000; --colors: ( primary: #409eff, success: #67c23a, warning: #e6a23c, danger: #f56c6c, info: #909399 ); @each $val, $color in var(--colors) { --cw-color-$(val): $(color); @for $i from 3 to 9 by 2 { --cw-color-$(val)-light-$(i): mix(#fff, $(color), .$(i)) } --cw-color-$(val)-light-8: mix(#fff, $(color), 0.8); --cw-color-$(val)-dark-2: mix(#000, $(color), 0.2); } --cw-bg-color: #ffffff; --cw-bg-color-page: #f2f3f5; --cw-bg-color-overlay: #ffffff; --cw-text-color-primary: #303133; --cw-text-color-regular: #606266; --cw-text-color-secondary: #909399; --cw-text-color-placeholder: #a8abb2; --cw-text-color-disabled: #c0c4cc; --cw-border-color: #dcdfe6; --cw-border-color-light: #e4e7ed; --cw-border-color-lighter: #ebeef5; --cw-border-color-extra-light: #f2f6fc; --cw-border-color-dark: #d4d7de; --cw-border-color-darker: #cdd0d6; --cw-fill-color: #f0f2f5; --cw-fill-color-light: #f5f7fa; --cw-fill-color-lighter: #fafafa; --cw-fill-color-extra-light: #fafcff; --cw-fill-color-dark: #ebedf0; --cw-fill-color-darker: #e6e8eb; --cw-fill-color-blank: #ffffff; /* border */ --cw-border-width: 1px; --cw-border-style: solid; --cw-border-color-hover: var(--cw-text-color-disabled); --cw-border: var(--cw-border-width) var(--cw-border-style) var(--cw-border-color); --cw-border-radius-base: 4px; --cw-border-radius-small: 2px; --cw-border-radius-round: 20px; --cw-border-radius-circle: 100%; /*font*/ --cw-font-size-extra-large: 20px; --cw-font-size-large: 18px; --cw-font-size-medium: 16px; --cw-font-size-base: 14px; --cw-font-size-small: 13px; --cw-font-size-extra-small: 12px; --cw-font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "\5fae\8f6f\96c5\9ed1", Arial, sans-serif; --cw-font-weight-primary: 500; /*disabled*/ --cw-disabled-bg-color: var(--cw-fill-color-light); --cw-disabled-text-color: var(--cw-text-color-placeholder); --cw-disabled-border-color: var(--cw-border-color-light); /*animation*/ --cw-transition-duration: 0.3s; --cw-transition-duration-fast: 0.2s; }
import { itemNames, generateIndex, generatePrice, priceFormatter, } from "@/app/tools"; import Link from "next/link"; import { Button } from "@nextui-org/react"; import { global } from "styled-jsx/css"; import InventoryTable from "@/components/inventory_table"; import AddInventory from "@/components/add_product_form"; import TransactionHistory from "@/components/transaction_history"; export const dynamic = "force-dynamic"; function transactionHistory() { const day = new Date(); return new Array(50).fill(null).map(() => ({ date: `${day.getDate()}/${day.getMonth()}/${day.getFullYear()}`, itemName: itemNames[generateIndex(itemNames.length)], pricePerItem: priceFormatter.format(generatePrice()), quantity: generateIndex(200), total: priceFormatter.format(generateIndex(20) * generatePrice()), })); } export default async function Home(props) { const data = transactionHistory(); let apiData = await fetch("http://localhost:5000/api/products").then((k) => k.json(), ); let fetchSupplierID = await fetch( `http://localhost:5000/api/auth/fetch_supplier_id/${props.params.id}`, ).then((k) => k.json()); return ( <main className="flex min-h-screen flex-col items-center justify-center p-24"> <div> <div id="profile_section" className="grid grid-cols-2 sm:grid-cols-1 gap-4 items-center justify-items-center pb-6" > <div className="rounded-full h-16 w-16 bg-slate-700 flex items-center justify-center"> User </div> <div>Username</div> <div> <Link href="#addProduct"> <Button>Add Product</Button> </Link> </div> </div> <div id="stats" className="flex flex-row items-center justify-center gap-4 pb-4" > <div className=" bg-slate-700 rounded-full p-4 flex items-center justify-center"> Products Sold: 80 </div> <div className=" bg-slate-700 rounded-full p-4 flex items-center justify-center"> Products Remaining: 350 </div> <div className=" bg-slate-700 rounded-full p-4 flex items-center justify-center"> Orders pending: None </div> </div> </div> <InventoryTable data={apiData} /> <AddInventory supplier_id={fetchSupplierID.supplier_id} business_name={fetchSupplierID.business_name} /> <TransactionHistory data={data} /> </main> ); }
define Start(par){ #### Define all global colors and fonts etc. first here gHeaderFont <- MakeFont("VeraMono.ttf",0,22, MakeColor("black"), MakeColor("grey"),1) gTextFont <- MakeFont("VeraMono.ttf",0,13, MakeColor("black"), MakeColor("white"),1) gBtnFont <- MakeFont("VeraMono.ttf",0,15, MakeColor("black"), MakeColor("grey"),1) #### Read all audiofiles and init the lists gTutSentence <- ChangeListOrder([LoadSound("audio/Tutorial_2_100.wav"), LoadSound("audio/Tutorial_2_170.wav"), LoadSound("audio/Tutorial_2_230.wav")]) gTutQuestion <- "Läuft dort ein Elefant?" gAllSentences <- InitAllAudioList() #### Create Main Window gVideoWidth <- 1000 gVideoHeight <- 750 gWindow <- MakeWindow("white") nextBtn <- MakeLabel("Weiter", gBtnFont) AddObject(nextBtn, gWindow) Move(nextBtn, 500, 650) Hide(nextBtn) Draw() #### init experiment gSubNum <- GetSubNum(gWindow) if(not FileExists("output")) { MakeDirectory("output") } gFile <- FileOpenWrite("output/userData-" + gSubNum + ".txt") FilePrint(gFile, "Probandennummer: " + gSubNum) #Tutorial tutorialHeader <- MakeLabel("Tutorial", gHeaderFont) #TODO finish tutorial description explainationText <- MakeTextBox("Das Experiment läuft wie folgt ab: Du drückst beim Start eine beliebige Taste, um loszulegen. Daraufhin erklingt entweder ein Satz in einer a) schnellen oder b) niedrigen Geschwindigkeit. Bei schneller Geschwindigkeit a) wird getestet, ab welcher Geschwindigkeit du den Satz verstehst. Bei niedriger Geschwindigkeit b) wird getestet, wie lange du den Satz verstehst. Daher wirst du nach dem Hören gefragt, ob du den Satz a) “schon” oder b) “noch” verstanden hast. Klickst du bei a) auf “nein” und bei b) auf “ja”, wird dir der Satz in der a) nächstniedrigeren oder b) nächsthöheren Geschwindigkeit abgespielt. Dies wiederholt sich solange, bis du den Satz a) verstanden oder b) nicht mehr verstanden hast oder die a) niedrigste oder b) höchste Geschwindigkeit erreicht hast. Klickst du bei a) auf “ja”, schon verstanden, und bei b) auf “nein”, nicht mehr verstanden, wird dir a) als nächstes zur Überprüfung eine kontextuelle ja/nein Frage zu dem zuvor gehörten Satz gestellt oder b) einfach mit dem nächsten Satz fortgefahren. Nach dem Beantworten dieser Kontextfrage wird der Ablauf mit dem nächsten Satz wiederholt. Direkt vor dem Abspielen, blinkt auf dem Bildschirm kurz ein grüner Kreis auf. Anschließend wird die Audiodatei abgespielt. Konzentriere dich also besonders auf das Hören sobal du den Kreis aufblinken siehst. Alles Verstanden? Dann klicke unten auf Weiter und starte einen Beispielsatz.", gTextFont, 900, 500) AddObject(tutorialHeader, gWindow) AddObject(explainationText, gWindow) MoveCorner(tutorialHeader, 400, 40) Move(explainationText, 50,90) Show(nextBtn) Draw() #### Example Sentence nextClick <- WaitForClickOnTarget([nextBtn], [1]) RemoveObject(explainationText, gWindow) Hide(nextBtn) listenToLabel <-EasyLabel("Drücke eine beliebige Taste um den Beispielsatz zu starten",450 ,250,gWindow, 14) Draw() RemoveObject(listenToLabel, gWindow) Hide(tutorialHeader) WaitForAnyKeyPress() # gTutSentence loop(sentence, gTutSentence){ ShowListeningScreen() PlayForeground(sentence) # afterPlayDesc 0 == no, 1 == yes afterPlayDesc <- ShowAfterPlayScreen(0) if(afterPlayDesc == 1){ break } } FilePrint(gFile, "Tutorial: ") ShowContextQuestion(gTutQuestion) FilePrint(gFile, "") #### End of Tutorial screen Show(tutorialHeader) endTutorial <- MakeTextBox("Herzlichen Glückwunsch. Du hast das Tutorial erfolgreich absolviert." + "Um nun mit dem Experiment zu starten, klicke bitte auf Weiter", gTextFont, 500, 50) AddObject(endTutorial, gWindow) Move(endTutorial, 150, 120) Show(nextBtn) Draw(gWindow) nextClick <- WaitForClickOnTarget([nextBtn], [1]) RemoveObject(endTutorial, gWindow) RemoveObject(tutorialHeader, gWindow) Hide(nextBtn) Draw(gWindow) #### Start Experiment and loop through all sentences loop(senBundle, gAllSentences){ ShowPreSentenceScreen() #FInd out if last element is a context question. if so, cut out the last element and only go through the soundfiles contextQuestion <- Last(senBundle) isSlowToFast <- 1 if(IsString(contextQuestion)){ FilePrint(gFile, "Folgender Satz von schnell nach langsam: ") audioBundle <- SubList(senBundle, 1, Length(senBundle) -1) isSlowToFast <- 0 }else{ FilePrint(gFile, "Folgender Satz von langsam nach schnell: ") audioBundle <- senBundle isSlowToFast <- 1 } loop(sentence, audioBundle){ ShowListeningScreen() PlayForeground(First(sentence)) # afterPlayDesc 0 == no, 1 == yes afterPlayDesc <- ShowAfterPlayScreen(isSlowToFast) FilePrint(gFile, "SatzId_Geschwindigkeit: " + Last(sentence) + "; Verstanden(j/n = 1/0): " + afterPlayDesc) # Break if understood and show contextquestion if there is one if(isSlowToFast == 1 AND afterPlayDesc == 0){ break }elseif (isSlowToFast == 0 AND afterPlayDesc == 1){ ShowContextQuestion(contextQuestion) break } } FilePrint(gFile, " ") } Print("Loops done") #Experiment done - close all streams and exit FileClose(gFile) experimentDoneBox <- MakeTextBox("Glückwunsch! Du hast das Experiment erfolgreich abgeschlossen. Zum Beenden einfach das Fenster schließen oder 'q' drücken.", gTextFont, 500, 50) AddObject(experimentDoneBox, gWindow) Move(experimentDoneBox, 150, 150) Draw(gWindow) WaitForKeyPress("Q") } ##################### Functions ############################ # This method opens a pre setence screen define ShowPreSentenceScreen(){ preSetenceWin <- MakeWindow("white") AddObject(preSetenceWin, gWindow) sentSucceedLabel <- EasyLabel("Satz abgeschlossen!",500 ,200,preSetenceWin, 14) listenToLabel <- EasyLabel("Drücke eine beliebige Taste um den nächsten Satzablauf zu starten.",480 ,250,preSetenceWin, 14) Draw(preSetenceWin) WaitForAnyKeyPress() RemoveObject(preSetenceWin, gWindow) Draw(gWindow) } define ShowListeningScreen(){ listeningScreen <- MakeWindow("white") AddObject(listeningScreen, gWindow) Draw(listeningScreen) Wait(500) play <- Circle(480,320,40,MakeColor("green"),1) AddObject(play, listeningScreen) Draw(listeningScreen) Wait(100) RemoveObject(listeningScreen, gWindow) Draw(gWindow) } # This shows an after setence playing screen, with the question if the subject # has understood the setence. two buttons are there to get the answer. # Returns 0 or 1. # If 0, the user pressed button "no, dont understand" # if 1, the user pressed button "yes, understood" define ShowAfterPlayScreen(isSlowToFast){ afterPlayWin <- MakeWindow("white") AddObject(afterPlayWin, gWindow) if(isSlowToFast == 1){ headerLabel <- MakeLabel("Hast du den Satz NOCH verstanden?", gTextFont) yesLabel <- MakeLabel("Ja, bitte schneller abspielen.", gBtnFont) noLabel <- MakeLabel("Nein, jetzt war es zu schnell.", gBtnFont) }else{ headerLabel <- MakeLabel("Hast du den Satz SCHON verstanden?", gTextFont) yesLabel <- MakeLabel("Ja, weiter mit der Frage.", gBtnFont) noLabel <- MakeLabel("Nein, bitte langsamer abspielen.", gBtnFont) } AddObject(headerLabel, afterPlayWin) AddObject(yesLabel, afterPlayWin) AddObject(noLabel, afterPlayWin) MoveCorner(headerLabel, 300, 150) MoveCorner(yesLabel, 100, 400) MoveCorner(noLabel, 500, 400) Draw(afterPlayWin) click <- WaitForClickOnTarget([yesLabel, noLabel], [1, 0]) Print("Click: " + click) RemoveObject(afterPlayWin, gWindow) Draw(gWindow) return click } # Opens a context question screen and saves the answer to the file define ShowContextQuestion(contextQuestion){ contextWin <- MakeWindow("white") AddObject(contextWin, gWindow) headerLabel <- MakeLabel("Kontextfrage", gHeaderFont) contextLabel <- MakeLabel(contextQuestion, gTextFont) yesLabel <- MakeLabel("Ja, richtig.", gBtnFont) noLabel <- MakeLabel("Nein, falsch.", gBtnFont) AddObject(headerLabel, contextWin) AddObject(contextLabel, contextWin) AddObject(yesLabel, contextWin) AddObject(noLabel, contextWin) MoveCorner(headerLabel, 350, 50) MoveCorner(contextLabel, 300, 150) MoveCorner(yesLabel, 250, 400) MoveCorner(noLabel, 500, 400) Draw(contextWin) answer <- WaitForClickOnTarget([yesLabel, noLabel], [1, 0]) FilePrint(gFile, contextQuestion + " Antwort(j/n = 1/0): " + answer) RemoveObject(contextWin, gWindow) Draw(gWindow) } #Get all soundfiles to the sentence with the given id #The setence id is written in the versuchsplan define GetSentences(sentenceId){ sentences <- [] # we start at 120% and increase by 20 i <- 120 while(i <= 280){ fileId <- sentenceId + "_" + i sen<- LoadSound("audio/" + fileId + ".wav") PushOnEnd(sentences, [sen, fileId]) i <- i + 20 } return sentences } # Change the order of the given list, so that the returned list is the sample # list but the now from last to first element. define ChangeListOrder(changingList){ orderedList <- [] i <- Length(changingList) while( i >= 1){ item <- Nth(changingList, i) PushOnEnd(orderedList, item) i <- i -1 } return orderedList } # initializes all audio lists and returns one list including all sublists define InitAllAudioList(){ gSentence1_1 <- GetSentences("1_1") gSentence1_1Backward <- ChangeListOrder(gSentence1_1) PushOnEnd(gSentence1_1Backward, "Ist das Haus dunkelblau?") gSentence1_2 <- GetSentences("1_2") gSentence1_2Backward <- ChangeListOrder(gSentence1_2) PushOnEnd(gSentence1_2Backward, "Weiche Kekse sind lecker.") gSentence2_2 <- GetSentences("2_2") gSentence2_2Backward <- ChangeListOrder(gSentence2_2) PushOnEnd(gSentence2_2Backward, "Vertreibt Korn auch Sorgen am Morgen?") gSentence2_3 <- GetSentences("2_3") gSentence2_3Backward <- ChangeListOrder(gSentence2_3) PushOnEnd(gSentence2_3Backward, "Der Wind ist ein laues Lüftchen.") gSentence3_1 <- GetSentences("3_1") gSentence3_1Backward <- ChangeListOrder(gSentence3_1) PushOnEnd(gSentence3_1Backward, "Das Bier im Eschenbräu schmeckt nicht.") gSentence3_2 <- GetSentences("3_2") gSentence3_2Backward <- ChangeListOrder(gSentence3_2) PushOnEnd(gSentence3_2Backward, "Die Beuth möchte Chipkarten einführen.") return [gSentence1_2Backward, gSentence2_2, gSentence3_1Backward, gSentence1_1Backward, gSentence1_2, gSentence3_2, gSentence2_3Backward, gSentence3_1, gSentence2_2Backward, gSentence1_1, gSentence2_3, gSentence3_2Backward] }
import ItemImage from "./ItemImage"; import StackImage from "./StackImage"; import { stackLogos } from "../projects/stack"; import ProjectTag from "./ProjectTag"; const images = require.context('../../public', true); export default function ProjectItem({ img, title, description, url, repo, stack, tag, }: { img: string, title: string, description: string[], url: string, repo: string, stack?: string[], tag?: string, }) { let projectImg; try { projectImg = images(`./${img}`).default; } catch (error) { projectImg = images(`./${"bucketly_logo.webp"}`).default; } const projectHref = url && url.length > 0 ? url : repo; return ( <span className="w-full flex flex-col gap-5 md:flex-row lg:flex-row" key={title}> <span className='flex justify-end translate-y-12 md:hidden lg:hidden'> <ProjectTag tag={tag} /> </span> <ItemImage imageSrc={projectImg} title={title} projectHref={projectHref} /> <span className="w-full"> <h3 className="text-2xl font-bold tracking-wider">{title}</h3> {description && description.map((item, index) => ( <p key={index} className="text-lg text-justify">{item}</p> ))} <p className="pt-5"> Stack: </p> <div className="w-full flex flex-wrap flex-row items-start justify-start pb-5 gap-1"> {stack && stack.map((item, index) => { let logo; try { logo = images(`./${(stackLogos as any)[item]["filename"]}`).default; } catch (error) { logo = images(`./typescript.webp`).default; } let stackLogo = (stackLogos as any)[item]; stackLogo = stackLogo ?? (stackLogos as any)["typescript"]; return ( <StackImage key={index} title={item} url={stackLogo?.url} logo={logo} /> ) })} </div> <span className="flex flex-col"> {url && url.length > 0 && ( <a className="text-lg underline text-indigo-500 hover:text-pink-500 transition ease-out duration-500" href={url} target='_blank'>See &#10148;</a> )} {repo && repo.length > 0 && ( <a className="text-lg underline text-indigo-500 hover:text-pink-500 transition ease-out duration-500" href={repo} target='_blank'>Github &#10148;</a> )} </span> </span> <span className='hidden md:flex lg:flex'> <ProjectTag tag={tag} /> </span> </span> ) }
# 1. receive multicast messages from WSJT-X (and anything that looks like it on the same group) # 2. decode messages from QTDatastream and map the fields # # # format description: # https://sourceforge.net/p/wsjt/wsjtx/ci/master/tree/Network/NetworkMessage.hpp # based on QDatastream from the Qt framework. # # dependencies: # if using PySide6, pip install pyside6 # if using PyQt5, sudo apt install qtbase5-dev; pip install pyqt5 # install hexdump with pip install simple-hexdump # install juliandate with pip install juliandate import socket import struct import sys #from PyQt5.QtCore import QByteArray, QDataStream, QIODevice from PySide6.QtCore import QByteArray, QDataStream, QIODevice from hexdump import hexdump import datetime import juliandate as jd debug = True # decode the UTF-8 strings embedded in the QDatastream of WSJT-X UDP messages def decode_utf8_str(stream): len = stream.readUInt32() if len == 0xffffffff: # null string is mashed into an empty string return "" else: bytes = stream.readRawData(len) return bytes.decode("utf-8)") # decode qtime (milliseconds since midnight UTC) into an ISO 8601 timestamp string def decode_qtime_iso8601str(stream): utcnow = datetime.datetime.now(datetime.UTC) utcmidnight = datetime.datetime(utcnow.year, utcnow.month, utcnow.day, 0, 0) msecs_since_midnight = stream.readUInt32() timestamp = utcmidnight + datetime.timedelta(milliseconds=msecs_since_midnight) iso8601_timestamp = timestamp.isoformat() + 'Z' if debug: print("iso8601_timestamp:", iso8601_timestamp) return iso8601_timestamp # decode qdatetime into an ISO 8601 timestamp string def decode_qdatetime_iso8601str(stream): julian_days = stream.readInt64() # QDate msecs_since_midnight = stream.readUInt32() timespec = stream.readUInt8() if timespec == 3: raise("non-spec qso logged message received with timespec 3 (timezones).") if timespec == 2: offset = stream.readInt32() if debug: print("offset:", offset) raise("unable to deal with QDateTime objects with timespec=2 (offset={}).".format(offset)) gregorian_datetime = datetime.datetime(*jd.to_gregorian(julian_days)) # Apparently this is always noon. since the QTime is milliseconds since midnight, if we add it to the # gregorgian_date the resulting timestamp will be off by 12 hours every time. # Instead, we recreate the date with starting point at midnight and add milliseconds to it. This is safe # because julian_days will always be an integer and never fractions of a day. combined_datetime = datetime.datetime(gregorian_datetime.year, gregorian_datetime.month, gregorian_datetime.day,0,0) + datetime.timedelta(milliseconds=msecs_since_midnight) iso8601_datetime = combined_datetime.isoformat() + 'Z' if debug: print("julian_days:", julian_days) print("msecs_since_midnight:", msecs_since_midnight) print("timespec:", timespec) print("gregorian_datetime:", gregorian_datetime) print("combined_datetime:", combined_datetime) print("combined_datetime.isoformat()Z:", iso8601_datetime) print("iso8601_datetime", iso8601_datetime) return iso8601_datetime # open multicast socket and join group 224.0.0.1:2237 where we expect WSJT-X UDP multicasts in QTDatastream format mcast_group = '224.0.0.1' mcast_port = 2237 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((mcast_group, mcast_port)) mreq = socket.inet_aton(mcast_group) + socket.inet_aton("0.0.0.0") sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: data, addr = sock.recvfrom(10240) if debug: print(hexdump(data)) print("source:",format(addr)) buffer = QByteArray(data) stream = QDataStream(buffer) stream.setByteOrder(QDataStream.BigEndian) try: # check magic number match magic = stream.readUInt32() if magic != 0xadbccbda: raise Exception("bad magic number (" + str(magic) + ")") # check schema number match schema = stream.readUInt32() if schema != 2: raise Exception("unsupported schema (" + str(schema) + ")") # if we got here, we know we have something that looks like the message we're expecting from WSJT-X message_type = stream.readUInt32() # FIXME placeholder # https://github.com/ckuhtz/ham/issues/3 id = decode_utf8_str(stream) match message_type: case 0: # Heartbeat message from WSJT-X (discovery and schema negotiation) # It appears schema negotation is optional? # Out/In max_schema = stream.readUInt32() version = decode_utf8_str(stream) revision = decode_utf8_str(stream) if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(heartbeat)") print("max_schema:", max_schema) print ("version/revision: {version}/{revision}".format(version=version,revision=revision)) case 1: # Status update from WSJT-X # Out dial_freq = stream.readUInt64() mode = decode_utf8_str(stream) dx_call = decode_utf8_str(stream) report = decode_utf8_str(stream) tx_mode = decode_utf8_str(stream) tx_enabled = stream.readBool() transmitting = stream.readBool() decoding = stream.readBool() rx_df = stream.readUInt32() tx_df = stream.readUInt32() de_call = decode_utf8_str(stream) de_grid = decode_utf8_str(stream) dx_grid = decode_utf8_str(stream) tx_watchdog = stream.readBool() sub_mode = decode_utf8_str(stream) fast_mode = stream.readBool() spec_op_mode = stream.readUInt8() freq_tolerance = stream.readUInt32() tr_period = stream.readUInt32() config_name = decode_utf8_str(stream) tx_message = decode_utf8_str(stream) if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(status)") print("dial_freq:", dial_freq) print("mode:", mode) print("dx_call:", dx_call) print("report:", report) print("tx_mode:", tx_mode) print("tx_enabled:", tx_enabled) print("transmitting:", transmitting) print("decoding:", decoding) print("rx_df:", rx_df) print("tx_df:", tx_df) print("de_call:", de_call) print("de_grid:", de_grid) print("dx_grid:", dx_grid) print("tx_watchdog:", tx_watchdog) print("sub_mode:", sub_mode) print("fast_mode:", fast_mode) print("spec_op_mode: {} ".format(spec_op_mode), end="") match spec_op_mode: case 0: print("(none)") case 1: print("(NA VHF)") case 2: print("(EU VHF)") case 3: print("(FIELD DAY)") case 4: print("(RTTY RU)") case 5: print("(WW DIGI)") case 6: print("(FOX)") case 7: print("(HOUND)") case 8: print("(ARRL DIGI)") case _: print("(wtf?)") print("freq_tolerance:", freq_tolerance, end="") if freq_tolerance == 4294967295: print(" (not applicable)") else: print() print("tr_period:", tr_period, end="") if tr_period == 4294967295: print(" (not applicable)") else: print() print("config_name:", config_name) print("tx_message:",tx_message) case 2: # WSJT-X has decoded a message # Out new = stream.readBool() time = decode_qtime_iso8601str(stream) snr = stream.readInt32() delta_time = stream.readFloat() delta_freq = stream.readUInt32() mode = decode_utf8_str(stream) rx_message = decode_utf8_str(stream) low_conf = stream.readBool() off_air = stream.readBool() if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(decode)") print("new:", new) print("time:", time) print("snr:", snr) print("delta_time:", delta_time) print("delta_freq:", delta_freq) print("mode:", mode) print("rx_message:", rx_message) print("low_conf:", low_conf) print("off_air:", off_air) case 3: # Either user has discarded prior decodes or the server is being instructed to discard decodes # Out/In window = stream.readUInt8() if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(clear)") print("window:", window) case 4: # Inbound control message to WSJT-X only # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(reply)") # ignored case 5: # QSO logged datetime_off = decode_qdatetime_iso8601str(stream) dx_call = decode_utf8_str(stream) dx_grid = decode_utf8_str(stream) tx_freq = stream.readUInt64() mode = decode_utf8_str(stream) report_sent = decode_utf8_str(stream) report_rcvd = decode_utf8_str(stream) tx_power = decode_utf8_str(stream) comments = decode_utf8_str(stream) name = decode_utf8_str(stream) datetime_on = decode_qdatetime_iso8601str(stream) op_call = decode_utf8_str(stream) de_call = decode_utf8_str(stream) de_grid = decode_utf8_str(stream) exch_sent = decode_utf8_str(stream) exch_rcvd = decode_utf8_str(stream) adif_prop_mode = decode_utf8_str(stream) if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(qso logged)") print("datetime_off:", datetime_off) print("dx_call:", dx_call) print("dx_grid:", dx_grid) print("tx_freq:", tx_freq) print("mode:", mode) print("report_sent:", report_sent) print("report_rcvd:", report_rcvd) print("tx_power:", tx_power) print("comments:", comments) print("name:", name) print("datetime_on:", datetime_on) print("op_call", op_call) print("de_call:", de_call) print("de_grid:", de_grid) print("exch_sent:", exch_sent) print("exch_rcvd:", exch_rcvd) print("adif_prop_mode:", adif_prop_mode) case 6: # WSJT-X shutting down if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(close)") case 7: # Replay previous band decodes from WSJT-X if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(replay)") # ignored case 8: # Halt transmissions in WSJT-X # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(halt tx)") # ignored case 9: # Set free text message in WSJT-X # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(freetext)") # ignored case 10: # WSPR decode receive from WSJT-X # Out if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(WSPR decode)") # ignored case 11: # Location update for WSJT-X # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(location update)") # ignored case 12: # Logged ADIF message from WSJT-X # Out adif = decode_utf8_str(stream) if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(logged ADIF)") print("adif:", adif) case 13: # Highlight call sign in WSJT-X # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(callsign highlight)") # ignored case 14: # Switch WSJT-X configuration # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(switch configuration)") # ignored case 15: # Configure WSJT-X # In if debug: print("id:", id) print("message_type: {message_type} ".format(message_type=message_type), end="") print("(configure)") # ignored case _: print() raise Exception("unknown message type " + str(id) + " received.") except Exception as e: print("Error decoding WSJT-X data:", str(e)) if debug: print()
import { useCallback } from "react"; import CheckedIcon from "../../assets/checked.svg"; import { useStep } from "../../hook"; import { CheckedImage, CheckedStepperContainer, CircularStepperContainer, InnerCircularStepper, LineStepper, LineStepperInner, RelativeText, SimpleStepperContainer, StepperItem, StepperText } from "./styles"; export type StepperConfigProps = { simple?: boolean; checkeds?: boolean; simpleText?: boolean; clickExample?: boolean; }; export type StepperProps = { steps: any[]; step: number; } & StepperConfigProps; export type SimpleItem = { text: string; } & StepperProps; export const SimpleItem = ({ text, step, steps }: SimpleItem) => { return <RelativeText {...{ step, steps }}>{text}</RelativeText>; }; export const Stepper = ({ steps, step, simple, checkeds, simpleText }: StepperProps) => { const { goToNext } = useStep(); const text = String((step / steps.length) * 100) + "%"; const getLine = (step: number) => { return step < steps.length - 1; }; if (simpleText) { return ( <CheckedStepperContainer onClick={goToNext}> {steps.map((_step, index) => { const active = step === index; const passed = step >= index; return ( <> <CircularStepperContainer> <InnerCircularStepper active={passed}> {index} </InnerCircularStepper> </CircularStepperContainer> <StepperText lateral active={active}> {_step.title} </StepperText> {getLine(index) && ( <LineStepper> <LineStepperInner notVisible active={passed} /> </LineStepper> )} </> ); })} </CheckedStepperContainer> ); } if (checkeds) { return ( <CheckedStepperContainer onClick={goToNext}> {steps.map((_step, index) => { const active = step === index; const passed = step > index; const animate = step - 1 === index; return ( <> <CircularStepperContainer> <InnerCircularStepper active={active}> {passed ? <CheckedImage src={CheckedIcon} /> : index} </InnerCircularStepper> <StepperText active={active}>{_step.title}</StepperText> </CircularStepperContainer> {getLine(index) && ( <LineStepper> <LineStepperInner active={passed} animate={animate}/> </LineStepper> )} </> ); })} </CheckedStepperContainer> ); } return ( <> <SimpleStepperContainer onClick={goToNext}> {simple && <SimpleItem {...{ text, step, steps }} />} <StepperItem step={step} steps={steps} /> </SimpleStepperContainer> </> ); };
const mongoose = require('mongoose') const bcrypt = require('bcrypt') const validator = require('validator') const jwt = require('jsonwebtoken') const User = require('../models/userModel') const generateAccessToken = (_id) => { return jwt.sign({ _id: _id }, process.env.SECRET, { expiresIn: '3d' }) } // Login user const loginUser = async (req, res) => { const { email, password } = req.body if (!email || !password) { return res .status(400) .json({ error: 'Please fill all the required fields' }) } const user = await User.findOne({ email }) if (!user) { return res.status(400).json({ error: 'Incorrect email' }) } const isMatched = await bcrypt.compare(password, user.password) if (!isMatched) { return res.status(400).json({ error: 'Incorrect password' }) } // generate access token const accessToken = generateAccessToken(user._id) res.status(200).json({ role: user.role, email, name: user.name, accessToken }) } // Register user const registerUser = async (req, res) => { const { email, password, confirmPassword } = req.body if (!email || !password || !confirmPassword) { return res .status(400) .json({ error: 'Please fill all the required fields' }) } const isEmailUsed = await User.findOne({ email }) if (isEmailUsed) { return res.status(400).json({ error: 'Email already used' }) } if (!validator.isEmail(email)) { return res.status(400).json({ error: 'Email is invalid' }) } if (!validator.isStrongPassword(password)) { return res.status(400).json({ error: 'Password is not strong enough' }) } if (password !== confirmPassword) { return res.status(400).json({ error: 'Passwords mismatch' }) } const salt = await bcrypt.genSalt(10) const hashedPassword = await bcrypt.hash(password, salt) // try to create try { const user = await User.create({ email, password: hashedPassword }) // generate access token const accessToken = generateAccessToken(user._id) res.status(200).json({ email, accessToken }) } catch (error) { res.status(400).json({ error: error.message }) } } module.exports = { loginUser, registerUser, }
import React, { useState, useCallback } from "react"; import { Div, Button, Heading } from "."; export const Accordion = React.memo(({ accordionData }) => { const [accordion, setAccordion] = useState(""); const [accordionId, setAccordionId] = useState(0); const openAccordion = useCallback( (accordionKey) => { if (accordion === "") { setAccordion("show"); setAccordionId(accordionKey); } else { setAccordion(""); setAccordionId(0); } }, [accordion] ); return ( <Div divClass="accordion" id="accordionExample"> {accordionData && accordionData.length !== 0 ? ( accordionData.map((item) => ( <Div divClass="accordion-item" key={item.id}> <Heading headingClass="accordion-header"> <Button buttonClass={ accordion === "show" && accordionId === item.id ? "accordion-button collapsed" : "accordion-button" } buttonHandler={() => openAccordion(item.id)} type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne" > {item.moduleName} </Button> </Heading> <Div id="collapseOne" divClass={ accordion === "show" && accordionId === item.id ? `accordion-collapse show mt-3` : `accordion-collapse collapse` } data-bs-parent="#accordionExample" > <Div divClass="accordion-body align-justify">{item.listText}</Div> </Div> </Div> )) ) : ( <></> )} </Div> ); });
'''Mean minimum political distance (MMPD)''' is a [[political spectrum]] statistic defined as the mean distance between a voter and the nearest elected candidate. == Example == Assume a one-dimensional political spectrum with the voter distribution * 15% at position 0 * 20% at position 0.25 * 30% at position 0.5 * 20% at position 0.75 * 15% at position 1 If the candidate set {0.25, 0.75} is elected, then <table border> <tr> <th>voters</th> <th>position</th> <th>nearest winner</th> <th>distance</th> <th>voters × distance</th> </tr> <tr align="right"> <td>0.15</td> <td>0.00</td> <td>0.25</td> <td>0.25</td> <td>0.0375</td> </tr> <tr align="right"> <td>0.20</td> <td>0.25</td> <td>0.25</td> <td>0.00</td> <td>0.0000</td> </tr> <tr align="right"> <td>0.30</td> <td>0.55</td> <td>either</td> <td>0.25</td> <td>0.0750</td> </tr> <tr align="right"> <td>0.20</td> <td>0.75</td> <td>0.75</td> <td>0.00</td> <td>0.0000</td> </tr> <tr align="right"> <td>0.15</td> <td>1.00</td> <td>0.75</td> <td>0.25</td> <td>0.0375</td> </tr> <tr> <th colspan="4">sum of voters × distance</th> <td align="right">0.1500</td> </tr> </table> The MMPD of this example is 0.15. == Special cases == On a [[uniform linear political spectrum]]: === Random Ballots === The mathematically expected MMPD for ''n'' winners randomly selected from uniform(0,1) is (n+3)/(2(n+1)(n+2)), which is 1/3 for a single winner, and asympotically 1/(2n) as the number of seats approaches infinity. === Droop Multiples === Electing the candidates {i/(n+1): 1&le;i&le;n} gives an MMPD of (n+3)/(4(n+1)²). As ''n'' approaches infinity, this is asymptotically equal to the optimal value of 1/(4n). === Optimal Winners === The minimum possible MMPD in a uniform linear spectrum is 1/(4n), which occurs when the candidate set {(2i+1)/(2n): 0&le;i&lt;n} is elected.
doctype html html head meta(charset='utf-8') meta(name='viewport', content='width=device-width, initial-scale=1') title jade body div - var obj = { "size": 10, "from": 0, "explain": false, "highlight": {}, "query": { "conjuncts": [ { "match": "上海泉灵信息科技有限公司", "filed": "F_Applicant", "boost": 10, "prefix_length": 0, "fuzziness": 0 } ] }, "fields": [ "*" ], "facets": { "class": { "size": 100, "field": "F_PatentType" } } }; -var obj2 = typeof(obj); -var obj5 = typeof(obj); ul li wo______#{obj} li shi______#{obj2} li xiang______ li ni______ //这是注释 //-这是注释 // 多行注释 duohangzhushi h1 好好学习 a(href='http://www.w3cplus.com/html/how-to-use-jade.html') input(type = 'checkbox',checked) input( type='checkbox', name='agreement', checked ) - var authenticated = true span(class=authenticated ? 'authed' : 'anon') - var currentUrl = '/about' a(class={active: currentUrl === '/'} href='/') Home a(class={active: currentUrl === '/about'} href='/about') About .link a.link #button a#button div a(style={color: 'red', background: 'green'}) //属性 - var attributes = {'data-foo': 'bar'}; div#foo(data-bar="foo")&attributes(attributes) //单行文本 p 单行文本 //管道文本使用管道符 p | 这是管道文本,行数无限 | 这也是管道文本,行数无限 //多行文本需要在文本后添加点号 p. 这是多行文本,注意缩进 这是多行文本注意缩进 //将 JavaScript 嵌入到 Jade 中,一共有三种方法。第一种方式是使用 -,代码中的特殊字符不会被转义: - for (var x = 0; x < 3; x++) //不转义 li <a></a> //转义 li= '<a></a>' //不转义 p!= 'This code is <escaped>!' // 转义字符串插值 `#{}` - var theGreat = "<span>escape!</span>"; p This will be safe: #{theGreat} // 不转义字符串插值 `!{}` - var theGreat = "<span>escape!</span>"; p This will be safe: !{theGreat} // 标签插值 p #[a(href="jade-lang.com") Jade]
<!DOCTYPE html> <html> <head> <title>MyCloset</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <script src="https://kit.fontawesome.com/adc8ff6a3d.js" crossorigin="anonymous"></script> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> <meta name="viewport" content="width=device-width,initial-scale=1.0"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-lg-10 col-sm-12"> <%= yield %> </div> <div class="col-lg-2 margin-top"> <%= image_tag 'logo.jpg', :size =>'200x200' %> <% if user_signed_in? %> <div class = "width-50 mx-auto menu"> <li> <%= link_to "Top", root_path %> </li> <li> <%= link_to "User Top", user_path(current_user) %> </li> <li> <%= link_to "User Edit", edit_user_path(current_user) %> </li> <li> <%= link_to "Item", items_path %> </li> <li> <%= link_to "Post", posts_path %> </li> <li> <%= link_to "Sign out", destroy_user_session_path, method: :delete %> </li> </div> <% else %> <div class = "width-50 mx-auto menu"> <li> <%= link_to "Top", root_path %> </li> <li> <%= link_to "Adout", about_path %> </li> <li> <%= link_to "Sign in", new_user_session_path %> </li> <li> <%= link_to "Sign up", new_user_registration_path %> </li> </div> <% end %> </div> </div> </div> </body> </html>
@mixin font-face($family, $src, $fileArgs: '', $style: normal, $weight: normal) { @font-face { font-family: $family; src: url('#{$src}.eot#{$fileArgs}'); // IE9 compatibility src: url('#{$src}.eot#{$fileArgs}#iefix') format('embedded-opentype'), // IE8 and below url('#{$src}.ttf#{$fileArgs}') format('truetype'), // Safari, Android, iOS url('#{$src}.woff2#{$fileArgs}') format('woff2'), // new standards url('#{$src}.woff#{$fileArgs}') format('woff'), // standards url('#{$src}.svg#{$fileArgs}##{$family}') format('svg'); // legacy iOS font-style: $style; font-weight: $weight; } } @mixin row($horizontal: flex-start, $vertical: flex-start) { display: flex; flex-direction: row; justify-content: $horizontal; align-items: $vertical; } @mixin column($horizontal: flex-start, $vertical: flex-start) { display: flex; flex-direction: column; justify-content: $vertical; align-items: $horizontal; } @mixin center { @include row(center, center); } @mixin size($width: 100%, $height: 100%) { width: $width; height: $height; } @mixin square($size) { @include size($size, $size); } @mixin fill { @include square(100%); } @mixin headings { h1, h2, h3, h4, h5, h6 { @content; } } @mixin transition($type: all, $duration:0.4s) { transition: $type $duration ease-out; } @mixin list($spacing: 1rem, $columns:false) { @include row; flex-wrap: wrap; gap: $spacing; @if ($columns) { > * { width: calc(100% / $columns - $spacing * ($columns - 1) / $columns); } } } @mixin grid($grid: 2, $spacing: 0) { display: grid; grid-template-columns: repeat($grid, 1fr); gap: $spacing; } @mixin absoluteFit { position: absolute; left: 0; top: 0; height: 100%; width: 100%; } @mixin imgFit($fit: contain, $position: center) { width: 100%; height: 100%; object-fit: $fit; object-position: $position; } @mixin text-overflow($lines: 3) { display: -webkit-box; -webkit-line-clamp: $lines; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; } @function pxrem($px) { @return calc($px / 16 * 1rem); }
import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import '../controller/datacontroller.dart'; class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { late List<Map<String, dynamic>> data = []; bool state = true; getdata() async { data = await Datafetch().fetchProducts(); setState(() {}); if (data.isNotEmpty) { setState(() { state = false; }); } } @override Widget build(BuildContext context) { if (state) { getdata(); } return Scaffold( appBar: AppBar( title: const Text("Home"), ), body: Container( padding: const EdgeInsets.all(5), child: ListView.builder( itemCount: data.length, itemBuilder: (BuildContext context, int index) { return Card( child: Padding( padding: const EdgeInsets.fromLTRB(15, 0, 5, 10), child: Column( children: [ Image.network(data[index]['image']), Row( children: [ Flexible( child: Text( data[index]['name'], textAlign: TextAlign.left, ), ) ], ), Row( children: [ Flexible( child: Text( data[index]['brand'], style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 25), textAlign: TextAlign.left, ), ) ], ), Row( children: [ Flexible( child: Text("Rs ${data[index]['price']}/-")) ], ), Row( children: [ (data[index]['rating'] == null) ? (Row(children: const [ Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ])) : (((data[index]['rating'] > 0)) ? ((data[index]['rating'] > 1) ? ((data[index]['rating'] > 2) ? ((data[index]['rating'] > 3) ? ((data[index]['rating'] > 4) ? ((data[index]['rating'] > 4 && data[index] ['rating'] < 5) ? (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon( Icons.star_half) ])) : (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons.star) ]))) : (data[index]['rating'] == 4) ? (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons .star_border) ])) : (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons .star_half), Icon(Icons .star_border) ]))) : (data[index]['rating'] == 3) ? (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), Icon(Icons.star_border), Icon(Icons.star_border) ])) : (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star_half), Icon(Icons.star_border), Icon(Icons.star_border) ]))) : (data[index]['rating'] == 2) ? (Row(children: const [ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ])) : ((Row(children: const [ Icon(Icons.star), Icon(Icons.star_half), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ])))) : (data[index]['rating'] == 1) ? (Row(children: const [ Icon(Icons.star), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ])) : (Row(children: const [ Icon(Icons.star_half), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ]))) : (Row(children: const [ Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border), Icon(Icons.star_border) ]))), Flexible( child: Text(data[index]['rating'].toString())) ], ), ], ), ), ); }), )); } }
// // WeatherDailyViewModel.swift // Weather-Test-App // // Created by Владимир Михайлюк on 8/12/22. // import Foundation struct WeatherDailyViewModel { let date: Double let day: String let tempMin: String let tempMax: String let description: String let conditionImage: String static func getViewModel(with weatherViewModel: [WeatherViewModel]) -> [WeatherDailyViewModel] { var dailyViewModelArray = [WeatherDailyViewModel]() let temporaryDailyDictionary = Dictionary(grouping: weatherViewModel, by: { $0.dateWithMonth }) // temporaryDailyDictionary -> ["d/MM": [WeatherViewModel], "d/MM": [WeatherViewModel] ..] temporaryDailyDictionary.forEach { key, value in // find highest temperature using min. let tempMax = value.max { $0.tempMaxInt < $1.tempMaxInt } // find lowest temperature using min. let tempMin = value.min { $0.tempMinInt < $1.tempMinInt } guard let tempMax = tempMax, let tempMin = tempMin else { return } for i in 0...value.count - 1 { let date = value[i].date let day = value[i].day let description = value[i].description dailyViewModelArray.append(WeatherDailyViewModel.init(date: date, day: day, tempMin: tempMin.tempMin, tempMax: tempMax.tempMax, description: description, conditionImage: tempMax.conditionImage)) } } // remove repetitive elements let uniqueArray = dailyViewModelArray.unique(for: \.day) return uniqueArray.sorted { $0.date < $1.date } } }
Une API (Application Programming Interface) est un ensemble de règles et de spécifications qui définissent comment les applications peuvent communiquer entre elles. Elle permet aux développeurs de créer des applications en utilisant les fonctionnalités d'autres applications ou services existants. Les fonctions principales d'une API comprennent : Accès aux données : L'API permet aux développeurs d'accéder à des données stockées par une autre application ou un service. Interaction avec des services tiers : Les API permettent aux développeurs de se connecter et d'interagir avec des services tiers tels que les réseaux sociaux, les systèmes de paiement, les bases de données, etc. Automatisation des tâches : Les API peuvent automatiser des tâches complexes en permettant aux applications de se connecter entre elles et de partager des informations. Amélioration de la fonctionnalité : Les API peuvent ajouter des fonctionnalités supplémentaires à une application existante en lui permettant de se connecter à d'autres services. En résumé, les API permettent aux développeurs de construire des applications plus rapidement en utilisant les fonctionnalités existantes d'autres services, sans avoir à les implémenter eux-mêmes. ############################################## Si vous souhaitez créer une application de services en ligne, vous pouvez utiliser une API pour intégrer diverses fonctionnalités à votre application. Par exemple : Paiement en ligne : Vous pouvez intégrer une API de paiement pour permettre à vos utilisateurs de payer en ligne pour les services que vous offrez. Livraison de notifications : Vous pouvez utiliser une API de notifications pour informer les utilisateurs de l'état de leurs commandes ou de tout autre mise à jour importante. Stockage de données : Vous pouvez utiliser une API de stockage de données pour stocker et gérer les informations de vos utilisateurs, telles que leurs coordonnées et leurs commandes passées. Géolocalisation : Vous pouvez utiliser une API de géolocalisation pour déterminer l'emplacement actuel des utilisateurs et leur fournir des services basés sur leur emplacement. En utilisant les API, vous pouvez rapidement ajouter de nouvelles fonctionnalités à votre application sans avoir à les développer vous-même. Cela vous permet de vous concentrer sur la création d'une expérience utilisateur unique pour vos clients. ##################################################################### Les API REST (Representational State Transfer) et GraphQL sont deux types différents de protocoles d'interface de programmation d'application (API). API REST : Les API REST sont des API basées sur le protocole HTTP, qui utilisent des méthodes telles que GET, POST, PUT et DELETE pour effectuer des opérations sur les données. Les API REST sont souvent utilisées pour accéder à des ressources sur le web, telles que les images, les vidéos et les données structurées. API GraphQL : GraphQL est un protocole d'interface de programmation d'application développé par Facebook. Il permet aux clients de définir exactement les données dont ils ont besoin et de les recevoir en une seule requête, plutôt que d'avoir à faire plusieurs requêtes séparées pour obtenir des données différentes. Les API GraphQL sont souvent utilisées pour les applications de type « single page » qui nécessitent une grande flexibilité pour les requêtes de données. En résumé, REST est un protocole bien établi pour les API, tandis que GraphQL est un protocole plus récent qui offre une plus grande flexibilité pour les requêtes de données. Les deux types d'API peuvent être utilisés en fonction des besoins spécifiques de votre application. <!-- {% extends "bases/base.html" %} {% load static %} {% load static crispy_forms_tags %} {% block content %} <div class="content-section col-lg-12 col-md-12 col-sm-12 tutorial-style" style="min-height:65vh;"> <legend class="border-bottom mb-4">Profile Information:</legend> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="media"> <img src="{% static form.instance.profile_photo.url %}" class="align-self-start mr-3" style="width:100px; height:100px;"> <div class="media-body"> <h2 class="account-heading">{{ form.instance.username }} <small class="text-muted">({{ form.instance.status }})</small> </h2> <p class="text-secondary">{{ form.instance.first_name }} {{ form.instance.last_name }}</p> <p class="text-secondary">{{ form.instance.email }}</p> <p class="text-secondary">{{ form.instance.city }}, {{ form.instance.country }}</p> <p class="text-secondary">Phone Number: {{ form.instance.phone_number }}</p> </div> </div> {% if user.username == form.instance.username %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile Information</legend> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.first_name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.last_name|as_crispy_field }} </div> </div> {{ form.email|as_crispy_field }} {{ form.city|as_crispy_field }} {{ form.country|as_crispy_field }} {{ form.phone_number|as_crispy_field }} {{ form.profile_photo|as_crispy_field }} <a href="/">Change password?</a> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> {% endif %} </form> <script> fetch("https://restcountries.eu/rest/v2/all") .then(response => response.json()) .then(data => { // data contient la liste de tous les pays let countries = data.map(function(country) { return { name: country.name, code: country.alpha2Code }; }); // Vous pouvez maintenant utiliser la liste des pays pour alimenter votre liste déroulante. let select = document.getElementById("id_country"); countries.forEach(function(country) { let option = document.createElement("option"); option.value = country.code; option.text = country.name; select.add(option); }); }); </script> </div> {% endblock content %} -->
import {Component, OnInit, ViewEncapsulation} from '@angular/core'; import {RouteParams} from '@angular/router-deprecated'; import {DataTable, Column, ToggleButton} from 'primeng/primeng'; import {DateTimeFormat} from '../shared/pipes/date-time-format.pipe'; import {AppService} from '../shared/index'; import {Repairs, ApiResponse, RepairActivity, RepairPart} from '../shared/models/index'; import {UnitInfoComponent} from '../unit-info/unit-info.component'; import {OperatorInfoComponent} from '../operator-info/operator-info.component'; import {LoadingContainer, LoadingPage} from '../shared/loading-container'; @Component({ selector: 'repair-activity', templateUrl: 'app/repair-activity/repair-activity.component.html', styleUrls: [ 'app/repair-activity/repair-activity.component.css' ], directives: [ LoadingContainer, OperatorInfoComponent, UnitInfoComponent, DataTable, Column, ToggleButton ], pipes: [ DateTimeFormat ], encapsulation: ViewEncapsulation.None }) export class RepairActivityComponent extends LoadingPage implements OnInit { public Model: Repairs; public Activity: RepairActivity[]; public Parts: RepairPart[]; public ApiResponse: ApiResponse; constructor( public Service: AppService, private _routeParams: RouteParams) { super(true); this.Activity = []; this.Parts = []; this.ApiResponse = new ApiResponse(); } ngOnInit() { this.Model = this.Service.Repairs; let id = +this._routeParams.get('id'); let activityId = +this._routeParams.get('activityId'); if (id) { this.Service.LoadUnitInfo(id).subscribe((data: Repairs) => { this.Model = data; this.Service.GetRepairActivity(activityId).subscribe((response: ApiResponse) => { if (response.Data.RepairActivity != null) { this.Activity.push(response.Data.RepairActivity); } this.Parts = response.Data.RepairParts; this.Service.Status.IsProcessing = false; this.Ready(); }); }); } else { this.Service.GoToDone(); } } public DeleteRepairActivity(confirmed: boolean, item: RepairActivity) { if (!confirmed) { setTimeout(() => { item.ConfirmDelete = !item.ConfirmDelete; }, 2000); return; } this.Service.DeleteRepairActivity(item.Id).subscribe((response: ApiResponse) => { this.ApiResponse = response; if (!this.ApiResponse.IsError) { this.Activity = []; this.Parts = []; } }); } public DeleteRepairPart(confirmed: boolean, item: RepairPart) { if (!confirmed) { setTimeout(() => { item.ConfirmDelete = !item.ConfirmDelete; }, 2000); return; } this.Service.DeleteRepairPart(item.Id).subscribe((response: ApiResponse) => { this.ApiResponse = response; if (!this.ApiResponse.IsError) { this.Parts.splice(this.Parts.indexOf(item), 1); } }); } }
import React from "react"; import "./SavedMovies.css"; import MoviesCardList from "../MoviesCardList/MoviesCardList"; import Header from "../Header/Header"; import SearchForm from "../SearchForm/SearchForm"; import Preloader from "../Preloader/Preloader"; import Footer from "../Footer/Footer"; function SavedMovies({ loggedIn, isNavMenuOpen, onNavMenuOpen, isLoading, savedMovies, onAddMovies, onClose, isCheckedShortFilm, onCheckedShortFilm, onSubmit, isWasRequest, handleMovieDisLike, handleChangeSearchKeyword, keyword, }) { React.useEffect(() => { document.title = "Сохраненные фильмы — Movies Explorer"; }, []); return ( <> <Header loggedIn={loggedIn} isNavMenuOpen={isNavMenuOpen} onNavMenuOpen={onNavMenuOpen} onClose={onClose} /> <main className="main"> <SearchForm isChecked={isCheckedShortFilm} onChangeCheckbox={onCheckedShortFilm} onSubmit={onSubmit} isWasRequest={isWasRequest} handleChange={handleChangeSearchKeyword} keyword={keyword} /> {isLoading ? ( <Preloader/> ) : ( <MoviesCardList movies={savedMovies} savedMovies={savedMovies} onAddMovies={onAddMovies} isChecked={isCheckedShortFilm} isPlaceSavedMovies={true} isWasRequest={isWasRequest} handleMovieDisLike={handleMovieDisLike} /> )} </main> <Footer/> </> ); } export default SavedMovies;
import Modal from './Modal' import Box from '@mui/material/Box' import Button from '@mui/material/Button' import TextField from '@mui/material/TextField' import Avatar from '@mui/material/Avatar' import * as yup from 'yup' import { selectCurrentModal } from '../redux/reducers/ui' import useTypedSelector from '../hooks/useTypesSelector' import useAuth from '../hooks/useAuth' import { useFormik } from 'formik' import useTypedDispatch from '../hooks/useTypedDispatch' import { usersActions } from '../redux/reducers/users' import { SyntheticEvent, useEffect, useMemo, useRef, useState } from 'react' const EditProfileModal = () => { const [image, setImage] = useState<File | null>(null) const imageUrl = useMemo(() => image && URL.createObjectURL(image) || null, [image]) const fileInputRef = useRef<HTMLInputElement>(null!) const { currentUser } = useAuth() const dispatch = useTypedDispatch() const isOpen = useTypedSelector((state) => selectCurrentModal(state)) === 'edit-profile' const form = useFormik({ initialValues: { username: '' }, validationSchema: yup.object().shape({ username: yup.string() .trim() .required('Required') .min(3, 'Too short') .max(15, 'Too long'), }), onSubmit(v) { const changes: { username?: string, avatar?: File } = {} if (v.username !== currentUser.username) { changes.username = v.username } if (image) { changes.avatar = image } if (!Object.keys(changes).length) { return alert('no changes') } dispatch(usersActions.updateProfile(changes)) } }) useEffect(() => { if (isOpen) { form.setValues({ username: currentUser.username }) } }, [isOpen]) const handleFileInputChange = (e: SyntheticEvent) => { setImage((e.target as HTMLInputElement).files[0]) } return <> <Modal title='Edit' isOpen={isOpen}> <Box component='form' sx={{ display: 'flex', flexDirection: 'column' }} onSubmit={form.handleSubmit}> <Box sx={{ display: 'flex', gap: '2px' }} > <Avatar src={image ? imageUrl : currentUser.avatarUrl} /> <Button type='button' sx={{ ml: 'auto' }} onClick={() => fileInputRef.current.click()}> Replace </Button> <Button type='button' color='error'> Remove </Button> </Box> <TextField name='username' size='small' placeholder='Username' value={form.values.username} onChange={form.handleChange} onBlur={form.handleBlur} error={form.touched.username && Boolean(form.errors.username)} helperText={form.touched.username && form.errors.username} sx={{ mt: '5px' }} /> <Button type='submit' sx={{ mt: '20px' }} variant='contained' size='small'> Edit </Button> </Box> </Modal> <Box component='input' type='file' onChange={handleFileInputChange} ref={fileInputRef} hidden /> </> } export default EditProfileModal
package org.http.server.httpserverframework.handlers.methods.impl import com.sun.net.httpserver.HttpExchange import org.http.server.httpserverframework.handlers.RequestHandler import org.http.server.httpserverframework.handlers.methods.RequestHandlerMethod import org.http.server.httpserverframework.handlers.methods.impl.events.PostEventsHttpMethod import org.http.server.httpserverframework.http.HttpCodes import org.http.server.httpserverframework.log.Logger class NotFoundHttpMethod: RequestHandlerMethod() { companion object { private val log = Logger.getLogger(this::class.toString()) val INSTANCE by lazy { NotFoundHttpMethod() } } override fun handle(httpExchange: HttpExchange) { log.debug("Received request with uri ${httpExchange.requestURI} and method ${httpExchange.requestMethod}") httpExchange.sendResponseHeaders(HttpCodes.NOT_FOUND, RequestHandler.NOT_FOUND_MESSAGE.length.toLong()) httpExchange.responseBody.use { it.write(RequestHandler.NOT_FOUND_MESSAGE.toByteArray()) } } }
import { ITiledMap, ITiledMapEmbeddedTileset, ITiledMapLayer, ITiledMapTile, } from "@workadventure/tiled-map-type-guard"; import { PNG } from "pngjs"; import sharp, { Sharp } from "sharp"; import { LogLevel, OptimizeBufferOptions } from "./guards/libGuards.js"; sharp.cache(false); export class Optimizer { private optimizedMap: ITiledMap; private optimizedTiles: Map<number, number>; private optimizedTilesets: ITiledMapEmbeddedTileset[]; private currentTilesetOptimization: ITiledMapEmbeddedTileset; private currentExtractedTiles: Promise<Buffer>[]; private tileSize: number; private outputSize: number; private tilesetMaxTileCount: number; private tilesetPrefix: string; private tilesetSuffix?: string; private logLevel: LogLevel; constructor( map: ITiledMap, private readonly tilesetsBuffers: Map<ITiledMapEmbeddedTileset, Sharp>, options: OptimizeBufferOptions | undefined = undefined, private readonly outputPath: string ) { this.optimizedMap = map; this.optimizedTiles = new Map<number, number>(); this.optimizedTilesets = []; this.tileSize = options?.tile?.size ?? 32; this.outputSize = options?.output?.tileset?.size ? options?.output?.tileset?.size : 512; const maxColumns = this.outputSize / 32; this.tilesetMaxTileCount = maxColumns * maxColumns; this.tilesetPrefix = options?.output?.tileset?.prefix ?? "chunk"; this.tilesetSuffix = options?.output?.tileset?.suffix; this.logLevel = options?.logs ?? LogLevel.NORMAL; this.currentTilesetOptimization = this.generateNextTileset(); this.currentExtractedTiles = []; for (const tileset of [...tilesetsBuffers.keys()]) { if (tileset.tileheight !== this.tileSize || tileset.tilewidth !== this.tileSize) { throw Error(`Tileset ${tileset.name} not compatible! Accept only ${this.tileSize} tile size`); } } } public async optimize(): Promise<ITiledMap> { if (this.logLevel) { console.log("Start tiles optimization..."); } await this.optimizeLayers(this.optimizedMap.layers); await this.optimizeNamedTiles(); if (this.currentExtractedTiles.length > 0) { await this.currentTilesetRendering(); } this.optimizedMap.tilesets = []; for (const currentTileset of this.optimizedTilesets) { this.optimizedMap.tilesets.push(currentTileset); } if (this.logLevel) { console.log("Tiles optimization has been done"); } return this.optimizedMap; } private async optimizeLayers(layers: ITiledMapLayer[]): Promise<void> { for (let i = 0; i < layers.length; i++) { const layer = layers[i]; if (layer.type === "group") { if (!layer.layers) { continue; } await this.optimizeLayers(layer.layers); continue; } if (layer.type !== "tilelayer") { continue; } if (!layer.data) { continue; } for (let y = 0; y < layer.data.length; y++) { if (typeof layer.data === "string") { continue; } const tileId = layer.data[y]; if (tileId === 0) { continue; } await this.checkCurrentTileset(); const newTileId = await this.optimizeNewTile(Number(tileId)); layer.data[y] = newTileId; } } } private async optimizeNamedTiles(): Promise<void> { for (const tileset of this.tilesetsBuffers.keys()) { if (!tileset.tiles) { continue; } if (!tileset.firstgid) { throw new Error(`firstgid property is undefined on ${tileset.name} tileset`); } for (const tile of tileset.tiles) { const tileId = tileset.firstgid + tile.id; if (this.optimizedTiles.has(tileId)) { continue; } if (!tile.properties) { continue; } if (tile.properties.find((property) => property.name === "name")) { await this.optimizeNewTile(tileId); } } } } private generateNextTileset(): ITiledMapEmbeddedTileset { if (this.logLevel === LogLevel.VERBOSE) { console.log("Generate a new tileset data"); } const tilesetCount = this.optimizedTilesets.length + 1; return { columns: 1, firstgid: this.optimizedTiles.size + 1, image: `${this.tilesetPrefix}-${tilesetCount}${this.tilesetSuffix ? "-" + this.tilesetSuffix : ""}.png`, imageheight: 0, imagewidth: 0, margin: 0, name: `Chunk ${tilesetCount}`, properties: [], spacing: 0, tilecount: 0, tileheight: this.tileSize, tilewidth: this.tileSize, tiles: [], }; } private async generateNewTilesetBuffer(size: number): Promise<Buffer> { const newFile = new PNG({ width: size, height: size, }); return await newFile.pack().pipe(sharp()).toBuffer(); } private async optimizeNewTile(tileId: number): Promise<number> { if (this.logLevel === LogLevel.VERBOSE) { //console.log(`${tileId} tile is optimizing...`); } let minBitId; // 3758096384 = 29 & 30 & 31 // 3221225472 = 30 & 31 // 2684354560 = 29 & 31 // 2147483648 = 31 // 1610612736 = 29 & 30 // 1073741824 = 30 // 536870912 = 29 const bit29 = Math.pow(2, 29); const bit30 = Math.pow(2, 30); const bit31 = Math.pow(2, 31); const bit32 = Math.pow(2, 32); if (tileId < bit29) { minBitId = 0; } else if (tileId < bit30) { minBitId = bit29; } else if (tileId < bit29 + bit30) { minBitId = bit30; } else if (tileId < bit31) { minBitId = bit29 + bit30; } else if (tileId < bit29 + bit31) { minBitId = bit31; } else if (tileId < bit30 + bit31) { minBitId = bit29 + bit31; } else if (tileId < bit29 + bit30 + bit31) { minBitId = bit30 + bit31; } else if (tileId < bit32) { minBitId = bit29 + bit30 + bit31; } else { throw new Error(`Something was wrong with flipped tile id ${tileId}`); } const unflippedTileId = tileId - minBitId; const existantNewTileId = this.optimizedTiles.get(unflippedTileId); if (existantNewTileId) { return existantNewTileId + minBitId; } let oldTileset: ITiledMapEmbeddedTileset | undefined; for (const tileset of this.tilesetsBuffers.keys()) { if (!tileset.firstgid) { throw new Error(`firstgid property is undefined on ${tileset.name} tileset`); } if (!tileset.tilecount) { throw new Error(`tilecount property is undefined on ${tileset.name} tileset`); } if (tileset.firstgid <= unflippedTileId && tileset.firstgid + tileset.tilecount > unflippedTileId) { oldTileset = tileset; break; } } if (!oldTileset) { if (this.logLevel) { console.error(`${tileId} undefined! Corrupted layers or undefined in tilesets`); console.error("This tile has been replaced by a empty tile"); } return 0; } if (!oldTileset.firstgid) { throw new Error(`firstgid property is undefined on ${oldTileset.name} tileset`); } const oldFirstgid = oldTileset.firstgid; const oldTileIdInTileset = unflippedTileId - oldFirstgid; let tileData: ITiledMapTile | undefined = undefined; if (oldTileset.tiles) { tileData = oldTileset.tiles.find((tile) => tile.id === oldTileIdInTileset); if (tileData && tileData.animation) { if (tileData.animation.length + this.currentExtractedTiles.length > this.tilesetMaxTileCount) { for (let i = 1; i < this.tilesetMaxTileCount - this.currentExtractedTiles.length; i++) { this.optimizedTiles.set(-1, this.optimizedTiles.size + i); } await this.currentTilesetRendering(); } } } const newTileId = this.optimizedTiles.size + 1; this.optimizedTiles.set(unflippedTileId, newTileId); let newTileData: ITiledMapTile | undefined = undefined; this.currentExtractedTiles.push(this.extractTile(oldTileset, unflippedTileId)); const newTileIdInTileset = this.currentExtractedTiles.length - 1; if (oldTileset.properties) { newTileData = { id: newTileIdInTileset, properties: [...oldTileset.properties], }; } if (!oldTileset.tiles) { if (newTileData) { this.currentTilesetOptimization.tiles?.push(newTileData); } return newTileId + minBitId; } if (!tileData) { if (newTileData) { this.currentTilesetOptimization.tiles?.push(newTileData); } return newTileId + minBitId; } if (!newTileData) { newTileData = { id: newTileIdInTileset, }; this.currentTilesetOptimization.tiles?.push(newTileData); } if (tileData.properties) { newTileData.properties ? newTileData.properties.push(...tileData.properties) : (newTileData.properties = [...tileData.properties]); this.currentTilesetOptimization.tiles?.push(newTileData); } if (tileData.animation) { newTileData.animation = []; for (const frame of tileData.animation) { await this.optimizeNewTile(oldFirstgid + frame.tileid); newTileData.animation.push({ duration: frame.duration, tileid: this.currentExtractedTiles.length - 1, }); } } return newTileId + minBitId; } private async extractTile(tileset: ITiledMapEmbeddedTileset, tileId: number): Promise<Buffer> { if (!tileset.imagewidth) { throw new Error(`imagewidth property is undefined on ${tileset.name} tileset`); } if (!tileset.firstgid) { throw new Error(`firstgid property is undefined on ${tileset.name} tileset`); } const tileSizeSpaced = this.tileSize + (tileset.spacing || 0); const tilesetColumns = Math.floor( (tileset.imagewidth - (tileset.margin || 0) + (tileset.spacing || 0)) / tileSizeSpaced ); const tilesetTileId = tileId - tileset.firstgid + 1; const estimateLeft = tilesetTileId <= tilesetColumns ? tilesetTileId : tilesetTileId % tilesetColumns; const leftStartPoint = (estimateLeft === 0 ? tilesetColumns : estimateLeft) * tileSizeSpaced - tileSizeSpaced + (tileset.margin || 0); let topStartPoint = tileset.margin || 0; let state = tilesetTileId; while (state > tilesetColumns) { state -= tilesetColumns; topStartPoint += tileSizeSpaced; } const sharpObject = this.tilesetsBuffers.get(tileset); if (!sharpObject) { throw new Error("Undefined sharp object"); } return await sharpObject .extract({ left: leftStartPoint, top: topStartPoint, width: this.tileSize, height: this.tileSize, }) .toBuffer(); } private async checkCurrentTileset(): Promise<void> { if (this.currentExtractedTiles.length < this.tilesetMaxTileCount) { return; } await this.currentTilesetRendering(); } private async currentTilesetRendering(): Promise<void> { if (this.logLevel) { console.log(`Rendering of ${this.currentTilesetOptimization.name} tileset...`); } this.currentTilesetOptimization.tilecount = this.currentExtractedTiles.length; const columnCount = Math.ceil(Math.sqrt(this.currentTilesetOptimization.tilecount)); const imageSize = columnCount * this.tileSize; this.currentTilesetOptimization.columns = columnCount; this.currentTilesetOptimization.imagewidth = imageSize; this.currentTilesetOptimization.imageheight = imageSize; const tilesetBuffer = await this.generateNewTilesetBuffer(imageSize); if (this.logLevel === LogLevel.VERBOSE) { console.log("Empty image generated"); } const sharpTileset = sharp(tilesetBuffer); if (this.logLevel === LogLevel.VERBOSE) { console.log("Loading of all tiles who will be optimized..."); } const tileBuffers = await Promise.all(this.currentExtractedTiles); if (this.logLevel === LogLevel.VERBOSE) { console.log("Tiles loading finished"); console.log("Tileset optimized image generating..."); } const sharpComposites: sharp.OverlayOptions[] = []; let x = 0; let y = 0; for (const tileBuffer of tileBuffers) { if (x === imageSize) { y += this.tileSize; x = 0; } sharpComposites.push({ input: tileBuffer, top: y, left: x, }); x += this.tileSize; } await sharpTileset .composite(sharpComposites) .toFile(`${this.outputPath}/${this.currentTilesetOptimization.image}`); this.optimizedTilesets.push(this.currentTilesetOptimization); if (this.logLevel === LogLevel.VERBOSE) { console.log("Tileset optimized image generated"); } if (this.logLevel) { console.log("The tileset has been rendered"); } this.currentTilesetOptimization = this.generateNextTileset(); this.currentExtractedTiles = []; } }
import styles from "./cryptoCard.module.css"; import Tick from "../../assets/icon/tick"; const CryptoCard = ({ alt, icon, isSelected, text, handleCardClick, }: CryptoCardProps) => { return ( <div onClick={handleCardClick} className={`${isSelected ? styles.selectedContainer : styles.container}`} > <div className={styles.textWrapper}> <img src={icon} alt={alt} className={styles.logo} /> <div className={styles.title}>{text}</div> </div> {isSelected && <Tick />} </div> ); }; export interface CryptoCardProps { text: string; icon: string; alt: string; isSelected: boolean; handleCardClick: VoidFunction; } export default CryptoCard;
/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require("./bootstrap"); window.Vue = require("vue").default; import App from './App.vue'; import VueAxios from 'vue-axios'; import axios from 'axios'; Vue.use(VueAxios, axios); const app = new Vue(Vue.util.extend(App)).$mount('#app'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) // Vue.component( // "example-component", // require("./components/ExampleComponent.vue").default // ); // Vue.component( // "secret-component", // require("./components/SecretComponent.vue").default // ); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ // const app = new Vue({ // el: '#app', // // }); // Vue.component('Home', require('./components/Home.vue').default); // window.Vue = require("Vue").default; // import App from "./App.vue"; // import Home from "../js/components/Home"; // import Navbar from "../js/components/Navbar"; // import ContactList from "../js/components/ContactList"; // // import SecretComponent from "../js/components/SecretComponent"; // import VueAxios from "vue-axios"; // import axios from "axios"; // import { createRouter, createWebHistory } from "vue-router"; // // Vue.use(VueRouter); // import Vue from "vue"; // import { times } from "lodash"; // Vue.use(VueAxios, axios); // const routes = [ // { name: "/", path: "/", component: Home }, // { name: "login", path: "/login", component: Home }, // ]; // const router = createRouter({ // history: createWebHistory(), // routes, // }); // // const app = new Vue(Vue.util.extend({router},App).$mount("#app")); // const app = new Vue({ // el: "#app", // router, // }).$mount("#app"); // console.log("Vue");
# Introduction [My Switch Game](https://github.com/Littlefisher619/MyCTFChallenges/tree/master/CTFChallengeSwitch/Challenge2) and [Switch Pro Controller](https://github.com/Littlefisher619/MyCTFChallenges/tree/master/CTFChallengeSwitch/Challenge1) are the challenges for the game [RCTF2020](https://ctftime.org/event/1045) hosted by ROIS. * My Switch Game: `Reserve`+`Misc` * Switch Pro Controller: `Misc` *[Here for Chinese solution](https://github.com/Littlefisher619/MyCTFChallenges/blob/master/CTFChallengeSwitch/solution_zhcn.md)* # References Traffic * https://github.com/spacemeowx2/RemoteSwitchController/blob/dev/splatoon-bot/src/controller.ts * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md Switch Emulator * https://emulation.gametechwiki.com/index.php/Nintendo_Switch_emulators * https://github.com/Ryujinx/Ryujinx Switchbrew Dev * https://www.switchbru.com/appstore/#/ * https://github.com/switchbrew/libnx * https://switchbrew.org/wiki/Setting_up_Development_Environment * https://github.com/switchbrew/switch-examples/tree/master/templates/application Debugger: * https://github.com/reswitched/Mephisto # Switch Pro Controller(Challenge1) Switch Pro Controller is connect to Windows with Steam installed through USB. Open the friend chat window, and then press the left stick three times to launch Steam's screen keyboard. Starting screen recording and Wireshark to capture the packets. You should get flag by the video file and the pcapng file. Attachment: `capture.pcappng` `screenrecord.mp4` Description: none Flag: RCTF{5witch_1s_4m4z1ng_m8dw65} Solve.py: ```python import ffmpeg # install ffmpeg to your system and then pip3 install ffmpeg-python import numpy import cv2 import json KEY_A = 0b00001000 TIMEDELTA = 3 JSON_FILE = 'easy.json' VIDEO_FILE = 'easy.mp4' # Timedelta can be calculated by when the first packet that # means KEY_A pressed appears and when the first character # appears on the textbox in the video # It help us locate the KEY_A-Pressed frames in the video. f = open(JSON_FILE, 'r', encoding='utf-8') packets = json.loads(f.read()) f.close() # filter the packets which means A is pressed and extract time and frameNo buf = [] for packet in packets[735:]: layers = packet['_source']['layers'] packetid = int(layers['frame']['frame.number']) time = float(layers['frame']['frame.time_relative']) try: capdata = bytearray.fromhex(layers["usb.capdata"].replace(':', ' ')) if capdata[3] & KEY_A == KEY_A: buf.append([packetid, time]) print(packetid, time, [bin(data)[2:] for data in capdata[3:6]]) except KeyError: pass print(buf) # seperate sequences from filtered packets and calculate the average time for each sequence time_avg = [] _lastid = buf[0][0]-2 _sum = 0 _sumcnt = 0 _cnt = 0 for data in buf: _cnt += 1 if data[0]-_lastid==2 and _cnt!=len(buf): _sum+=data[1] _sumcnt+=1 else: time_avg.append(_sum/_sumcnt) _sum = 0 _sumcnt = 0 _lastid = data[0] print(time_avg) # extract frames from the video one by one for t in time_avg: out, err = ( ffmpeg.input(VIDEO_FILE, ss=t) .output('pipe:', vframes=1, format='image2', vcodec='mjpeg') .run(capture_stdout=True) ) image_array = numpy.asarray(bytearray(out), dtype="uint8") image = cv2.imdecode(image_array, cv2.IMREAD_COLOR) cv2.imshow('time={}'.format(t), image) cv2.moveWindow('time={}'.format(t), 0, 0) if cv2.waitKey(0) == 27: break else: cv2.destroyAllWindows() ``` # My Switch Game(Challenge2) Develop a console-based snake game on switch. Playing game with switch controller which BT traffic is relayed by a script running on ubuntu. In order to solve it, you should do reserve engineering on game's .nro file and analysis the traffic. And the source code of snake game is based on https://github.com/CompSciOrBust/Cpp-Snake-NX/ Attachment: `snake.nro` `log.log` Hint: flag's format is RCTF{xxx} and length of "RCTF{xxx}" is 32. Description: Relay bt traffic and capture by https://github.com/mart1nro/joycontrol/blob/master/scripts/relay_joycon.py Flag: RCTF{ddzljsqpaw6h31an5tgeaz75t0} Solution: 1. Reserve engineering(IDAPython plugin:[nxo64](https://github.com/reswitched/loaders)/[SwitchIDAProLoader](https://github.com/pgarba/SwitchIDAProLoader)): * Flag is generated by random number and the `seed` is determined by `nTail*4 + dir - 1` We can found an encrypted array that including flag's format. To decrypt, `xor` with `0x44`. `flag[:5]` and `flag[-1]` is `RCTF{}`, other chars on flag is generated char by char with the seed above: `flagchar = flagalphabet[rand() % strlen(flagalphabet)]` By the way, the generation of the coordinate of the next score is ahead of the generation of flagchar. ``` fruitX = rand() % width; fruitY = rand() % height; ``` * In `log.log`, we can found there are some `RUMBLE_DATA` packets in output reports. After filtering, there are 32 rumble packets in total that corresponds to flag's length. So we can assume that when the snake scores a point, vibration packet was sent to Switch Pro Controller. We can also validate the assumption by reserve engineering. * The snake is controlled by Direction Keys on the Controller. * Get the random number generation algorithm whose implement is depends on the complier. ```c unsigned __int64 rand() { __int64 v0; // x0 unsigned __int64 v1; // x1 v0 = sub_710007F0A0(); v1 = 6364136223846793005LL * *(_QWORD *)(v0 + 232) + 1; *(_QWORD *)(v0 + 232) = v1; return (v1 >> 32) & 0x7FFFFFFF; } ``` **We also can emulate running environment and use emulator to generate random numbers with the seed we assigned. The solution we provided was chose this method.** 2. Building Environment * Emulators: [Yuzu](https://yuzu-emu.org/)、[Ryujinx](https://ryujinx.org/) * Development: https://switchbrew.org/wiki/Setting_up_Development_Environment 3. Analysis the log file We can make use of this script and do some modification: https://github.com/mart1nro/joycontrol/blob/master/scripts/parse_capture.py According to the time when the Switch Pro Controller receive the rumble packet to find the last direction before the snake scores. And then `seed` can be calculated. We can print all the seeds we got. ```python import argparse import struct from joycontrol.report import InputReport, OutputReport, SubCommand import math DIR = { 0b00001000: ('LEFT', 1), 0b00000100: ('RIGHT',2), 0b00000010: ('UP', 3), 0b00000001: ('DOWN', 4) } RUMBLE = [4, 180, 1, 78, 4, 180, 1, 78] """ joycontrol capture parsing example. Usage: parse_capture.py <capture_file> parse_capture.py -h | --help """ def _eof_read(file, size): """ Raises EOFError if end of file is reached. """ data = file.read(size) if not data: raise EOFError() return data def get_rumble_timestamps(): rumble_timestamps = [i[0] for i in output_reports if i[1].get_rumble_data() == RUMBLE] return rumble_timestamps def get_dir_inputs(): dir_inputs = [(i[0], i[1].data[6]) for i in input_reports if i[1].data[6] & 0b00001111 != 0] return dir_inputs if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('capture_file') args = parser.parse_args() # list of time, report tuples input_reports = [] output_reports = [] with open(args.capture_file, 'rb') as capture: try: start_time = None while True: # parse capture time time = struct.unpack('d', _eof_read(capture, 8))[0] if start_time is None: start_time = time # parse data size size = struct.unpack('i', _eof_read(capture, 4))[0] # parse data data = list(_eof_read(capture, size)) if data[0] == 0xA1: report = InputReport(data) # normalise time input_reports.append((time, report)) elif data[0] == 0xA2: report = OutputReport(data) # normalise time output_reports.append((time, report)) else: raise ValueError(f'Unexpected data.') except EOFError: pass dir_input_list = get_dir_inputs() rumble_timestamps = get_rumble_timestamps() print(dir_input_list) print(rumble_timestamps) tailcnt = cursor = 0 seeds = [] # The last direction of before snake scoring a point can be found by the timestamp when the rumble packet was sent. for timestamp in rumble_timestamps: while cursor < len(dir_input_list) and dir_input_list[cursor][0] <= timestamp: cursor += 1 lastdir_before_rumble = dir_input_list[cursor-1][1] # In order to get the formula to calculate seed, you should do reserve engineering on game nro file. seed = tailcnt*4 + DIR[lastdir_before_rumble][1] - 1 seeds.append(str(seed)) tailcnt += 1 print(len(seeds), seeds) open('seeds.txt', 'w').write(' '.join(seeds)) # now plz place seeds.txt to switch emulator's /sdcard folder # and then run the rand.nro file you complied just now to generate random numbers # You should press a key on your keyboard correspond to 'A' in Pro Controller. # At the end, flag will put into flag.txt # For Ryujinx, /sdcard can be accessed by clicking Open Ryujinx Folder under the File menu in the GUI. # And key 'Z' on keyboard corresponds to 'A' in Pro Controller. ``` 4. Emulation & GetFLAG There is a great and easy demo to help you develop quickly. https://github.com/switchbrew/switch-examples/tree/master/templates/application Write some code to generate random coordinates and flag chars by the given seeds. There we get the flag. ```c const int width = 77; const int height = 41; const char* flagalphabet = "0123456789abcdefghijklmnopqrstuvwxyz_"; const char* flagformat="RCTF{}"; const int flaglen = 32; void solve(){ FILE *seeds = fopen("seeds.txt", "r"), *flag = fopen("flag.txt", "w"); if(seeds==NULL || flag==NULL){ puts("failed to open file"); return; } int seed, x, y, flagchar; puts("======Solving..."); for(int i=0;i<flaglen;i++){ if(i!=0){ fscanf(seeds,"%d",&seed); srand(seed); x = rand() % width, y = rand() % height; if(i < strlen(flagformat) - 1) flagchar = flagformat[i]; else if(i == flaglen - 1) flagchar = flagformat[strlen(flagformat) - 1]; else flagchar = flagalphabet[rand() % strlen(flagalphabet)]; }else x=-1, y=-1, flagchar = flagformat[0]; printf("[Seed=%d] (%d, %d) %c\n", seed, x, y, flagchar); fputc(flagchar, flag); } fclose(seeds); fclose(flag); } ```
using UserFetchSteam.API.Types; // UserFetchSteam API tipleri için gerekli using ifadesi using UserFetchSteam.API.Wrappers; // UserFetchSteam API sınıf sarmalları için gerekli using ifadesi using System; // Genel C# sistem kütüphanesi using System.Collections.Generic; // Koleksiyon tiplerini kullanmak için gerekli kütüphane using System.Linq; // LINQ sorguları için gerekli kütüphane namespace UserFetchSteam { // Steam istemci işlemlerini yöneten Client sınıfı public class Client { private List<ICallback> Callbacks = new List<ICallback>(); // Geri çağırım nesnelerinin listesi public SteamClient009 SteamClient; // Steam istemci nesnesi public SteamUser012 SteamUser; // Steam kullanıcı nesnesi public SteamUserStats007 SteamUserStats; // Steam kullanıcı istatistikleri nesnesi private int Pipe; // Steam bağlantı kanalı private int User; // Steam kullanıcı kimliği private bool RunningCallbacks; // Geriçağırımların çalışıp çalışmadığını tutan bayrak // Sınıfın yıkıcı (finalizer) metodu ~Client() { if (this.SteamClient == null) return; // Kullanıcıyı serbest bırak ve bağlantıyı kapat this.SteamClient.ReleaseUser(this.Pipe, this.User); this.User = 0; this.SteamClient.ReleaseSteamPipe(this.Pipe); this.Pipe = 0; } // Steam istemciyi başlatan metot public bool Initialize(long appId) { if (appId != 0L) Environment.SetEnvironmentVariable("SteamAppId", appId.ToString()); // Steam kurulum yolu alınıyor ve yükleniyor if (Steam.GetInstallPath() == null || !Steam.Load()) return false; // Steam istemci arabirimini oluştur this.SteamClient = Steam.CreateInterface<SteamClient009>("SteamClient009"); if (this.SteamClient == null) return false; // Steam bağlantı kanalı oluştur this.Pipe = this.SteamClient.CreateSteamPipe(); if (this.Pipe == 0) return false; // Küresel Steam kullanıcısına bağlan this.User = this.SteamClient.ConnectToGlobalUser(this.Pipe); if (this.User == 0) return false; // Steam kullanıcı ve istatistik nesnelerini al this.SteamUser = this.SteamClient.GetSteamUser012(this.User, this.Pipe); this.SteamUserStats = this.SteamClient.GetSteamUserStats006(this.User, this.Pipe); return true; } // Belirli türde bir geri çağırım nesnesi oluşturan ve kaydeden metot public TCallback CreateAndRegisterCallback<TCallback>() where TCallback : ICallback, new() { // Geri çağırım nesnesi oluştur ve kaydet TCallback callback = new TCallback(); this.Callbacks.Add((ICallback)callback); return callback; } // Geri çağırımları işleyen metot public void RunCallbacks(bool server) { if (this.RunningCallbacks) return; this.RunningCallbacks = true; CallbackMessage message = new CallbackMessage(); int call = 0; // Geri çağırım mesajlarını işle while (Steam.GetCallback(this.Pipe, ref message, ref call)) { // Belirli tipteki geri çağırımları çalıştır foreach (ICallback callback in this.Callbacks.Where<ICallback>((Func<ICallback, bool>)(candidate => { if (candidate.Id == message.m_iCallback) return candidate.Server == server; return false; }))) callback.Run(message.m_pubParam); // Son geri çağırımı serbest bırak Steam.FreeLastCallback(this.Pipe); } this.RunningCallbacks = false; } } }
<?php namespace App\Project\Application\Queries; use App\Project\Domain\PostAggregate; use Symfony\Component\Config\Definition\Exception\Exception; class QueryBus { /** @var array<AbstractQueryHandler> $handlers */ private array $handlers = []; public function registerHandler(string $queryClass, AbstractQueryHandler $handler): void { $this->handlers[$queryClass] = $handler; } /** * @param AbstractQuery $query * @return PostAggregate|array|PostAggregate[] */ public function handle(AbstractQuery $query): PostAggregate|array { $queryClass = get_class($query); if (!isset($this->handlers[$queryClass])) { throw new Exception(`Обработчик для запроса {$queryClass} не найден.`); } $handler = $this->handlers[$queryClass]; return $handler->handle($query); } }
import "./Likes.css"; import { useState, useEffect } from "react"; // material import Grid from "@material-ui/core/Grid"; //components import NavBar from "../../Componentss/Header/NavBar"; import CardSuperhero from "../../Componentss/Card/CardSuperhero"; const Likes = () => { const [favoritosList, setFavoritosList] = useState([]); const [search, setSearch] = useState(""); const traerLocStor = () => { const personajes = JSON.parse(localStorage.getItem("personajesFavorito")); setFavoritosList(personajes); }; const onSearchChange = (event) => { setSearch(event.target.value); }; const searchingTerm = (search) => { return function (x) { return x.name.includes(search) || !search; }; }; useEffect(() => { traerLocStor(); }, []); return ( <div> <NavBar onSearchChange={onSearchChange} value={search} to="/" text='home' /> <div> {favoritosList && favoritosList.length > 0 ? <Grid container direction="row" justify="center" alignItems="center"> {favoritosList.length && favoritosList .filter(searchingTerm(search)) .map((per, id) => ( <CardSuperhero data={per} key={id} id={id.toString()} img={`${per.thumbnail.path}.${per.thumbnail.extension}`} name={per.name} isInteractive={false} /> ))} </Grid> : <h1 className="textAlert" >you don't have favourites</h1> } </div> </div> ); }; export default Likes;
package com.example.beans; import com.example.service.VehicleServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("vehicleBean") public class Vehicle { private String name = "Honda"; private final VehicleServices vehicleServices; @Autowired public Vehicle(VehicleServices vehicleServices){ this.vehicleServices = vehicleServices; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public VehicleServices getVehicleServices() { return vehicleServices; } public void printHeello(){ System.out.println("Printing Hello from Component Vehicle Bean"); } @Override public String toString(){ return "Vehicle name is = " + this.name; } }
#include <stdlib.h> #include <stdio.h> #include "../include/glaze.h" /* Default error callback Use by calling glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(gl_error_callback, 0); */ void GLAPIENTRY glErrorCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* whatever ) { // To improve this see https://www.khronos.org/opengl/wiki/Debug_Output // Should this make use of glHandleErrors below? fprintf(stderr, "OpenGL Error: type = 0x%x, severity = 0x%x, message = %s\n", type, severity, message ); exit(EXIT_FAILURE); } void glHandleErrors(char* message) { GLenum err = glGetError(); do { if (err == GL_NO_ERROR) return; else if (err == GL_INVALID_ENUM) fprintf(stderr, "OpenGL Error: invalid enum\n"); else if (err == GL_INVALID_VALUE) fprintf(stderr, "OpenGL Error: invalid value\n"); else if (err == GL_INVALID_OPERATION) fprintf(stderr, "OpenGL Error: invalid operation\n"); else if (err == GL_STACK_OVERFLOW) fprintf(stderr, "OpenGL Error: stack overflow\n"); else if (err == GL_STACK_UNDERFLOW) fprintf(stderr, "OpenGL Error: stack underflow\n"); else if (err == GL_OUT_OF_MEMORY) fprintf(stderr, "OpenGL Error: out of memory\n"); else if (err == GL_INVALID_FRAMEBUFFER_OPERATION) fprintf(stderr, "OpenGL Error: invalid framebuffer operation\n"); else if (err == GL_CONTEXT_LOST) fprintf(stderr, "OpenGL Error: context lost\n"); else fprintf(stderr, "OpenGL Error: unknown error\n"); } while ((err = glGetError()) != GL_NO_ERROR); fprintf(stderr, "Error: %s\n", message); exit(EXIT_FAILURE); } /* Can check shader and program, user must provide the matching functions Only prints something if OpenGL set an info log. Otherwise behaves as all other OpenGL functions, setting a GLenum error */ void glCheckShaderProgram( GLuint program, GLenum pname, void (*glGetiv)(GLuint, GLenum, GLint*), void (*glGetInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*), void (*glDelete)(GLuint), char* message ) { GLuint result = GL_FALSE; glGetiv(program, pname, &result); if (result == GL_TRUE) return; // if result == GL_FALSE _and_ if program or pname is invalid GLint length = 0; // includes null char glGetiv(program, GL_INFO_LOG_LENGTH, &length); if (length > 0) { char* error = malloc(length); glGetInfoLog(program, length, NULL, error); glDelete(program); fprintf(stderr, "OpenGL Error: %s\nError: %s\n", error, message); } glHandleErrors("encountered while checking shader/program"); exit(EXIT_FAILURE); } GLuint glMakeShader(GLenum type, const char* const* source) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, source, NULL); glCompileShader(shader); glHandleErrors("compiling shader"); glCheckShaderProgram( shader, GL_COMPILE_STATUS, glGetShaderiv, glGetShaderInfoLog, glDeleteShader, "could not compile shader" ); return shader; } GLuint glMakeProgram(GLuint *shaders, size_t n) { GLuint program = glCreateProgram(); char message[24]; for (size_t i = 0; i < n; i++) { glAttachShader(program, shaders[i]); snprintf(message, sizeof(message), "attaching shader %u", i); glHandleErrors(message); } glLinkProgram(program); glCheckShaderProgram( program, GL_LINK_STATUS, glGetProgramiv, glGetProgramInfoLog, glDeleteProgram, "could not link program" ); glValidateProgram(program); glCheckShaderProgram( program, GL_VALIDATE_STATUS, glGetProgramiv, glGetProgramInfoLog, glDeleteProgram, "invalid program" ); return program; } //int main(int argc, char** argv) //{ // return 0; //}
"use client"; import React from "react"; import z from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { Form } from "../ui/form"; const formSchema = z.object({ firstName: z.string(), lastName: z.string(), email: z.string(), phone: z.number().min(10).max(10), gender: z.enum(["Male", "Female"]), }); type formType = z.infer<typeof formSchema>; const PersonalInfoForm = () => { const form = useForm<formType>({ resolver: zodResolver(formSchema), }); const onSubmit = (value: formType) => { console.log(value); }; return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}></form> </Form> ); }; export default PersonalInfoForm;
import { closeConnection, connectDatabase } from "@/Models"; import { UserModel, beneficiariesProps, findUserByEmail, findUserByPhoneNumber, notificationsProps, userProps, } from "@/Models/user"; import { getServerSession } from "next-auth"; import { authOptions } from "../../auth/[...nextauth]/options"; export const PATCH = async (req: Request) => { const { state, street_address, city, nextOfKin, nokName, }: { state: string; city: string; street_address: string; nextOfKin: string; nokName: string; } = await req.json(); const session = await getServerSession(authOptions); if (!session?.user) { return new Response(null, { status: 401, statusText: "Unathorized Please Login", }); } const { email } = session.user; if (!state && !city && !street_address && !nextOfKin && !nokName) { return new Response(null, { status: 403, statusText: "Missing field(s)", }); } await connectDatabase(); const user: userProps<beneficiariesProps> | null = (await findUserByEmail(email as string)) || (await findUserByPhoneNumber(email as string)); if (!user) { await closeConnection(); return new Response(null, { status: 404, statusText: "User not found (Invalid ID)", }); } if (user.disableAccount) { await closeConnection(); return new Response(null, { status: 400, statusText: "Account is disabled", }); } if (user.suspisiousLogin) { await closeConnection(); return new Response(null, { status: 400, statusText: "Cannot perform this action right now", }); } if (user.kyc_steps.length >= 2) { await closeConnection(); return new Response(null, { status: 429, statusText: "ID Details Already Added", }); } if (user.KYC_completed) { await closeConnection(); return new Response(null, { status: 429, statusText: "KYC Completed already", }); } const new_notification: notificationsProps = { time: Date.now(), type: "info", message: "Identification details has been added successfully", }; const updateValues: userProps<beneficiariesProps> | {} = { KYC: { ...user.KYC, address: { ...user.KYC.address, state: state, street_address: street_address, city: city, }, nextOfKin: { name: nextOfKin, nok: nokName, }, }, kyc_steps: ["first", "second"], notifications: [...user.notifications, new_notification], }; try { await UserModel.findByIdAndUpdate(user._id, updateValues); await closeConnection(); return new Response(null, { status: 201, statusText: "KYC personal details updated successfully", }); } catch (error) { return new Response(null, { status: 500, statusText: "Server error", }); } };
package com.sist.myapp; import java.util.*; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sist.dao.*; public class MainClass { private SeoulDAO dao; public void setDao(SeoulDAO dao) { this.dao = dao; } public static void main(String[] args) { String[] table={"","seoul_location","seoul_nature","seoul_shop"}; Scanner scan=new Scanner(System.in); System.out.println("데이터베이스 선택:"); int no=scan.nextInt(); Map map=new HashMap(); map.put("seoul_tbl", table[no]); //seoul-mapper.xml 에서 ${seoul_tbl} 키값과 같아야 함 => map.get("seoul_tbl"); //Map => 키, VO => getXxx() ApplicationContext app= new ClassPathXmlApplicationContext("app.xml"); MainClass mc=(MainClass)app.getBean("mc"); List<SeoulLocationVO> list=mc.dao.seoulListData(map); for(SeoulLocationVO vo:list) { System.out.println("이름:"+vo.getTitle()); System.out.println("주소:"+vo.getAddress()); System.out.println("소개:"+vo.getMsg()); System.out.println("------------------------------"); } } }
import { useState, useRef, useEffect } from 'react'; import { useTransition } from './useTransition'; import type { FluidValue, TransitionValueConfig, AssignValue } from '../types'; export interface UseMountConfig { from: number; enter: number | AssignValue; exit: number | AssignValue; enterConfig?: TransitionValueConfig; exitConfig?: TransitionValueConfig; config?: TransitionValueConfig; } /** * `useMount` * * applies mounting and unmounting of a component according to state change * applying transitions * * @param state - boolean indicating mount state of a component * @param config - the config object `UseMountConfig` */ export const useMount = (state: boolean, config: UseMountConfig) => { const initial = useRef(true); const [mounted, setMounted] = useState(false); const { from, enter, exit, config: innerConfig, enterConfig, exitConfig, } = useRef(config).current; const [animation, setAnimation] = useTransition(from, innerConfig); useEffect(() => { if (state) { initial.current = true; setMounted(true); } else { initial.current = false; setAnimation(exit, exitConfig, function ({ finished }) { if (finished) { setMounted(false); } }); } }, [state]); useEffect(() => { if (mounted && initial.current) { setAnimation(enter, enterConfig); } }, [mounted, initial.current]); return ( callback: (animation: FluidValue, mounted: boolean) => React.ReactNode ) => callback(animation, mounted); };
import { As, Box, Flex, HStack, Icon, Show, Tag, TagLabel, Text, useColorModeValue, } from "@chakra-ui/react"; import { Link } from "react-router-dom"; type TMenuItemElement = { title: string; to: string; icon: As<any>; active: boolean; isMenuExpanded: boolean; count?: number; }; function MenuItemElement({ icon, title, to, active, count, isMenuExpanded, }: TMenuItemElement) { const hoverBgActive = useColorModeValue("blackAlpha.100", "gray.600"); const hoverBgNoActive = useColorModeValue("blackAlpha.200", "gray.700"); const bg = useColorModeValue("blackAlpha.200", "gray.700"); return ( <Box as={Link} to={to} alignItems="center" h="28px" w="100%" px={3} py="1" borderRadius="lg" bg={active ? bg : "transparent"} _hover={{ bg: active ? hoverBgActive : hoverBgNoActive, }} display="flex" alignContent="center" > <HStack spacing={2.5}> <Icon as={icon} w="4" h="4" /> <Show above="lg"> {isMenuExpanded && ( <Flex justifyContent="space-between" w="full"> <Text fontSize="sm" h="20px"> {title} </Text> {count && ( <Tag size="sm" borderRadius="full" variant="solid" colorScheme="red" > <TagLabel>{count}</TagLabel> </Tag> )} </Flex> )} </Show> </HStack> </Box> ); } export default MenuItemElement;
namespace TestSingle is // OK: static property: use Other.SingleStatic.some_value; // OK: method group with single static member: use Other.SingleStatic.do_something; si namespace MultiStatic is // OK: method group with multiple static members: use Other.MultiStatic.do_something; si namespace MixedStaticAndInstance is // OK: method group with one static and one instance member: use Other.MixedStaticAndInstance.do_something; si namespace MultiMixedStaticAndInstance is // OK: method group with multiple static and instance members: use Other.MultiMixedStaticAndInstance.do_something; si namespace MultiInstance is // Error: method group only instance members: use Other.MultiInstance.do_something; si namespace SingleInstance is // Error: instance property: use Other.SingleInstance.some_value; // Error: method group only instance members: use Other.SingleInstance.do_something; si namespace Other is class SingleStatic is some_value: int static; do_something(value: int) -> int static => value; si class MultiStatic is do_something(value: int) -> int static => value; do_something(value: string) -> string static => value; si class MixedStaticAndInstance is do_something(value: int) -> int static => value; do_something(value: string) -> string => value; si class MultiMixedStaticAndInstance is do_something(value: char) -> char static => value; do_something(value: int) -> int static => value; do_something(value: string) -> string => value; do_somethimg(value: short) -> short => value; si class MultiInstance is do_something(value: int) -> int => value; do_something(value: string) -> string => value; si class SingleInstance is some_value: int; do_something(value: string) -> string => value; si si
function [gca1e, gca2] = ambi_plot_rE( S, V, M, C, fig_title, mode, ... ele_min, ele_max ) %ambi_plot_rE() produce plots of rE vs stimulus direction % S is real speaker array struct % V is virutal speaker array struct % M is decoder matrix % C is the channel definition struct % mode selects various plots, see switch statement % % TODO: needs a major cleanup %{ This file is part of the Ambisonic Decoder Toolbox (ADT). Copyright (C) 2013 Aaron J. Heller This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. %} % Author: Aaron J. Heller <heller@ai.sri.com> % $Id: 97f59e47cfef44ec2a751ed17ac11184aebd73ea $ %% defaults if ~exist('fig_title', 'var') || isempty(fig_title) fig_title = strrep(S.name,'_',' '); end; if ~exist('mode','var') || isempty(mode) mode = 5; end; if ~exist('ele_min', 'var') || isempty(ele_min) ele_min = -88; end if ~exist('ele_max', 'var') || isempty(ele_max) ele_max = +88; end shaded_renderer = ~inOctave(); fig_title_sanitized = strrep(fig_title, '_', ' '); %% girds n_phi = 45; % number of vertical divisions n_theta = 90; % number of horizontal divisions d_phi = pi/n_phi; % delta phi d_theta = 2*pi/n_theta; % delta theta switch mode case 1 % full sphere [geo.az, geo.el] = meshgrid(... linspace(... 0+d_theta/2,... % ~0 0 2*pi-d_theta/2,... % 2pi 360 n_theta), ... % 90 linspace(... pi/2+d_phi/2,... %~ +pi/2 +90 -pi/2-d_phi-d_phi/2,...%~ -pi/2 -90 n_phi)); %~ 45 case 2 % ?? [geo.az, geo.el] = meshgrid(... [-pi/90,pi/90], ... linspace(0,2*pi,2*n_phi)); case 3 % Y-plane circle [geo.az, geo.el] = meshgrid(... linspace(0+d_theta/2, pi-d_theta/2, n_theta), ... linspace(pi/2+d_phi/2, -pi/2-d_phi-d_phi/2, n_phi)); case 4 % left hemisphere [geo.az, geo.el] = meshgrid(... linspace(0,180,n_theta+1) * pi/180, ... ...%linspace(0+d_theta/2, pi-d_theta/2, n_theta), ... linspace(pi/2+d_phi/2, -pi/2-d_phi+d_phi/2, n_phi)); case 5 geo = AzElGrid(-180:4:180-4, ele_min:4:ele_max); end if false d_omega = cos(geo.el) * d_phi * d_theta; geo.az = geo.az; geo.el = geo.el; geo.w = d_omega / (4*pi); [geo.x, geo.y, geo.z] = sph2cart(geo.az, geo.el, 1); end %% compute rE and rV geo.a = ambi_sample_Y_sph(geo.az(:), geo.el(:), C)'; [rV, rE, P, E] = ambi_rVrE_Y(M, [S.x, S.y, S.z]', geo.a); %% grid plots ambi_plot_dir_error_grid([], rE, geo, S, V, 'rE', fig_title, fig_title_sanitized); ambi_plot_dir_error_grid([], rV, geo, S, V, 'rV', fig_title, fig_title_sanitized); %% decoder energy per Batke % nominally for matching loudness of different decoders decoder_energy = sum( abs(M(:)).^2 ); fprintf('\ndecoder energy = %d\n', decoder_energy); %% rV rE direction difference plot if true gcadd = figure(); set(gcadd,'numbertitle','on','name', 'rV rE direction difference'); imagesc( geo.az(1,:)*180/pi, geo.el(:,1)*180/pi,... reshape(ambi_dir_diff(rV.u,rE.u) .* 180/pi, size(geo.x))); axis('xy'); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); caxis([0,10]); title_bold18(sprintf('%s\nrV rE Direction Difference',fig_title_sanitized)); colorbar print(gcadd,'-dpng','-r100',... fullfile(ambi_decoders_dir(true),[fig_title '-rVrE-diff.png'])); end %% 3x2 panel of rE plots % FIXME this messes up in Octave 3.6.4 on MacOS % some clues here % http://octave.1599824.n4.nabble.com/FLTK-refresh-required-td4655874.html if true gca2=figure(); figtitle(fig_title_sanitized, ... 'fontsize', 16, 'fontweight', 'bold'); set(gca2,'units','normalized','outerposition',[0 0 1 1]); set(gca2,'numbertitle','on','name',fig_title); %set(gca2,'LooseInset',get(gca,'TightInset')); set(gca2, 'PaperPositionMode', 'auto'); %% magnitude of rE sp231=subplot(2,3,1); % top, left plot %mask = geo.az>=0; re.xx = reshape(rE.xyz(1,:), size(geo.x)); re.yy = reshape(rE.xyz(2,:), size(geo.y)); re.zz = reshape(rE.xyz(3,:), size(geo.z)); re.rr = reshape(rE.r, size(geo.x)); %mesh(re.xx,re.yy,re.zz,re.rr); surf_rE = surf(re.xx,re.yy,re.zz,re.rr); caxis([0,1]); % set up view label_cardinal_directions(1.2*max(re.rr(:))); title_bold18('mag and dir of rE'); set_surface_rendering(sp231,surf_rE, shaded_renderer); % bottom, left plot sp234=subplot(2,3,4); % FIXME, want image flipped left right. imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, re.rr); caxis([0,1]); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); %axis([-180,180-4,-90,90]); %% FIXME %set(sp234,'XDir','reverse') colorbar; title_bold18('magnitude of rE vs. test direction'); %refresh; %% angular error in degrees sp232=subplot(2,3,2); % top middle plot geo.u = [geo.x(:)'; geo.y(:)'; geo.z(:)']; angle_err = reshape(ambi_dir_diff(rE.u, geo.u), size(geo.x)); surf_angle_err = surf(geo.x, geo.y, geo.z, angle_err*180/pi); caxis([0,10]); label_cardinal_directions(1.2) title_bold18('rE angular error (degrees)'); %refresh; set_surface_rendering(sp232,surf_angle_err, shaded_renderer) % bottom, middle plot sp235=subplot(2,3,5); imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, angle_err*180/pi); caxis([0,10]); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); %axis([-180,180-4,-90,90]); %% FIXME colorbar; title_bold18('rE angular error (degrees)'); %refresh; %% Energy by source direction (not preceived direction!) sp236=subplot(2,3,6); % bottom right plot E2 = reshape(E, size(geo.x)); % find the energy closest to straight ahead E2_100 = squeeze(E2( ... abs(geo.az)==min(abs(geo.az(:))) & ... abs(geo.el)==min(abs(geo.el(:))))); E2 = 10 * log10(E2./E2_100(1)); %set (sp236, 'zlim', [0 1]); imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, E2); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); %axis([-180,180-4,-90,90]); %% FIXME colorbar; caxis([-6,6]); title_bold18('Energy gain vs. test dir'); %refresh; % sp233= subplot(2,3,3); % top right plot %re.mmdb=10*log10(re.mm); %surf(geo.x.*re.mm, geo.y.*re.mm, geo.z.*re.mm, 85+10*log10(re.mm)); E2pos = E2-min(E2(:)) + 6; %surf(geo.x.*E2pos, geo.y.*E2pos, geo.z.*E2pos, E2); surf_Egain = surf(... E2pos .* reshape(rE.u(1,:),size(geo.x)), ... E2pos .* reshape(rE.u(2,:),size(geo.y)), ... E2pos .* reshape(rE.u(3,:),size(geo.z)), ... E2); caxis([-6,6]); label_cardinal_directions(1.2*max(E2(:))); title_bold18('mag and dir of Energy gain'); set_surface_rendering(sp233,surf_Egain, shaded_renderer); %% figure title if false figtitle(strrep(fig_title, '_', '\_'), ... 'fontsize', 16, 'fontweight', 'bold'); end %% if inOctave % axis([sp231,sp232,sp233],'equal'); % doesn't work in Octave axis(sp231,'equal'); axis(sp232,'equal'); axis(sp233,'equal'); else axis([sp231,sp232,sp233],'equal','vis3d'); axis([sp234,sp235,sp236],'xy'); end %refresh; %saveas(gca2,[fig_title '-spheres.pdf']); %orient(gca2,'landscape'); print(gca2,'-dpng','-r100',... fullfile(ambi_decoders_dir(true),[fig_title '-rE-spheres.png'])); %refresh; end % end of 3x2 panel of rE plots % try some plots for Paul ambi_plot_rV(rV,P, geo,fig_title, fig_title_sanitized); end function title_bold18(str) if inOctave() title(str); else title(str, 'FontSize', 18, 'FontWeight', 'bold'); end end function label_cardinal_directions(radius) hold_state = ishold(); if ~hold_state, hold on; end; qs = eye(3); qrad = 1.5; quiver3(-qrad*qs(:,1),-qrad*qs(:,2),-qrad*qs(:,3), ... qrad*qs(:,1), qrad*qs(:,2), qrad*qs(:,3), 2); radius=qrad; text(radius,0,0, 'Front', 'HorizontalAlignment', 'center'); text(-radius,0,0, 'Back', 'HorizontalAlignment', 'center'); text(0,radius,0, 'Left', 'HorizontalAlignment', 'center'); text(0,-radius,0, 'Right', 'HorizontalAlignment', 'center'); text(0,0,radius, 'Top', 'HorizontalAlignment', 'center'); text(0,0,-radius, 'Bottom','HorizontalAlignment', 'center'); hold off if ~hold_state, hold off; end; end function set_surface_rendering( axis, obj, shaded_renderer ) if shaded_renderer shading(axis,'interp'); set(obj, ... %findobj(gca,'type','surface'),... 'FaceLighting','phong',... 'AmbientStrength',.3,'DiffuseStrength',.8,... 'SpecularStrength',.9,'SpecularExponent',25,... 'BackFaceLighting','reverselit' ) %'unlit') %lighting phong camlight('left'); %lightangle(-45,30) %set(figure1,'Renderer','opengl') end end function [ ] = ambi_plot_rV( rE, E, geo, fig_title, fig_title_sanitized ) %UNTITLED Summary of this function goes here % Detailed explanation goes here %% 3x2 panel of rE plots % FIXME this messes up in Octave 3.6.4 on MacOS % some clues here % http://octave.1599824.n4.nabble.com/FLTK-refresh-required-td4655874.html shaded_renderer = ~inOctave(); if true gca2=figure(); figtitle(fig_title_sanitized, ... 'fontsize', 16, 'fontweight', 'bold'); set(gca2,'units','normalized','outerposition',[0 0 1 1]); set(gca2,'numbertitle','on','name',fig_title); %set(gca2,'LooseInset',get(gca,'TightInset')); set(gca2, 'PaperPositionMode', 'auto'); %% magnitude of rV sp231=subplot(2,3,1); % top, left plot %mask = geo.az>=0; re.xx = reshape(rE.xyz(1,:), size(geo.x)); re.yy = reshape(rE.xyz(2,:), size(geo.y)); re.zz = reshape(rE.xyz(3,:), size(geo.z)); re.rr = reshape(rE.r, size(geo.x)); %mesh(re.xx,re.yy,re.zz,re.rr); surf_rE = surf(re.xx,re.yy,re.zz,re.rr); caxis([0,1]); % set up view label_cardinal_directions(1.2*max(re.rr(:))); title_bold18('mag and dir of rV'); set_surface_rendering(sp231,surf_rE, shaded_renderer); % bottom, left plot sp234=subplot(2,3,4); % FIXME, want image flipped left right. imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, re.rr); caxis([0,1]); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); %axis([-180,180-4,-90,90]); %% FIXME %set(sp234,'XDir','reverse') colorbar; title_bold18('magnitude of rV vs. test direction'); %refresh; %% angular error in degrees sp232=subplot(2,3,2); % top middle plot geo.u = [geo.x(:)'; geo.y(:)'; geo.z(:)']; angle_err = reshape(ambi_dir_diff(rE.u, geo.u), size(geo.x)); surf_angle_err = surf(geo.x, geo.y, geo.z, angle_err*180/pi); caxis([0,10]); label_cardinal_directions(1.2) title_bold18('rV angular error (degrees)'); %refresh; set_surface_rendering(sp232,surf_angle_err, shaded_renderer) % bottom, middle plot sp235=subplot(2,3,5); imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, angle_err*180/pi); caxis([0,10]); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); axis([-180,180-4,-90,90]); %% FIXME colorbar; title_bold18('rV angular error (degrees)'); %refresh; %% Pressure by source direction (not preceived direction!) if true sp236=subplot(2,3,6); % bottom right plot E2 = reshape(E, size(geo.x)); % find the Pressure closest to straight ahead E2_100 = squeeze(E2( ... abs(geo.az)==min(abs(geo.az(:))) & ... abs(geo.el)==min(abs(geo.el(:))))); E2 = 10 * log10(E2./E2_100(1)); %set (sp236, 'zlim', [0 1]); imagesc(geo.az(1,:)*180/pi, geo.el(:,1)*180/pi, E2); xlabel('right<--- azimuth (deg) --->left'); ylabel('elevation (deg)'); axis([-180,180-4,-90,90]); %% FIXME colorbar; caxis([-6,6]); title_bold18('Pressure gain vs. test dir'); %refresh; % sp233= subplot(2,3,3); % top right plot %re.mmdb=10*log10(re.mm); %surf(geo.x.*re.mm, geo.y.*re.mm, geo.z.*re.mm, 85+10*log10(re.mm)); E2pos = E2-min(E2(:)) + 6; %surf(geo.x.*E2pos, geo.y.*E2pos, geo.z.*E2pos, E2); surf_Egain = surf(... E2pos .* reshape(rE.u(1,:),size(geo.x)), ... E2pos .* reshape(rE.u(2,:),size(geo.y)), ... E2pos .* reshape(rE.u(3,:),size(geo.z)), ... E2); caxis([-6,6]); label_cardinal_directions(1.2*max(E2(:))); title_bold18('mag and dir of Pressure gain'); set_surface_rendering(sp233,surf_Egain, shaded_renderer); end %% figure title if false figtitle(strrep(fig_title, '_', '\_'), ... 'fontsize', 16, 'fontweight', 'bold'); end %% if inOctave % axis([sp231,sp232,sp233],'equal'); % doesn't work in Octave axis(sp231,'equal'); axis(sp232,'equal'); axis(sp233,'equal'); else axis([sp231,sp232,sp233],'equal','vis3d'); axis([sp234,sp235,sp236],'xy'); end %refresh; %saveas(gca2,[fig_title '-spheres.pdf']); %orient(gca2,'landscape'); print(gca2,'-dpng','-r100',... fullfile(ambi_decoders_dir(true),[fig_title '-rV-spheres.png'])); %refresh; end % end of 3x2 panel of rE plots end
(function(win, $){ function clone(src,out){ for(var attr in src.prototype){ out.prototype[attr] = src.prototype[attr]; } } function Circle(){ this.item = $('<div class="circle"></div>'); } Circle.prototype.color = function(clr){ this.item.css('background', clr); } Circle.prototype.move = function(left, top){ this.item.css('left',left); this.item.css('top',top); }; Circle.prototype.get = function(){ return this.item; } function Rect(){ this.item = $('<div class="rect"></div>'); } clone(Circle, Rect); function selfDestructDecorator(obj) { obj.item.click(function() { obj.kill(); }) obj.kill = function() { obj.item.remove(); } } function RedCircleBuilder(){ this.item = new Circle(); this.init(); } RedCircleBuilder.prototype.init = function() { //NOTHING }; RedCircleBuilder.prototype.get = function() { return this.item; }; function BlueCircleBuilder(){ this.item = new Circle(); this.init(); } BlueCircleBuilder.prototype.init = function() { this.item.color("blue"); var rect = new Rect(); rect.color("yellow"); rect.move(40,40); selfDestructDecorator(rect); this.item.get().append(rect.get()); }; BlueCircleBuilder.prototype.get = function() { return this.item; }; ShapeFactory = function(){ this.types = {}; this.create = function(type){ return new this.types[type]().get(); }; this.register = function(type, cls){ if(cls.prototype.init && cls.prototype.get){ this.types[type] = cls; } } }; function Stage(id){ this.index = 0; this.context = $(id); this.SIG = 'stageItem_'; } Stage.prototype.add = function (item){ ++this.index; item.addClass(this.SIG + this.index); this.context.append(item); }; Stage.prototype.remove = function(index){ this.context.remove('.' + this.SIG + index); } function CompositeController(a) { this.a = a; } CompositeController.prototype.action = function (act) { var args = Array.prototype.slice.call(arguments); args.shift(); for(var item in this.a) { this.a[item][act].apply(this.a[item][act], args); } } var CircleGeneratorSingleton = (function(){ var instance; function init(){ var _aCircle = [], _stage, _sf = new ShapeFactory(), _cc = new CompositeController(_aCircle); function _position(circle, left, top){ circle.move(left, top); } function registerShape(name,cls){ _sf.register(name, cls); } function setStage(stg){ _stage = stg; } function create(left, top,type){ var circle = _sf.create(type); circle.move(left, top); return circle; } function tint(clr) { _cc.action('color', clr); } function move(left, top) { _cc.action('move', clr); } function add(circle){ _stage.add(circle.get()); _aCircle.push(circle); } function index(){ return _aCircle.length; } return {index:index, create:create, add:add, register:registerShape, setStage:setStage, tint: tint, move: move}; } return { getInstance: function(){ if(!instance){ instance = init(); } return instance; } } })(); $(win.document).ready(function(){ var cg = CircleGeneratorSingleton.getInstance(); cg.register('red', RedCircleBuilder); cg.register('blue', BlueCircleBuilder); cg.setStage(new Stage('.advert')); $('.advert').click(function(e){ var circle = cg.create(e.pageX-25, e.pageY-25,"red"); cg.add(circle); }); $(document).keypress(function(e){ if(e.key=='a'){ var circle = cg.create(Math.floor(Math.random()*600), Math.floor(Math.random()*600), "blue"); cg.add(circle); } else if(e.key === 't') { cg.tint('black'); } else if(e.key === 'ArrowRight') { cg.tint('+=5px', '+=0px'); } else if(e.key === 'ArrowLeft') { cg.tint('-=5px', '+=0px'); } }); }); })(window, jQuery);
220340320055 LOKESH PATIL KHARGHAR SECTION-1 Q-1 create table DEPT (DEPTNO int(2),DNAME varchar(15),LOC varchar(10)); insert into DEPT values (10,'ACCOUNTING','NEW YORK'), (20,'RESEARCH','DALLAS'), (30,'SALES','CHICAGO'), (40,'OPERATIONS','BOSTON'); Q-2 create table EMP (EMPNO int(4), ENAME varchar(10), JOB varchar(9), HIREDATE date, SAL float(7,2), COMM float(7,2), DEPTNO int(2)); insert into EMP values (7839,'KING','MANAGER','1991-11-17',5000,NULL,10), (7698,'BLAKE','CLERK','1981-05-01',2850,NULL,30), (7782,'CLARK','MANAGER','1981-06-09',2450,NULL,10), (7566,'JONES','CLERK','1981-04-02',2975,NULL,20), (7654,'MARTIN','SALESMAN','1981-09-28',1250,1400,30), (7499,'ALLEN','SALESMAN','1981-02-20',1600,300,30); Q-3 select * from EMP where SAL between 2500 and 5000; Q-4 select * from EMP order by ENAME desc; Q-5 select lower(JOB) from EMP; Q-6 select ENAME, LENGTH(ENAME) AS Length from EMP; Q-7 select DEPTNO, count(*) from EMP GROUP BY DEPTNO; Q-8 select DNAME, ENAME from EMP, DEPT where DEPT.DEPTNO = EMP.DEPTNO; Q-9 select ename from emp where ename like '%AR%'; Q-10 select ENAME,SAL,(SAL*0.2)'HRA' from EMP; SECTION -02 Q-01 create table TEMPP (String_a varchar(20), String_b varchar(20), Message varchar(20)); delimiter // create procedure PROC1 (str_a varchar(20), str_b varchar(20)) begin declare x int; set x = LOCATE(str_a,str_b); if (x!=0) then insert into TEMPP VALUES (str_a,str_b,'PRESENT'); else insert into TEMPP VALUES (str_a,str_b,'NOT PRESENT'); END IF; end; // delimiter ; call PROC1('DAC','CDAC'); Q-02 create table TEMPP2(side_a int, side_b int, side_c int, Result varchar(10)); delimiter // create function FUNC1(a int, b int, c int) returns boolean deterministic begin if (a+b>c AND b+c>a and c+a>b) THEN return TRUE; else return FALSE; END IF; end; // delimiter ; delimiter // create procedure Triangle( a int, b int, c int) begin if FUNC1(a,b,c) then insert into TEMPP2 values(a,b,c,'TRUE'); else insert into TEMPP2 values(a,b,c,'FALSE'); end if; end; // delimiter ; call Triangle(5,10,20);
# Section 18 RESTful API Testing with Rest Assured Pada materi ini mempelajari : - REST API Concept - Fundamental API Integration - BDD With Cucumber - REST ASSURED ## API Concept API mempunyai konsep: <br> - Client (request) -> Waiter - API (request) -> Chef - System/Server (request) <br> - Chef - System/Server (response) -> Waiter - API (response) -> Client (response) <br> ## Fundamental API Integration > Mobile App -> API Server -> EXT Process -> API Testing Test Process : - Record, Define API Information - Parsing, Filter or Recording API Data and then extract - Reconstruction API calls, and sent them from a simulate client - Test Validation ## BDD With Cucumber 1. Write Story 2. Map Steps to Java 3. Configure Stories 4. Run Stories 5. View Reports ## REST ASSURED - Supports for HTTP Method - Support for BDD / Gherkin ( Given, When, Then) - Use of Hamcrest matches for checks - User of Gpath for selecting element from JSON response # TASK # BANG INI ERROR MERAH MERAH KENAPA YA PUSING EUY <img src="screenshot/Screenshot_1.png"> <img src="screenshot/Screenshot_2.png"> <img src="screenshot/Screenshot_3.png"> <img src="screenshot/Screenshot_4.png"> <img src="screenshot/Screenshot_5.png"> <img src="screenshot/Screenshot_6.png">
import { createAxesHelper, createGridHelper } from './components/helpers.js' import { createCamera } from './components/camera.js'; import { createCube } from './components/basicObjects/cube.js'; import { createMeshGroup, createFractalGroup } from './components/meshGroups/meshGroup.js'; import { createLights } from './components/lights.js'; import { createScene } from './components/scene.js'; import { createControls } from './systems/controls.js'; import { createRenderer } from './systems/renderer.js'; import { Resizer } from './systems/Resizer.js'; import { Loop } from './systems/Loop.js'; import { Train } from './components/Train/Train.js'; import { loadBirds } from './components/birds/birds.js'; // These variables are module-scoped: we cannot access them // from outside the module let camera; let renderer; let scene; let loop; let controls; class World { // Create an instance of the World app constructor(container) { scene = createScene(); camera = createCamera(); renderer = createRenderer(); loop = new Loop(camera, scene, renderer); container.append(renderer.domElement) // add the automatically created <canvas> element to the page controls = createControls(camera, renderer.domElement); // const cube = createCube(); // create a Mesh containing the geometry and material //const meshGroup = createMeshGroup(); // create a Mesh group // const train = new Train(); const { ambientLight, mainLight } = createLights(); // create a light source // scene.add(createAxesHelper(), createGridHelper()); // add axis loop.updatables.push(controls); // add items to the tick array scene.add(ambientLight, mainLight); // add the light source and the mesh to the scene // resize the frustrum const resizer = new Resizer(container, camera, renderer); } // async function that waits for the models to load async init() { const { parrot, flamingo1, flamingo2, flamingo3, stork } = await loadBirds(); controls.target.copy(parrot.position); // move the target to the center of the front bird loop.updatables.push(parrot, flamingo1, flamingo2, flamingo3, stork) scene.add(parrot, flamingo1, flamingo2, flamingo3, stork); } // Render the scene render() { renderer.render(scene, camera); // draw a single frame } // animation loop start start() { loop.start(); } // animation loop end stop() { loop.stop(); } } export { World };
/// /// [Author] Alex (https://github.com/Alex525) /// [Date] 2020/3/31 15:28 /// import 'dart:math' as math; import 'dart:typed_data'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:photo_manager/photo_manager.dart'; import 'package:tuple/tuple.dart'; /// [ChangeNotifier] for assets picker. /// /// The provider maintain all methods that control assets and paths. /// By extending it you can customize how you can get all assets or paths, /// how to fetch the next page of assets, how to get the thumb data of a path. abstract class AssetPickerProvider<Asset, Path> extends ChangeNotifier { AssetPickerProvider({ this.maxAssets = 9, this.pageSize = 320, this.pathThumbSize = 80, List<Asset>? selectedAssets, }) { if (selectedAssets?.isNotEmpty == true) { _selectedAssets = List<Asset>.from(selectedAssets!); } } bool _mounted = true; /// Maximum count for asset selection. /// 资源选择的最大数量 int maxAssets; /// Assets should be loaded per page. /// 资源选择的最大数量 /// /// Use `null` to display all assets into a single grid. final int pageSize; /// Thumb size for path selector. /// 路径选择器中缩略图的大小 final int pathThumbSize; /// Clear all fields when dispose. /// 销毁时重置所有内容 @override void dispose() { super.dispose(); _isAssetsEmpty = false; _isSwitchingPath = false; _pathEntityList.clear(); _currentPathEntity = null; _currentAssets.clear(); _selectedAssets.clear(); _mounted = false; } bool get mounted => _mounted; /// Whether there are assets on the devices. /// 设备上是否有资源文件 bool _isAssetsEmpty = false; bool get isAssetsEmpty => _isAssetsEmpty; set isAssetsEmpty(bool value) { if (value == _isAssetsEmpty) { return; } _isAssetsEmpty = value; if(mounted){ notifyListeners(); } } /// Whether there are any assets can be displayed. /// 是否有资源可供显示 bool _hasAssetsToDisplay = false; /// Whether there are any assets can be displayed. /// 是否有资源可供显示 bool _hasAlbumsToDisplay = false; bool get hasAlbumsToDisplay => _hasAlbumsToDisplay; set hasAlbumsToDisplay(bool value){ if (value == _hasAlbumsToDisplay) { return; } _hasAlbumsToDisplay = value; if(mounted){ notifyListeners(); } } bool get hasAssetsToDisplay => _hasAssetsToDisplay; set hasAssetsToDisplay(bool value) { if (value == _hasAssetsToDisplay) { return; } _hasAssetsToDisplay = value; if(mounted){ notifyListeners(); } } /// Whether more assets are waiting for a load. /// 是否还有更多资源可以加载 bool get hasMoreToLoad => _currentAssets.length < _totalAssetsCount; /// The current page for assets list. /// 当前加载的资源列表分页数 int get currentAssetsListPage => (math.max(1, _currentAssets.length) / pageSize).ceil(); /// Total count for assets. /// 资源总数 int _totalAssetsCount = 0; int get totalAssetsCount => _totalAssetsCount; set totalAssetsCount(int value) { if (value == _totalAssetsCount) { return; } _totalAssetsCount = value; if(mounted){ notifyListeners(); } } /// If path switcher opened. /// 是否正在进行路径选择 bool _isSwitchingPath = false; bool get isSwitchingPath => _isSwitchingPath; set isSwitchingPath(bool value) { if (value == _isSwitchingPath) { return; } _isSwitchingPath = value; if(mounted){ notifyListeners(); } } /// Map for all path entity. /// 所有包含资源的路径里列表 /// /// Using [Map] in order to save the thumb data for the first asset under the path. /// 使用[Map]来保存路径下第一个资源的缩略数据。 final Map<String, Tuple2<Path, Uint8List?>?> _pathEntityList = {}; Map<String, Tuple2<Path, Uint8List?>?> get pathEntityList => _pathEntityList; /// How many path has a valid thumb data. /// 当前有多少目录已经正常载入了缩略图 /// /// This getter provides a "Should Rebuild" condition judgement to [Selector] /// with the path entities widget. /// 它为目录部件展示部分的 [Selector] 提供了是否重建的条件。 int get validPathThumbCount => _pathEntityList.values.where((Tuple2<Path, Uint8List?>? d) => d != null).length; /// The path which is currently using. /// 正在查看的资源路径 Path? _currentPathEntity; Path? get currentPathEntity => _currentPathEntity; set currentPathEntity(Path? value) { if (value == null || value == _currentPathEntity) { return; } _currentPathEntity = value; if(mounted){ notifyListeners(); } } /// Assets under current path entity. /// 正在查看的资源路径下的所有资源 List<Asset> _currentAssets = <Asset>[]; List<Asset> get currentAssets => _currentAssets; set currentAssets(List<Asset> value) { if (value == _currentAssets) { return; } _currentAssets = List<Asset>.from(value); if(mounted){ notifyListeners(); } } /// Selected assets. /// 已选中的资源 List<Asset> _selectedAssets = <Asset>[]; List<Asset> get selectedAssets => _selectedAssets; set selectedAssets(List<Asset> value) { if (value == _selectedAssets) { return; } _selectedAssets = List<Asset>.from(value); if(mounted){ notifyListeners(); } } /// Descriptions for selected assets currently. /// 当前已被选中的资源的描述 /// /// This getter provides a "Should Rebuild" condition judgement to [Selector] /// with the preview widget's selective part. /// 它为预览部件的选中部分的 [Selector] 提供了是否重建的条件。 String get selectedDescriptions => _selectedAssets.fold( <String>[], (List<String> list, Asset a) => list..add(a.toString()), ).join(); /// 选中资源是否为空 bool get isSelectedNotEmpty => selectedAssets.isNotEmpty; /// 是否已经选择了最大数量的资源 bool get selectedMaximumAssets => selectedAssets.length == maxAssets; set maximumAssets(int assetCount){ maxAssets = assetCount; notifyListeners(); } /// Get assets path entities. /// 获取所有的资源路径 Future<void> getAssetPathList(); /// Get thumb data from the first asset under the specific path entity. /// 获取指定路径下的第一个资源的缩略数据 Future<Uint8List?> getFirstThumbFromPathEntity(Path pathEntity); /// Get assets under the specific path entity. /// 获取指定路径下的资源 Future<void> getAssetsFromEntity(int page, Path pathEntity); /// Load more assets. /// 加载更多资源 Future<void> loadMoreAssets(); /// Select asset. /// 选中资源 void selectAsset(Asset item) { if (selectedAssets.length == maxAssets || selectedAssets.contains(item)) { return; } final List<Asset> _set = List<Asset>.from(selectedAssets); _set.add(item); selectedAssets = _set; } /// Un-select asset. /// 取消选中资源 void unSelectAsset(Asset item) { final List<Asset> _set = List<Asset>.from(selectedAssets); _set.remove(item); selectedAssets = _set; } void clearAll(){ selectedAssets = <Asset>[]; } /// Switch path entity. /// 切换路径 Future<void> switchPath([Path? pathEntity]); } class DefaultAssetPickerProvider extends AssetPickerProvider<AssetEntity, AssetPathEntity> { /// Call [getAssetList] with route duration when constructing. /// 构造时根据路由时长延时获取资源 DefaultAssetPickerProvider({ List<AssetEntity>? selectedAssets, this.requestType = RequestType.image, this.filterOptions, int maxAssets = 9, int pageSize = 80, int pathThumbSize = 80, Duration routeDuration = const Duration(milliseconds: 300), }) : super( maxAssets: maxAssets, pageSize: pageSize, pathThumbSize: pathThumbSize, selectedAssets: selectedAssets, ) { Future<void>.delayed(routeDuration).then( (dynamic _) async { await getAssetPathList(); // hasAlbumsToDisplay = true; await getAssetList(); }, ); } /// Request assets type. /// 请求的资源类型 final RequestType requestType; /// Filter options for the picker. /// 选择器的筛选条件 /// /// Will be merged into the base configuration. /// 将会与基础条件进行合并。 final FilterOptionGroup? filterOptions; @override Future<void> getAssetPathList() async { // _pathEntityList.clear(); // Initial base options. // Enable need title for audios and image to get proper display. final FilterOptionGroup options = FilterOptionGroup( imageOption: const FilterOption( needTitle: true, sizeConstraint: SizeConstraint(ignoreSize: true), ), audioOption: const FilterOption( needTitle: true, sizeConstraint: SizeConstraint(ignoreSize: true), ), ); // Merge user's filter option into base options if it's not null. if (filterOptions != null) { options.merge(filterOptions!); } // Get All Photos final List<AssetPathEntity> _other = await PhotoManager.getAssetPathList( onlyAll: true, type: requestType, filterOption: options, ); // Get all albums final List<AssetPathEntity> _list = await PhotoManager.getAssetPathList( type: requestType, filterOption: options, ); // Remove recents from the list of albums _list.removeWhere((element) => element.name == (Platform.isIOS ? "Recents" : "Recent")); // Add recents into the first index _list.insert(0, _other.first); List<Future<void>> otherList = []; for (final AssetPathEntity pathEntity in _list) { // Use sync method to avoid unnecessary wait. if(_pathEntityList[pathEntity.id] == null){ if (requestType != RequestType.audio) { final x = getFirstThumbFromPathEntity(pathEntity).then((Uint8List? data) { _pathEntityList[pathEntity.id] = Tuple2(pathEntity, data); }); otherList.add(x); } } } await Future.wait(otherList); // Set first path entity as current path entity. if (_pathEntityList.isNotEmpty) { hasAlbumsToDisplay = true; notifyListeners(); } } /// Get assets list from current path entity. /// 从当前已选路径获取资源列表 Future<void> getAssetList() async { if (_pathEntityList.isNotEmpty) { Tuple2<AssetPathEntity, Uint8List?>? _entity = _pathEntityList.values.firstWhere((element) => element?.item1.name == (Platform.isIOS ? "Recents" : "Recent")); if(_entity != null){ _currentPathEntity = _entity.item1; } else{ _currentPathEntity = _pathEntityList.values.elementAt(0)?.item1; } totalAssetsCount = currentPathEntity!.assetCount; await getAssetsFromEntity(0, currentPathEntity!); // Update total assets count. } else { isAssetsEmpty = true; } } @override Future<void> getAssetsFromEntity(int page, AssetPathEntity pathEntity) async { _currentAssets.clear(); _currentAssets = (await pathEntity.getAssetListPaged( page: page, size: pageSize, )).toList(); // _currentAssets = _currentAssets.toSet().toList(); _hasAssetsToDisplay = currentAssets.isNotEmpty; if(mounted){ notifyListeners(); } } @override Future<void> loadMoreAssets() async { final List<AssetEntity> assets = (await currentPathEntity!.getAssetListPaged( page: currentAssetsListPage, size: pageSize, )) .toList(); if (assets.isNotEmpty && currentAssets.contains(assets[0])) { return; } final List<AssetEntity> tempList = <AssetEntity>[]; tempList.addAll(_currentAssets); tempList.addAll(assets); currentAssets = tempList; } @override Future<void> switchPath([AssetPathEntity? pathEntity]) async { assert(() { if (_currentPathEntity == null && pathEntity == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('Empty $AssetPathEntity was switched.'), ErrorDescription( 'Neither currentPathEntity nor pathEntity is non-null, which makes ' 'this method useless.', ), ErrorHint( 'You need to pass a non-null $AssetPathEntity or call this method ' 'when currentPathEntity is not null.', ), ]); } return true; }()); if (_currentPathEntity == null && pathEntity == null) { return; } pathEntity ??= _currentPathEntity!; _isSwitchingPath = false; _currentPathEntity = pathEntity; _totalAssetsCount = pathEntity.assetCount; if(mounted){ notifyListeners(); } await getAssetsFromEntity(0, currentPathEntity!); } @override Future<Uint8List?> getFirstThumbFromPathEntity( AssetPathEntity pathEntity, ) async { final AssetEntity asset = (await pathEntity.getAssetListRange( start: 0, end: 1, )) .elementAt(0); final Uint8List? assetData = await asset.thumbnailDataWithSize(ThumbnailSize(pathThumbSize, pathThumbSize)); return assetData; } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HomeComponent } from './home/home.component'; import { FooterComponent } from './footer/footer.component'; import { HeaderComponent } from './header/header.component'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatIconModule } from '@angular/material/icon'; import { MatTableModule } from '@angular/material/table'; import { MatButtonModule } from '@angular/material/button'; import { MatDialogModule } from '@angular/material/dialog'; import { DialogComponent } from './dialog/dialog.component'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, HomeComponent, FooterComponent, HeaderComponent, DialogComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatToolbarModule, MatIconModule, MatTableModule, MatButtonModule, MatDialogModule, MatFormFieldModule, MatInputModule, FormsModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
/** * DeepRequired * @desc Transform all fields to required state in object or array (including nested) * * @example * // Expect: { * // prop: { * // NestedProps: { * // data: string; * // }; * // }; * // } * type NestedProps = { * prop?: { * nestedProp?: { * data?: string; * }; * }; * }; * type RequiredNestedPropertiess = DeepRequired<NestedProps>; */ export type DeepRequired<T> = T extends (...args: any[]) => any ? T : T extends any[] ? DeepArrayRequired<T[number]> : T extends object ? DeepObjectRequired<T> : T; export interface DeepArrayRequired<T> extends Array<DeepRequired<T extends undefined ? never : T>> {} export type DeepObjectRequired<T> = { [P in keyof T]-?: DeepRequired<T[P] extends undefined ? never : T[P]>; };
import { useDispatch } from "react-redux"; interface Hook { valueAction: <T>(actionCallback: (value: T) => void) => (payload: T) => void; voidAction: (actionCallback: () => void) => () => void; } export default function useActionDispatcher(): Hook { const dispatch = useDispatch(); function valueAction<T>(action: (value: T) => any) { return function dispatchAction(payload: T) { dispatch(action(payload)); }; } function voidAction(actionCallback: () => any) { return function dispatchAction() { dispatch(actionCallback()); }; } return { valueAction, voidAction, }; }
<?php namespace frontend\controllers; use common\helpers\Path; use frontend\models\ResendVerificationEmailForm; use frontend\models\VerifyEmailForm; use Yii; use yii\base\InvalidArgumentException; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\filters\VerbFilter; use yii\filters\AccessControl; use common\models\LoginForm; use Exception; use frontend\models\tokyoconsulting\Content; use frontend\models\PasswordResetRequestForm; use frontend\models\ResetPasswordForm; use frontend\models\SignupForm; use frontend\models\ContactForm; use frontend\models\tokyoconsulting\ContentDetail; use frontend\models\tokyoconsulting\Country; use frontend\models\tokyoconsulting\MemberHasType; /** * Site controller */ class SiteController extends Controller { /** * {@inheritdoc} */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::class, 'only' => ['logout', 'signup'], 'rules' => [ [ 'actions' => ['signup'], 'allow' => true, 'roles' => ['?'], ], [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::class, 'actions' => [ // 'logout' => ['post'], ], ], ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => \yii\web\ErrorAction::class, ], 'captcha' => [ 'class' => \yii\captcha\CaptchaAction::class, 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } /** * Displays homepage. * * @return mixed */ public function actionIndex() { return $this->redirect(Yii::$app->homeUrl . 'site/home'); } public function actionHome() { $dropdown = []; $subtopicDetail = []; $dropdown = Country::find()->where("status=1") ->orderBy('countryName') ->asArray() ->all(); $subtopic = Content::find() ->where(['contentName' => "Subtopic"]) ->asArray() ->one(); if (isset($subtopic) && !empty($subtopic)) { $subtopicDetail = ContentDetail::find() ->where(["contentId" => $subtopic["contentId"], "status" => 1]) ->asArray() ->one(); } $index = Content::find() ->where(["contentName" => "Banner"]) ->asArray() ->one(); $b = Content::find() ->where(["contentName" => "Branch"]) ->asArray() ->one(); $c = Content::find() ->where(["contentName" => "Company"]) ->asArray() ->one(); $sertitle = Content::find() ->where(["contentName" => "Titleservice"]) ->asArray() ->one(); $d = Content::find() ->where(["contentName" => "Business"]) ->asArray() ->one(); $e = Content::find() ->where(["contentName" => "Society"]) ->asArray() ->one(); $f = Content::find() ->where(["contentName" => "About"]) ->asArray() ->one(); $h = Content::find() ->where(["contentName" => "Footer"]) ->asArray() ->one(); $n = Content::find() ->where(["contentName" => "Country"]) ->asArray() ->one(); $k = Content::find() ->where(["contentName" => "Branchcountry"]) ->asArray() ->one(); $p = Content::find() ->where(["contentName" => "Countrypage"]) ->asArray() ->one(); $banners = []; $branch = []; $company = []; $business = []; $society = []; $about = []; $footer = []; $country = []; $branchcountry = []; $countrypage = []; $titleservice = []; if (isset($index) && !empty($index)) { $banners = ContentDetail::find() ->where(["contentId" => $index["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($b) && !empty($b)) { $branch = ContentDetail::find() ->where(["contentId" => $b["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($c) && !empty($c)) { $company = ContentDetail::find() ->where(["contentId" => $c["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($d) && !empty($d)) { $business = ContentDetail::find() ->where(["contentId" => $d["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($e) && !empty($e)) { $society = ContentDetail::find() ->where(["contentId" => $e["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($f) && !empty($f)) { $about = ContentDetail::find() ->where(["contentId" => $f["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($h) && !empty($h)) { $footer = ContentDetail::find() ->where(["contentId" => $h["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($n) && !empty($n)) { $country = ContentDetail::find() ->where(["contentId" => $n["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($k) && !empty($k)) { $branchcountry = ContentDetail::find() ->where(["contentId" => $k["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($p) && !empty($p)) { $countrypage = ContentDetail::find() ->where(["contentId" => $p["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($sertitle) && !empty($sertitle)) { $titleservice = ContentDetail::find() ->where(["contentId" => $sertitle["contentId"], "status" => 1]) ->asArray() ->all(); } $admin = 0; if (isset(Yii::$app->user->id)) { $memberTypeAdmin = MemberHasType::find() ->select("mt.memberTypeName") ->JOIN("LEFT JOIN", "member_type mt", "member_has_type.memberTypeId = mt.memberTypeId") //->leftJoin('member_type', 'member_type.memberTypeId = member_has_type.memberTypeId') ->where([ "member_has_type.memberId" => Yii::$app->user->id, "memberTypeName" => "Administrator" ]) ->asArray() ->one(); } if (isset($memberTypeAdmin) && !empty($memberTypeAdmin)) { $admin = 1; } return $this->render('index', [ "banners" => $banners, "branch" => $branch, "company" => $company, "business" => $business, "society" => $society, "about" => $about, "footer" => $footer, "country" => $country, "branchcountry" => $branchcountry, "countrypage" => $countrypage, "titleservice" => $titleservice, "sertitle" => $sertitle, "admin" => $admin, "index" => $index, "pp" => $b, "c" => $c, "d" => $d, "e" => $e, "f" => $f, "n" => $n, "dropdown" => $dropdown, "subtopic" => $subtopic, "subtopicDetail" => $subtopicDetail, ]); } public function actionServices() { $r = Content::find() ->where(["contentName" => "Services"]) ->asArray() ->one(); $s = Content::find() ->where(["contentName" => "Bannerservices"]) ->asArray() ->one(); $x = Content::find() ->where(["contentName" => "Box"]) ->asArray() ->one(); $t = Content::find() ->where(["contentName" => "Item"]) ->asArray() ->one(); $d = Content::find() ->where(["contentName" => "Detail"]) ->asArray() ->one(); $tokyo = Content::find() ->where(["contentName" => "Picturegraphics"]) ->asArray() ->one(); $o = Content::find() ->where(["contentName" => "Founder"]) ->asArray() ->one(); $u = Content::find() ->where(["contentName" => "Star"]) ->asArray() ->one(); $v = Content::find() ->where(["contentName" => "Itemstar"]) ->asArray() ->one(); $g = Content::find() ->where(["contentName" => "Data"]) ->asArray() ->one(); $w = Content::find() ->where(["contentName" => "Data"]) ->asArray() ->one(); $q = Content::find() ->where(["contentName" => "Button"]) ->asArray() ->one(); $tcf = Content::find() ->where(["contentName" => "Best"]) ->asArray() ->one(); $pic = Content::find() ->where(["contentName" => "Accounting"]) ->asArray() ->one(); $table = Content::find() ->where(["contentName" => "Taxation"]) ->asArray() ->one(); $select = Content::find() ->where(["contentName" => "Stage"]) ->asArray() ->one(); $bk = Content::find() ->where(["contentName" => "Background"]) ->asArray() ->one(); $mos = Content::find() ->where(["contentName" => "Most"]) ->asArray() ->one(); $tryin = Content::find() ->where(["contentName" => "Countryindex2"]) ->asArray() ->one(); $services = []; $bannerservices = []; $box = []; $item = []; $detail = []; $picturegraphics = []; $founder = []; $star = []; $itemstar = []; $data = []; $drive = []; $button = []; $best = []; $accounting = []; $taxation = []; $stage = []; $background = []; $most = []; $countryindex2 = []; if (isset($r) && !empty($r)) { $services = ContentDetail::find() ->where(["contentId" => $r["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($s) && !empty($s)) { $bannerservices = ContentDetail::find() ->where(["contentId" => $s["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($x) && !empty($x)) { $box = ContentDetail::find() ->where(["contentId" => $x["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($t) && !empty($t)) { $item = ContentDetail::find() ->where(["contentId" => $t["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($d) && !empty($d)) { $detail = ContentDetail::find() ->where(["contentId" => $d["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($tokyo) && !empty($tokyo)) { $picturegraphics = ContentDetail::find() ->where(["contentId" => $tokyo["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($o) && !empty($o)) { $founder = ContentDetail::find() ->where(["contentId" => $o["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($u) && !empty($u)) { $star = ContentDetail::find() ->where(["contentId" => $u["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($v) && !empty($v)) { $itemstar = ContentDetail::find() ->where(["contentId" => $v["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($g) && !empty($g)) { $data = ContentDetail::find() ->where(["contentId" => $g["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($w) && !empty($w)) { $drive = ContentDetail::find() ->where(["contentId" => $w["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($q) && !empty($q)) { $button = ContentDetail::find() ->where(["contentId" => $q["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($tcf) && !empty($tcf)) { $best = ContentDetail::find() ->where(["contentId" => $tcf["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($pic) && !empty($pic)) { $accounting = ContentDetail::find() ->where(["contentId" => $pic["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($table) && !empty($table)) { $taxation = ContentDetail::find() ->where(["contentId" => $table["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($select) && !empty($select)) { $stage = ContentDetail::find() ->where(["contentId" => $select["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($bk) && !empty($bk)) { $background = ContentDetail::find() ->where(["contentId" => $bk["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($mos) && !empty($mos)) { $most = ContentDetail::find() ->where(["contentId" => $mos["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($tryin) && !empty($tryin)) { $countryindex2 = ContentDetail::find() ->where(["contentId" => $tryin["contentId"], "status" => 1]) ->asArray() ->all(); } return $this->render('services', [ "services" => $services, "bannerservices" => $bannerservices, "box" => $box, "item" => $item, "detail" => $detail, "picturegraphics" => $picturegraphics, "founder" => $founder, "star" => $star, "itemstar" => $itemstar, "data" => $data, "drive" => $drive, "button" => $button, "best" => $best, "accounting" => $accounting, "taxation" => $taxation, "stage" => $stage, "background" => $background, "most" => $most, "countryindex2" => $countryindex2 ]); } public function actionTest() { return $this->render('in'); } public function actionAbout1() { $ut = Content::find() ->where(["contentName" => "Vision"]) ->asArray() ->one(); $ce = Content::find() ->where(["contentName" => "Existence"]) ->asArray() ->one(); $tr = Content::find() ->where(["contentName" => "Strategy"]) ->asArray() ->one(); $ld = Content::find() ->where(["contentName" => "Should"]) ->asArray() ->one(); $group = Content::find() ->where(["contentName" => "Consultinggroup"]) ->asArray() ->one(); $h = Content::find() ->where(["contentName" => "Footer"]) ->asArray() ->one(); $ft = Content::find() ->where(["contentName" => "Footercontact"]) ->asArray() ->one(); $vision = []; $existence = []; $strategy = []; $should = []; $consultinggroup = []; $footer = []; $footercontact = []; if (isset($ut) && !empty($ut)) { $vision = ContentDetail::find() ->where(["contentId" => $ut["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($ce) && !empty($ce)) { $existence = ContentDetail::find() ->where(["contentId" => $ce["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($tr) && !empty($tr)) { $strategy = ContentDetail::find() ->where(["contentId" => $tr["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($ld) && !empty($ld)) { $should = ContentDetail::find() ->where(["contentId" => $ld["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($group) && !empty($group)) { $consultinggroup = ContentDetail::find() ->where(["contentId" => $group["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($h) && !empty($h)) { $footer = ContentDetail::find() ->where(["contentId" => $h["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($ft) && !empty($ft)) { $footercontact = ContentDetail::find() ->where(["contentId" => $ft["contentId"], "status" => 1]) ->asArray() ->all(); } return $this->render('about1', [ "vision" => $vision, "existence" => $existence, "strategy" => $strategy, "should" => $should, "consultinggroup" => $consultinggroup, "footer" => $footer, "footercontact" => $footercontact, ]); } public function actionContact1() { $tact = Content::find() ->where(["contentName" => "Contact"]) ->asArray() ->one(); $ft = Content::find() ->where(["contentName" => "Footercontact"]) ->asArray() ->one(); $dis = Content::find() ->where(["contentName" => "Disclaimer"]) ->asArray() ->one(); $contact = []; $footercontact = []; $disclaimer = []; if (isset($tact) && !empty($tact)) { $contact = ContentDetail::find() ->where(["contentId" => $tact["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($ft) && !empty($ft)) { $footercontact = ContentDetail::find() ->where(["contentId" => $ft["contentId"], "status" => 1]) ->asArray() ->all(); } if (isset($dis) && !empty($dis)) { $disclaimer = ContentDetail::find() ->where(["contentId" => $dis["contentId"], "status" => 1]) ->asArray() ->all(); } return $this->render('contact1', [ "contact" => $contact, "footercontact" => $footercontact, "disclaimer" => $disclaimer ]); } /** * Logs in a user. * * @return mixed */ public function actionLogin() { if (!Yii::$app->user->isGuest) { //return $this->goHome(); return $this->redirect(Yii::$app->homeUrl . "site/index"); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->redirect(Yii::$app->homeUrl . "site/index"); // return $this->goBack(); } $model->password = ''; return $this->render('login', [ 'model' => $model, ]); } /** * Logs out the current user. * * @return mixed */ public function actionLogout() { Yii::$app->user->logout(); return $this->redirect(Yii::$app->homeUrl . "site/index"); } /** * Displays contact page. * * @return mixed */ public function actionContact() { $model = new ContactForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.'); } else { Yii::$app->session->setFlash('error', 'There was an error sending your message.'); } return $this->refresh(); } return $this->render('contact', [ 'model' => $model, ]); } /** * Displays about page. * * @return mixed */ public function actionAbout() { return $this->render('about'); } /** * Signs user up. * * @return mixed */ public function actionSignup() { $model = new SignupForm(); if ($model->load(Yii::$app->request->post())) { Yii::$app->session->setFlash('success', 'Thank you for registration. Please check your inbox for verification email.'); // return $this->redirect(Yii::$app->homeUrl . "site/index"); return $this->goHome(); } return $this->render('signup', [ 'model' => $model, ]); } /** * Requests password reset. * * @return mixed */ public function actionRequestPasswordReset() { $model = new PasswordResetRequestForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail()) { Yii::$app->session->setFlash('success', 'Check your email for further instructions.'); return $this->goHome(); } Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.'); } return $this->render('requestPasswordResetToken', [ 'model' => $model, ]); } /** * Resets password. * * @param string $token * @return mixed * @throws BadRequestHttpException */ public function actionResetPassword($token) { try { $model = new ResetPasswordForm($token); } catch (InvalidArgumentException $e) { throw new BadRequestHttpException($e->getMessage()); } if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) { Yii::$app->session->setFlash('success', 'New password saved.'); return $this->goHome(); } return $this->render('resetPassword', [ 'model' => $model, ]); } /** * Verify email address * * @param string $token * @throws BadRequestHttpException * @return yii\web\Response */ public function actionVerifyEmail($token) { try { $model = new VerifyEmailForm($token); } catch (InvalidArgumentException $e) { throw new BadRequestHttpException($e->getMessage()); } if (($user = $model->verifyEmail()) && Yii::$app->user->login($user)) { Yii::$app->session->setFlash('success', 'Your email has been confirmed!'); return $this->goHome(); } Yii::$app->session->setFlash('error', 'Sorry, we are unable to verify your account with provided token.'); return $this->goHome(); } /** * Resend verification email * * @return mixed */ public function actionResendVerificationEmail() { $model = new ResendVerificationEmailForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail()) { Yii::$app->session->setFlash('success', 'Check your email for further instructions.'); return $this->goHome(); } Yii::$app->session->setFlash('error', 'Sorry, we are unable to resend verification email for the provided email address.'); } return $this->render('resendVerificationEmail', [ 'model' => $model ]); } public function actionCallApi() { $ch1 = curl_init(); curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch1, CURLOPT_URL, Path::backendUrl().'content/default/res-api?branchName=Bangladesh'); $result1 = curl_exec($ch1); curl_close($ch1); $obj = json_decode($result1, true); throw new Exception (print_r($obj, true)); } }
/** * @param {number} amount * @param {number[]} coins * @return {number} */ function change(amount, coins) { if (amount === 0) return 1; let counts = new Array(amount + 1).fill(0); for (const coin of coins) { const nextCounts = [1]; for (let curAmount = 1; curAmount <= amount; curAmount++) { const withoutCoinAmount = curAmount - coin; const withoutCoinCount = withoutCoinAmount < 0 ? 0 : nextCounts[withoutCoinAmount]; nextCounts[curAmount] = withoutCoinCount + counts[curAmount]; } counts = nextCounts; } return counts[amount]; } exports.change = change;
import React, { useState, useContext } from "react"; import AppBar from "@mui/material/AppBar"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import IconButton from "@mui/material/IconButton"; import Button from "@mui/material/Button"; import MenuIcon from "@mui/icons-material/Menu"; import MenuItem from "@mui/material/MenuItem"; import Menu from "@mui/material/Menu"; import { useNavigate } from "react-router-dom"; import { styled } from '@mui/material/styles'; import { useTheme } from "@mui/material/styles"; import useMediaQuery from "@mui/material/useMediaQuery"; import { AuthContext } from "../../contexts/authContext"; const Offset = styled('div')(({ theme }) => theme.mixins.toolbar); const SiteHeader = ({ history }) => { const [anchorEl, setAnchorEl] = useState(null); const open = Boolean(anchorEl); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down("md")); const context = useContext(AuthContext); const navigate = useNavigate(); const menuOptions = [ { label: "Home", path: "/home" }, { label: "Upcoming", path: "/movies/upcoming" }, { label: "Latest", path: "/movies/latest" }, { label: "Favorites", path: context.isAuthenticated ? "/movies/favorites" : "/login" }, { label: "Watchlist", path: context.isAuthenticated ? "/movies/playlist" : "/login" }, { label: "Actors", path: "/actors" }, { label: "Sign in", path: "/login", hideWhenAuth: true }, { label: "Sign up", path: "/signup", hideWhenAuth: true }, { label: "Log out", path: "/", action: () => context.signout(), showWhenAuth: true }, ]; const handleMenuSelect = (opt) => { if (opt.action) { opt.action(); } else { navigate(opt.path, { replace: true }); } }; const handleMenu = (event) => { setAnchorEl(event.currentTarget); }; return ( <> <AppBar position="fixed" sx={{ backgroundColor: '#424242' }}> <Toolbar> <Typography variant="h4" sx={{ flexGrow: 1, color: 'white' }}> TMDB Client </Typography> <Typography variant="h6" sx={{ flexGrow: 1, color: 'white' }}> {context.isAuthenticated ? `Hi ${context.userName}, Welcome Back!` : ""} </Typography> {isMobile ? ( <> <IconButton aria-label="menu" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleMenu} sx={{ color: 'white' }} > <MenuIcon /> </IconButton> <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: "top", horizontal: "right", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "right", }} open={open} onClose={() => setAnchorEl(null)} > {menuOptions.map((opt) => ( (!opt.hideWhenAuth || !context.isAuthenticated) && (!opt.showWhenAuth || context.isAuthenticated) && ( <MenuItem key={opt.label} onClick={() => handleMenuSelect(opt)} > {opt.label} </MenuItem> ) ))} </Menu> </> ) : ( <> {menuOptions.map((opt) => ( (!opt.hideWhenAuth || !context.isAuthenticated) && (!opt.showWhenAuth || context.isAuthenticated) && ( <Button key={opt.label} color="inherit" onClick={() => handleMenuSelect(opt)} sx={{ color: 'white' }} > {opt.label} </Button> ) ))} </> )} </Toolbar> </AppBar> <Offset /> </> ); }; export default SiteHeader;
<template> <div id="graph"> <h5> Редактор графов <small class="text-muted" ><small>(работает в тестовом режиме)</small></small > </h5> <p class="small"> Один клик по полю - добавление вершины<br /> Поочередный клик по вершинам - рисование ребра<br /> Двойной клик по вершине - переименование <small>(для завершения, нажать Enter или кликнуть по полю)</small><br /> Для удаления, включить «Режим удаления» и кликнуть по элементу<br /> (остальные операции в процессе разработки) </p> <!-- <div>RectX {{ rectX }}, rectY {{ rectY }}</div> --> <!-- <div>texts: {{ texts }}</div> --> <div id="graphPole" class="rounded-2 border"> <svg version="1.1" baseProfile="full" width="100%" height="350" xmlns="http://www.w3.org/2000/svg" @click.self="addPoint" id="pole" ></svg> </div> <div class="d-flex justify-content-between"> <button class="btn btn-sm btn-dark mt-2" @click="clearPole"> Очистить поле </button> <button class="btn btn-sm mt-2" @click="removeMode = !removeMode" :class="{ 'btn-outline-danger': !removeMode, 'btn-danger': removeMode }" > Режим удаления </button> <div class="bg-light border rounded-2 mt-2 p-0 pt-1 ps-2 pe-2 small"> Вершин {{ points.length }}, ребер {{ lines.length }} </div> </div> </div> </template> <script> export default { data() { return { height: 350, radius: 14, poleEl: null, editMode: false, removeMode: false, lineStart: null, lineEnd: null, lines: [], points: [], texts: [] } }, mounted() { this.poleEl = document.getElementById('pole') this.poleEl.style.background = '#F8F9FA' }, computed: {}, methods: { addPoint(e) { if (!this.editMode && !this.removeMode) { const cx = e.offsetX const cy = e.offsetY const point = { x: cx, y: cy } this.points.push(point) const textContent = this.points.length const text = { x: cx, y: cy, text: textContent } this.texts.push(text) this.draw() } else { this.editMode = false } }, drawPoint() { this.points.forEach((item, index) => { const pointEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' ) pointEl.setAttribute('cx', item.x) pointEl.setAttribute('cy', item.y) pointEl.setAttribute('r', this.radius) pointEl.setAttribute('fill', 'white') pointEl.setAttribute('stroke', '#8E44AD') pointEl.setAttribute('stroke-width', '3') pointEl.setAttribute('stroke-opacity', '0.8') // Create Text const textEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'text' ) textEl.setAttribute('x', item.x) textEl.setAttribute('y', item.y) textEl.setAttribute('fill', '#000000') textEl.setAttribute('font-family', 'sans-serif') textEl.setAttribute('font-size', '14') textEl.setAttribute('text-anchor', 'middle') textEl.setAttribute('stroke-width', '1') textEl.setAttribute('stroke', '#000000') textEl.setAttribute('dy', '.35em') textEl.style.userSelect = 'none' textEl.textContent = this.texts[index].text // Create foreignObject const foreignEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'foreignObject' ) foreignEl.setAttribute('x', item.x - 12) foreignEl.setAttribute('y', item.y - 12) foreignEl.setAttribute('width', 24) foreignEl.setAttribute('height', 24) foreignEl.setAttribute('id', 'foreign' + index) foreignEl.style.display = 'none' // Create inputEl const inputEl = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'input' ) inputEl.setAttribute('type', 'text') inputEl.setAttribute('id', 'inputEl' + index) inputEl.setAttribute('maxlength', '2') inputEl.style.width = '100%' inputEl.style.height = '100%' inputEl.style.textAlign = 'center' inputEl.style.fontSize = '14px' //inputEl.style.border = '4px solid red' // Create Grpup const groupEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' ) groupEl.style.cursor = 'pointer' foreignEl.append(inputEl) groupEl.append(pointEl) groupEl.append(textEl) groupEl.append(foreignEl) this.poleEl.append(groupEl) groupEl.addEventListener('click', () => { if (this.removeMode) { this.removePoint(index, item.x, item.y) } else { this.addLine(item.x, item.y) } }) groupEl.addEventListener('dblclick', () => { this.renamePoint(index) }) }) }, removePoint(index, x, y) { this.points.splice(index, 1) this.texts.splice(index, 1) if (this.lines.length) { this.removeLineFromPoint(x, y) } else { this.draw() } }, removeLineFromPoint(x, y) { this.lines = this.lines.filter( item => item.x1 != x && item.y1 != y && item.x2 != x && item.y2 != y ) this.draw() }, removeLineSelf(x1, x2, y1, y2) { this.lines = this.lines.filter( item => (item.x1 != x1 && item.y1 != y1) || (item.x2 != x2 && item.y2 != y2) ) this.draw() }, renamePoint(index) { this.editMode = true const foreignElEdit = document.getElementById('foreign' + index) foreignElEdit.style.display = 'block' const inputElEdit = foreignElEdit.firstChild inputElEdit.focus() inputElEdit.addEventListener('keydown', e => { if (e.keyCode === 13) { this.texts[index].text = inputElEdit.value foreignElEdit.style.display = 'none' this.draw() this.editMode = false } }) inputElEdit.addEventListener('blur', () => { this.texts[index].text = inputElEdit.value foreignElEdit.style.display = 'none' this.draw() }) }, addLine(cx, cy) { if (!this.lineStart) { this.lineStart = { x: cx, y: cy } //console.log('lineStart cx:', cx, ' cy:', cy) } else { if (this.lineStart.x != cx || this.lineStart.y != cy) { if (!this.lineEnd) { this.lineEnd = { x: cx, y: cy } //console.log('lineEnd cx:', cx, ' cy:', cy) const line = { x1: this.lineStart.x, x2: this.lineEnd.x, y1: this.lineStart.y, y2: this.lineEnd.y } this.lines.push(line) this.draw() } } } }, drawLine() { this.lines.forEach(item => { const lineEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' ) lineEl.setAttribute('x1', item.x1) lineEl.setAttribute('x2', item.x2) lineEl.setAttribute('y1', item.y1) lineEl.setAttribute('y2', item.y2) lineEl.setAttribute('stroke', '#8E44AD') lineEl.setAttribute('stroke-width', '4') lineEl.setAttribute('stroke-linecap', 'round') lineEl.setAttribute('stroke-opacity', '1') lineEl.style.cursor = 'pointer' this.poleEl.prepend(lineEl) lineEl.addEventListener('click', () => { if (this.removeMode) { this.removeLineSelf(item.x1, item.x2, item.y1, item.y2) } }) }) this.lineStart = null this.lineEnd = null }, draw() { this.poleEl.innerHTML = '' this.drawPoint() this.drawLine() }, clearPole() { this.poleEl.innerHTML = '' this.points = [] this.texts = [] this.lines = [] } } } </script>
<template> <section class="slider w-full" :class="{ ' py-20 md:pt-28 md:pb-32 bg-darkBlue relative top_skew bottom_skew': type !== 'sliderImage' }"> <template v-if="type === 'sliderImage'"> <VueSlickCarousel v-bind="options"> <div v-for="slide in list" :key="slide._key"> <picture class="object-cover object-center"> <source v-if="slide.imageItem[1].type === 'mobile'" media="(max-width: 768px)" :srcset="`https://cdn.sanity.io/images/17qu8ckk/production/${slide.imageItem[1].image.slice(6, -4)}.jpg`" width="560" height="780" /> <img v-if="slide.imageItem[0].type === 'desktop'" class="lazyload" :src="`https://cdn.sanity.io/images/17qu8ckk/production/${slide.imageItem[0].image.slice(6, -4)}.jpg`" width="1920" height="1024" /> </picture> </div> </VueSlickCarousel> </template> <template v-else> <div class="container"> <h2 class="title w-full text-3xl font-bold mb-24 relative text-white text-center md:text-left">{{ title }}</h2> <VueSlickCarousel v-bind="options"> <div v-for="slide in list" :key="slide._key" class="slide md:mb-0 mb-24"> <div class="video_container w-full md:h-96 h-56 relative"> <img class="w-full h-full object-cover z-0 relative" :src="`https://i.ytimg.com/vi/${imagePreview(slide.youtube)}/maxresdefault.jpg`" width="1200" height="500" /> <div class="overlay z-10 absolute bg-black w-full h-full inset-0 bg-opacity-50 block"></div> <a class="text-yellow play w-16 h-16 absolute top-2/4 left-2/4 z-20 hover:text-blue" @click="openModal({ isEnabled: true, data: slide.youtube })"> <font-awesome-icon class="text-6xl w-16 h-16" :icon="['fas', 'play-circle']" /> </a> </div> </div> </VueSlickCarousel> </div> </template> </section> </template> <script> import VueSlickCarousel from 'vue-slick-carousel' import 'vue-slick-carousel/dist/vue-slick-carousel.css' export default { name: 'Slider', components: { VueSlickCarousel, }, props: { list: { type: Array, required: true, }, type: { type: String, // required: true, default: 'sliderImage', }, title: { type: String, // required: true, default: '', }, }, data: () => ({ data: null, options: { dots: true, dotsClass: 'slick-dots', autoplay: true, arrows: false, // fade: true, // edgeFriction: 0.35, infinite: false, // speed: 500, slidesToShow: 1, slidesToScroll: 1, }, }), methods: { imagePreview(url) { return url.slice(url.length - 11, url.length) }, openModal(value) { this.$store.dispatch('bindModal', value) }, }, } </script> <style lang="scss" scoped> .slider { overflow: hidden; .play { transform: translate(-50%, -50%); z-index: 10; } picture { z-index: -1; position: relative; display: block; } } </style>
import type { NextPage } from "next"; import type { Session, User } from "@supabase/supabase-js"; import { useEffect, useState } from "react"; import { supabase } from "../utils/supabaseClient"; import Image from "next/image"; const Home: NextPage = () => { const auth = supabase.auth; const [email, setEmail] = useState<User["email"]>(undefined); const [image, setImage] = useState<string | undefined>(undefined); const [file, setFile] = useState<File | undefined>(undefined); const setStates = (user: Session["user"]) => { setEmail(user?.email); setImage(user?.user_metadata.picture); }; useEffect(() => { auth.onAuthStateChange((_event, session) => { const user = session && session.user; setStates(user); }); const user = auth.user(); setStates(user); }, [auth]); return ( <div> {!email ? ( <button onClick={(event) => { event.preventDefault(); auth.signIn({ provider: "google" }); }} > Login </button> ) : ( <button onClick={(event) => { event.preventDefault(); auth.signOut(); }} > Logout </button> )} <p>{email}</p> <div> {image && <Image src={image} alt="image" width={100} height={100} />} </div> <input type="file" accept="image/png, image/jpeg" onChange={(event) => { event.preventDefault(); const { files } = event.target; if (!files) { return; } setFile(files[0]); }} /> <div> <Image src={(file && URL.createObjectURL(file)) || "/no_image.png"} alt="No Image" width={100} height={100} /> </div> <button onClick={async (event) => { event.preventDefault(); if (!file) { return; } const { error } = await supabase.storage .from("images") .upload("public/image.png", file); console.log(error); }} > Upload </button> </div> ); }; export default Home;
import test from 'node:test'; import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; /** * @see https://nodejs.org/api/test.html * @see https://glebbahmutov.com/blog/trying-node-test-runner/ */ // Some functions to use function greet(fail = false) { if (fail) throw new Error('Failed!'); return 'Hi there!'; } async function greetAsync(fail = false) { if (fail) throw new Error('Failed!'); return 'Hi there!'; } // Basic example test('Basic greet', () => { const expected = 'Hi there!'; const result = greet(); assert.equal(result, expected, 'checking the greeting'); }); // Using describe + it semantics describe('Greet', () => { const expected = 'Hi there!'; it('Should greet', () => { const result = greet(); assert.strictEqual(result, expected, 'checking the greeting'); }); it('Should fail', () => { assert.throws(() => { greet(true); }); }); }); // Async usage describe('Greet async', () => { const expected = 'Hi there!'; it('Should greet', async () => { const result = await greetAsync(); assert.strictEqual(result, expected, 'checking the greeting'); }); it('Should fail', async () => { const expected = { name: 'Error', message: 'Failed!' }; await assert.rejects(async () => { await greetAsync(true); }, expected); }); });
import { BasicPackageData, PackageData } from './../model/package'; import { QueryResult } from './../model/query'; import { Component } from '@angular/core'; import { Db } from '../model/query'; import { DbQueryService } from '../services/db-query.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-db-test', templateUrl: './db-test.component.html', styleUrls: ['./db-test.component.scss'] }) export class DbTestComponent { actions = ['Insert package', 'Get package by name', 'Remove comments of package', 'Get names of <n> sorted packages by given field and offset', 'Get <n> most voted packages basic data', 'Get packages occurences count']; expandedIndex = 0; namesOfSortedPkgsResult: QueryResult<string[]> | void = undefined; getNamesOfSortedPkgsForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), fieldName: new FormControl('popularity', [Validators.required]), limit: new FormControl(5, [Validators.required]), offset: new FormControl(0, [Validators.required]) }) mostVotedPkgsResult: QueryResult<BasicPackageData[]> | void = undefined; mostVotedPkgsForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), limit: new FormControl(5, [Validators.required]), }) getPkgResult: QueryResult<PackageData> | void = undefined; getPkgForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), name: new FormControl('dropbox', [Validators.required]), }) insertPkgResult: QueryResult<void> | void = undefined; insertPkgForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), pkgJson: new FormControl('', [Validators.required]), }) removeCommentsResult: QueryResult<void> | void = undefined; removeCommentsForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), pkgName: new FormControl('test-7777', [Validators.required]), }) packagesOccurencesResult: QueryResult<Map<string, number>> | void = undefined; packagesOccurencesForm = new FormGroup({ targetDb: new FormControl(Db.SurrealDb, [Validators.required]), pkgNames: new FormControl('rust,go,python', [Validators.required]), }) constructor (private dbQueryService: DbQueryService) {} async getNamesOfSortedPackagesByName() { this.namesOfSortedPkgsResult = undefined; let data = this.getNamesOfSortedPkgsForm.value; this.dbQueryService.sortPkgsByFieldWithLimit( data.targetDb as Db, data.fieldName as string, data.offset as number, data.limit as number ) .catch(err => console.error(err)) .then(response => this.namesOfSortedPkgsResult = response) } async getMostVotedPkgs() { this.mostVotedPkgsResult = undefined; let data = this.mostVotedPkgsForm.value; this.dbQueryService.getMostVotedPackages( data.targetDb as Db, data.limit as number ) .catch(err => console.error(err)) .then(response => this.mostVotedPkgsResult = response) } async getPkg() { this.getPkgResult = undefined; let data = this.getPkgForm.value; this.dbQueryService.getPkg( data.targetDb as Db, data.name as string ) .catch(err => console.error(err)) .then(response => this.getPkgResult = response) } async insertPkg() { this.insertPkgResult = undefined; let data = this.insertPkgForm.value; let pkg: PackageData = JSON.parse(data.pkgJson as string); this.dbQueryService.insertPkg( data.targetDb as Db, pkg ) .catch(err => console.error(err)) .then(response => this.insertPkgResult = response) } async removeComments() { this.removeCommentsResult = undefined; let data = this.removeCommentsForm.value; this.dbQueryService.removeComments( data.targetDb as Db, data.pkgName as string ) .catch(err => console.error(err)) .then(response => this.removeCommentsResult = response) } async getPackagesOccurencesInDeps() { this.packagesOccurencesResult = undefined; let data = this.packagesOccurencesForm.value; let pkgNames = (data.pkgNames as string).split(','); this.dbQueryService.getPackagesOccurencesInDeps( data.targetDb as Db, pkgNames as string[] ) .catch(err => console.error(err)) .then(response => this.packagesOccurencesResult = response) } }
const {Universal, Node, MemoryAccount, Crypto, AeSdk, CompilerHttp, hash, encode, Encoding, generateKeyPair} = require('@aeternity/aepp-sdk') const fetch = require('node-fetch') const fs = require('fs') const COMPILER_URL = 'https://v7.compiler.aepps.com' const factorySource = ` contract Example = entrypoint example(x : int) = x main contract Factory = stateful entrypoint create() = Chain.create() : Example ` const cloneSource = ` contract Example = entrypoint example(x : int) = x main contract CloneFactory = stateful entrypoint clone(template : Example) = Chain.clone(ref = template) : Example ` const accounts = [ 'ak_tWZrf8ehmY7CyB1JAoBmWJEeThwWnDpU4NadUdzxVSbzDgKjP', 'ak_2QkttUgEyPixKzqXkJ4LX7ugbRjwCDWPBT4p4M2r8brjxUxUYd', ]; const output = { accounts }; const devModeRequest = async (path) => { const response = await fetch(`http://mdw.aeternity.localhost:3313${path}`, { headers: { 'Accept': 'application/json' } }); return await response.json(); }; const emitKb = () => devModeRequest('/emit_kb'); const emitMb = () => devModeRequest('/emit_mb'); const main = async () => { const keypair = { 'publicKey': 'ak_tWZrf8ehmY7CyB1JAoBmWJEeThwWnDpU4NadUdzxVSbzDgKjP', 'secretKey': '7fa7934d142c8c1c944e1585ec700f671cbc71fb035dc9e54ee4fb880edfe8d974f58feba752ae0426ecbee3a31414d8e6b3335d64ec416f3e574e106c7e5412' } const node = new Node('http://mdw.aeternity.localhost:3013/', { ignoreVersion: true }); const account = new MemoryAccount(keypair.secretKey); const aeSdk = new AeSdk({ nodes: [{ name: 'devnet', instance: node }], accounts: [account], onCompiler: new CompilerHttp(COMPILER_URL) }); const factoryContract = await aeSdk.initializeContract({ sourceCode: factorySource }); const cloneFactoryContract = await aeSdk.initializeContract({ sourceCode: cloneSource }); // Use client here.. await emitKb() const spend = await aeSdk.spend(100000, accounts[1]); await emitKb() const contractCreate = await factoryContract.$deploy([]); console.log(contractCreate) const contract1 = contractCreate.result.contractId; const contractCall1 = await factoryContract.create(); const innerContract1 = contractCall1.decodedResult; const contractClone = await cloneFactoryContract.$deploy([]); console.log(contractClone) const contract2 = contractClone.result.contractId; const contractCall2 = await cloneFactoryContract.clone(innerContract1); const innerContract2 = contractCall2.decodedResult; output.contracts = [contract1, innerContract1, contract2, innerContract2]; await emitKb() fs.writeFileSync('output.json', JSON.stringify(output)); }; main();
import json import pinecone from langchain.vectorstores import Pinecone def read_json_file(filename): with open(filename, "r") as f: data = json.load(f) return data data = read_json_file("data.json") # print(data) def objects_to_paragraphs(objects): paragraphs = [] for object in objects: paragraph = "" for key, value in object.items(): paragraph += f"{key}: {value}\n" paragraphs.append(paragraph) return paragraphs res = objects_to_paragraphs(data) # print(res) import os from dotenv import load_dotenv load_dotenv() OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') PORT = os.getenv('PORT') import pinecone from langchain.vectorstores import Pinecone from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY) PINECONE_API_KEY = os.getenv('PINECONE_API_KEY') PINECONE_API_ENV = os.getenv('PINECONE_API_ENV') pinecone.init( api_key=PINECONE_API_KEY, environment=PINECONE_API_ENV ) index = "travel-chatbot" docsearch = Pinecone.from_texts(res, embeddings, index_name=index) from langchain.llms import OpenAI from langchain.chains.question_answering import load_qa_chain from flask import Flask, jsonify, request, Response from flask_cors import CORS import openai app = Flask(__name__) CORS(app, resources={r"/ask": {"origins": ["http://127.0.0.1:5500", "https://travel-buddy-ga201.netlify.app"]}}) CORS(app, resources={r"/chat": {"origins": ["http://127.0.0.1:5500", "https://travel-buddy-ga201.netlify.app"]}}) product_func = [ { "name":"get_places_images", "description": "Get all the images of particular place", "parameters": { "type":"object", "properties": { "data" : { "type" : "array", "items" : { "type":"object", "properties" : { "images" : { "type" :"string", "description" : "Places image, e.g. https://t3.ftcdn.net/jpg/01/30/86/06/240_F_130860698_oBQfdpO4kdQ6EnMtvnCn90fOrClUvBuZ.jpg" }, "names" : { "type" :"string", "description" : "Places names, e.g. Goa, Agra, Shimla" }, "places_to_watch" : { "type" :"string", "description" : "Places to watch, e.g. Baga beach, Agra fort, Mall road, Nubra Valley" }, "weather" : { "type" :"string", "description" : "Places weather, e.g. cold, moderate, hot" }, "place_type" : { "type" :"string", "description" : "Places type, e.g. Historical, Hill Station, Beach" } }, "required" : ["name", "images", "place_type", "places_to_watch", "weather"] } } }, "required":["data"] } } ] @app.route('/ask', methods = ['GET', 'POST']) def ask(): try: # Get the query from the client side query = request.json['user_input'] # print(query) # Initialize the OpenAI model llm = OpenAI(temperature=0, openai_api_key=OPENAI_API_KEY) # Load the QA chain chain = load_qa_chain(llm, chain_type="stuff") # Perform a similarity search to get relevant documents docs = docsearch.similarity_search(query) # Run the query through the chain answer = chain.run(input_documents=docs, question=query) completion = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages = [{"role" : "user", "content" : f"""{docs}"""}], functions = product_func, function_call = "auto" ) # print(completion) output = completion.choices[0].message # print(output) arguments = json.loads(output.function_call.arguments) # names = [item['names'] for item in arguments['data']] # places_to_watch = [item['places_to_watch'] for item in arguments['data']] # weather = [item['weather'] for item in arguments['data']] # place_type = [item['place_type'] for item in arguments['data']] # # print(arguments) # images = [item["images"] for item in arguments["data"]] # print(images) # # Return the answer as JSON response response = { 'answer': answer } # if "images" in query.lower(): # response["images"] = images # elif "names" in query.lower(): # response["names"] = names # elif "places" in query.lower(): # response["names"] = names return jsonify(response) except Exception as e: return jsonify({'error': str(e)}), 500 # Global dictionary to store chat history chat_history = {} @app.route('/chat', methods=['GET','POST']) def chat(): user_input = request.json['user_input'] # Generate a response from OpenAI response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages= [{"role": "system", "content": "You are a helpful travel assistant, who help users with their travel, vacation, trip related queries only. If users ask questions other than travel related queries, you have to say Sorry, I am designed to help you in Travel related queries only."}, {"role" : "user", "content" : user_input}], temperature=0.7, # Adjust as needed max_tokens=300, top_p=1, # Adjust the response length ) # Extract and save the chatbot's reply to the conversation history chatbot_reply = response['choices'][0]['message']['content'] return jsonify({'response': chatbot_reply}) if __name__ == '__main__': app.run(port=PORT)
import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { findAllTransactionsBetweenRange } from "../../actions/transactionAction"; import PaginationTemp from "../../components/PaginationTemp"; import CSVExport from "../../components/ExplorerView/AddressView/CSVExport"; import TransactionBodyContent from "./TransactionBodyContent"; import TransactionHeader from "./TransactionHeader"; import { TimeSort } from "../../utils/TimeSort"; const TransactionsExplorer = () => { const id = useParams(); const [transactions, setTransactions] = useState(null); const [totalPage, setTotalPage] = useState(0); const [txPerPage, setTxPerPage] = useState(10); const [currentPage, setCurrentPage] = useState(0); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [dateASC, setDateASC] = useState(true); const DateOrderhandler = (e) => { e.preventDefault(); setDateASC(!dateASC); }; const handleSelectChange = (event) => { setTxPerPage(event.target.value); }; useEffect(() => { fetchData(); }, [currentPage, txPerPage]); async function fetchData() { setLoading(true); // Begin loading try { const fetchedTransactions = await findAllTransactionsBetweenRange( currentPage, txPerPage ); setTotalPage(fetchedTransactions.length / txPerPage); setTransactions(fetchedTransactions); } catch (error) { console.error("Error fetching transaction: ", error); setError(error); // Set the error state } finally { setLoading(false); // End loading } } return ( <div className="w-full justify-start max-w-[1408px] min-w-[343px] flex flex-col items-start px-5 mx-auto pb-10"> <h2 className="dark:text-white text-black text-[34px] leading-[1.2em] font-semibold text-left"> Transactions </h2> <div className="pt-4 w-full"> <div className="rounded-lg overflow-x-auto flex flex-col bg-white dark:bg-darkPrimary p-6 border-[1px] dark:border-darkColorSeparator border-colorSeparator"> <div className="flex flex-col"> {/* Tab Index */} <div className=""></div> {/* MainBoard */} <div className="p-[10px] flex flex-col gap-3"> <div className="flex flex-row justify-between w-full"> <span className="text-[18px] leading-[1.5em] text-[rgb(85,98,109)] dark:text-white"> {txPerPage}&nbsp;transactions shown </span> <PaginationTemp totalPage={totalPage} currentPage={currentPage} setCurrentPage={setCurrentPage} /> </div> <div className="overflow-auto transition-all duration-100 min-h-[600px] flex flex-col" id="Scrollbar" > <table className="w-full min-w-[1266px] table-auto relative border-spacing-0 border-separate h-full max-h-[1266px] overflow-y-hidden"> <TransactionHeader dateASC={dateASC} DateOrderhandler={DateOrderhandler} /> <tbody className="max-h-[1266px] overflow-y-hidden"> {transactions && TimeSort(transactions, dateASC).map((item, index) => ( <TransactionBodyContent key={index} item={item} /> ))} </tbody> </table> </div> <div className="pt-6 flex flex-row justify-between items-center"> <div className="flex flex-row gap-4 items-center"> <div className="flex items-center justify-between flex-row border"> <select value={txPerPage} onChange={handleSelectChange} className="block appearance-none w-full bg-transparent border border-gray-400 hover:border-gray-500 hover:cursor-pointer px-4 py-2 pr-8 rounded shadow leading-tight focus:outline-none focus:shadow-outline dark:text-white" > {" "} totalPage={totalPage} <option value={10}>10</option> <option value={25}>25</option> <option value={50}>50</option> <option value={100}>100</option> </select> </div> <span className="dark:text-white text-[14px] leading-[1.5em] text-[#55626D]"> records per page </span> </div> <PaginationTemp totalPage={totalPage} currentPage={currentPage} setCurrentPage={setCurrentPage} /> </div> <CSVExport id={id} /> </div> </div> </div> </div> </div> ); }; export default TransactionsExplorer;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue JS - Codes</title> </head> <body> <h1>Fists time - VueJs</h1> <div id="app"> <!-- Generates codes thought VueJs --> <p> {{title}} </p> <p> {{ isActive == true ? 'Está funcionando' : 'Não está funcionando'}} </p> <a v-bind:href="url" v-bind:title="anchorTitle">VueJs Official page</a> </div> <script src="vue.js"></script> <script> new Vue({ el: '#app', data: { title: 'Title text from object data->title', isActive: 'true', url: 'https://vuejs.org', anchorTitle: 'O melhor framework JS.', } }); </script> </body> </html>
package aeaconf2_test import ( "fmt" "reflect" "github.com/safinsingh/aeaconf2" ) func getFunctionRegistry() map[string]reflect.Type { funcRegistry := make(map[string]reflect.Type) funcRegistry["PathExists"] = reflect.TypeOf(PathExists{}) funcRegistry["FileContains"] = reflect.TypeOf(FileContains{}) funcRegistry["ServiceUp"] = reflect.TypeOf(ServiceUp{}) aeaconf2.CheckFunctionRegistry(funcRegistry) return funcRegistry } type PathExists struct { aeaconf2.BaseCondition Path string } func (p *PathExists) Score() bool { return true } func (p *PathExists) DefaultString() string { return fmt.Sprintf("Path '%s' exists", p.Path) } type FileContains struct { aeaconf2.BaseCondition File string Value string } func (f *FileContains) Score() bool { return true } func (f *FileContains) DefaultString() string { return fmt.Sprintf("File '%s' contains '%s'", f.File, f.Value) } type ServiceUp struct { aeaconf2.BaseCondition Service string } func (s *ServiceUp) Score() bool { return true } func (s *ServiceUp) DefaultString() string { return fmt.Sprintf("Service '%s' is running", s.Service) } // add more...
<?php /** * Wishlist * * @author c.friedl */ class Schracklive_SchrackWishlist_Model_Partslist extends Mage_Core_Model_Abstract { const HASH_SEED='xA'; const FIXED_DEBUG_CC = 'p.trummer@schrack.com'; public function __construct() { parent::__construct(); $this->_setResourceModel('schrackwishlist/partslist'); } /** * Set date of last update for wishlist * * @return Mage_Wishlist_Model_Wishlist */ protected function _beforeSave() { // Fetch the partslist-id and try to find out, if there is a change on a shared partslist (-> then update the changed-flag): $sessionLoggedInCustomer = Mage::getSingleton('customer/session')->getCustomer(); $customerEmail = $sessionLoggedInCustomer->getEmail(); $partslistId = $this->getId(); if ($partslistId) { $query = "UPDATE partslist_sharing_map SET last_update_notification_flag = 1, last_update_notification_at = '" . date('Y-m-d H:i:s') . "', updated_at = '" . date('Y-m-d H:i:s') . "'"; $query .= " WHERE shared_partslist_id = " . $partslistId . " AND email_sharer LIKE '" . $customerEmail . "'"; $writeConnection = Mage::getSingleton('core/resource')->getConnection('core_write'); $writeConnection->query($query); } parent::_beforeSave(); $this->setUpdatedAt(Mage::getSingleton('core/date')->gmtDate()); return $this; } protected function _afterDelete() { // Fetch the partslist-id and try to find out, if there is a change on a shared partslist (-> then update the changed-flag): $sessionLoggedInCustomer = Mage::getSingleton('customer/session')->getCustomer(); $customerEmail = $sessionLoggedInCustomer->getEmail(); $partslistId = $this->getId(); $query = "DELETE FROM partslist_sharing_map"; $query .= " WHERE shared_partslist_id = " . $partslistId . " AND email_sharer LIKE '" . $customerEmail . "'"; $writeConnection = Mage::getSingleton('core/resource')->getConnection('core_write'); $writeConnection->query($query); parent::_afterDelete(); } private function _loadByCustomer($customerId) { return Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $customerId)) ->addOrder('is_active', 'DESC') ->addOrder('description', 'ASC'); } public function loadByCustomer($customer) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } $partslists = $this->_loadByCustomer($customer); return $partslists; } /** * * @param Mage_Customer_Model_Customer $customer * @return Schracklive_SchrackWishlist_Model_Partslist * @throws Exception */ public function loadActiveListByCustomer($customer, $create = false) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $customer)) ->addFieldToFilter('is_active', array('=' => 1)) ->setOrder('description', 'ASC'); $count = $partslists->count(); if ($count === 0 && $create) { $partslists = $this->_loadByCustomer($customer); if ($partslists->count() === 0) { // count again to see if there are any lists by this customer, including non-active $this->create($customer, null, null); } } else if ($count === 1) { $this->_getResource()->load($this, $partslists->getFirstItem()->getId()); } return $this; } public function loadByCustomerAndHashedId($customer, $hashedId) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $customer)); foreach ( $partslists as $partslist ) { if ( $partslist->getHashedId() === $hashedId ) { $this->_getResource()->load($this, $partslist->getId()); return $this; } } return $this; } public function getHashedId() { return sha1(self::HASH_SEED . $this->getId()); } /** * * @param Mage_Customer_Model_Customer $customer * @return bool * @throws Exception */ public function hasCustomerActiveList($customer) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $customer)) ->addFieldToFilter('is_active', array('=' => 1)); return ($partslists->count() === 1); } /** * Create new partslist for customer * * @param mixed $customer * @param string $description description of new partslist (with a default) * @return Schracklive_SchrackWishlist_Model_Partslist */ public function create($customer, $description = null, $comment = null, $isEndcustomer = 0) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } if ($description === null) $description = Mage::helper('adminhtml')->__('My Partslist'); if (!$this->hasCustomerActiveList($customer)) $this->setIsActive(1); $this->setCustomerId($customer); $this->setDescription($description); $this->setComment($comment); $this->setIsEndcustomer($isEndcustomer); if ( $isEndcustomer ) { $this->setIsVisible(0); } else { $this->setIsVisible(1); } $this->save(); return $this; } public function activate() { $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $this->getCustomerId())) ->addFieldToFilter('is_active', array('=' => 1)); foreach($partslists as $partslist) $partslist->deactivate(); $this->setIsActive(1); $this->save(); } public function deactivate() { $this->setIsActive(0); $this->save(); } /** * * @return Schracklive_SchrackWishlist_Model_Partslist */ public function save() { return parent::save(); } /** * * @param mixed $customer * @param int $partslistId * @return type */ public function loadByCustomerAndId($customer, $partslistId) { if ($customer instanceof Mage_Customer_Model_Customer) { $customer = $customer->getId(); } $count = $this->getCollection() ->addFieldToFilter('customer_id', array('eq' => $customer)) ->addFieldToFilter('partslist_id', array('eq' => $partslistId)) ->count(); if ($count === 1) { $this->_getResource()->load($this, $partslistId); // TODO there surely is a way to do this without data access, but I didn't find it yet... } else { throw new Exception('partslist could not be found'); } return $this; } public function hasPartslistItems() { return ($this->getItemsCount() > 0); } public function validate() { if ($this->getIsActive()) { $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('eq' => $this->getCustomerId())) ->addFieldToFilter('partslist_id', array('neq' => $this->getId())) ->addFieldToFilter('is_active', array('eq' => 1)); if ($partslists->count() !== 0) throw new Exception(Mage::helper('core')->__('There can only be one active partslist.')); } } public function getDescription() { $d = parent::getDescription(); if (!strlen($d)) $d = Mage::helper('core')->__('My Partslist'); return $d; } /** * Adding item to partslist * * @param Schracklive_SchrackWishlist_Model_Partslist_Item $item * @return Schracklive_SchrackWishlist_Model_Partslist */ public function addItem(Schracklive_SchrackWishlist_Model_Partslist_Item $item) { $item->setPartslist($this); if (!$item->getId()) { $this->getItemCollection()->addItem($item); Mage::dispatchEvent('partslist_add_item', array('item' => $item)); } return $this; } /** * Adds new product to partslist. * Returns new item or string on error. * * @param int|Mage_Catalog_Model_Product $product * @param mixed $buyRequest * @param bool $forciblySetQty * @return Schracklive_SchrackWishlist_Model_Partslist_Item|string */ public function addNewItem($product, $buyRequest = null, $forciblySetQty = true, $referrerUrl = null) { /* * Always load product, to ensure: * a) we have new instance and do not interfere with other products in partslist * b) product has full set of attributes */ if ($product instanceof Mage_Catalog_Model_Product) { $productId = $product->getId(); // Maybe force some store by partslist internal properties $storeId = $product->hasPartslistStoreId() ? $product->getPartslistStoreId() : $product->getStoreId(); } else { $productId = (int) $product; if ($buyRequest->getStoreId()) { $storeId = $buyRequest->getStoreId(); } else { $storeId = Mage::app()->getStore()->getId(); } } /* @var $product Mage_Catalog_Model_Product */ $product = Mage::getModel('catalog/product') ->setStoreId($storeId) ->load($productId); if ($buyRequest instanceof Varien_Object) { $_buyRequest = $buyRequest; } elseif (is_string($buyRequest)) { $_buyRequest = new Varien_Object(unserialize($buyRequest)); } elseif (is_array($buyRequest)) { $_buyRequest = new Varien_Object($buyRequest); } else { $_buyRequest = new Varien_Object(); } $cartCandidates = $product->getTypeInstance(true) ->processConfiguration($_buyRequest, $product); /** * Error message */ if (is_string($cartCandidates)) { return $cartCandidates; } /** * If prepare process return one object */ if (!is_array($cartCandidates)) { $cartCandidates = array($cartCandidates); } $errors = array(); $items = array(); foreach ($cartCandidates as $candidate) { if ($candidate->getParentProductId()) { continue; } $candidate->setPartslistStoreId($storeId); $item = $this->_addCatalogProduct($candidate, $candidate->getQty(), $forciblySetQty, $referrerUrl); $items[] = $item; // Collect errors instead of throwing first one if ($item->getHasError()) { $errors[] = $item->getMessage(); } } Mage::dispatchEvent('partslist_product_add_after', array('items' => $items)); return $item; } /** * Retrieve wishlist items count * * @return int */ public function getItemsCount() { return $this->_getResource()->fetchItemsCount($this); } /** * Adding catalog product object data to wishlist * * @param Mage_Catalog_Model_Product $product * @param int $qty * @param bool $forciblySetQty * @return Schracklive_SchrackWishlist_Model_Partslist_Item */ protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1, $forciblySetQty = true, $referrerUrl = null) { if ($forciblySetQty && strlen($qty) === 0) { $qty = 1; } $item = null; foreach ($this->getItemCollection() as $_item) { if ($_item->representProduct($product)) { $item = $_item; break; } } if ($item === null) { $storeId = $product->hasPartslistStoreId() ? $product->getPartslistStoreId() : $this->getStore()->getId(); $item = Mage::getModel('schrackwishlist/partslist_item'); $item->setProductId($product->getId()) ->setPartslistId($this->getId()) ->setAddedAt(now()) ->setStoreId($storeId) ->setOptions($product->getCustomOptions()) ->setProduct($product) ->setQty($qty) ->setReferrerUrl($referrerUrl) ->save(); } else { $qty = $forciblySetQty ? $qty : $item->getQty() + $qty; $item->setQty($qty) ->save(); } $this->addItem($item); return $item; } /** * Retrieve wishlist item collection * * @return Schracklive_SchrackWishlist_Model_Mysql4_Partslist_Item_Collection */ public function getItemCollection() { if (is_null($this->_itemCollection)) { $this->_itemCollection = Mage::getResourceModel('schrackwishlist/partslist_item_collection') ->addPartslistFilter($this); } return $this->_itemCollection; } /** * Retrieve wishlist item collection * * @param int $itemId * @return Schracklive_SchrackWishlist_Model_Partslist_Item */ public function getItem($itemId) { if (!$itemId) { return false; } return $this->getItemCollection()->getItemById($itemId); } public function getItemByProduct($product) { $this->_itemCollection = null; return $this->getItemCollection() ->addFieldToFilter('partslist_id', $this->getId()) ->addFieldToFilter('product_id', $product->getId()) ->getFirstItem(); } /** * Retrieve Product collection * * @deprecated after 1.4.2.0 * @see Mage_Wishlist_Model_Wishlist::getItemCollection() * * @return Mage_Wishlist_Model_Mysql4_Product_Collection */ public function getProductCollection() { $collection = $this->getData('product_collection'); if (is_null($collection)) { $collection = Mage::getResourceModel('schrackwishlist/partslist/product_collection'); $this->setData('product_collection', $collection); } return $collection; } public function getIsProductOnList($product) { if ($product instanceof Mage_Catalog_Model_Product) { $productId = $product->getId(); } else { $productId = (int) $product; } $count = $this->getItemCollection()->addFieldToFilter('partslist_id', $this->getId()) ->addFieldToFilter('product_id', $productId) ->count(); return ($count === 1); } public function truncate() { foreach ($this->getItemCollection() as $item) { $item->delete(); $item->isDeleted(true); } $this->save(); } public function delete() { if ($this->getIsActive()) { $partslists = Mage::getModel('schrackwishlist/partslist')->getCollection() ->addFieldToFilter('customer_id', array('=' => $this->getCustomerId())) ->addFieldToFilter('is_active', array('=' => 0)) ->setOrder('description', 'ASC') ->setPageSize(1) ->setCurPage(0); if ($partslists->count() === 1) { foreach ($partslists as $list) { $list->activate(); break; } } else if ($partslists->count() === 0) { throw new Exception('cannot delete the only remaining partslist'); } else { throw new Exception('unable to set a new active partslist'); } } parent::delete(); } public function getCustomer() { $customer = Mage::getModel('customer/customer')->load($this->getCustomerId()); return $customer; } public function sendRequestOfferEmails($ecplCustomer, $params) { $this->_sendRequestOfferSchrackcustomerEmail($ecplCustomer, $params); $this->_sendRequestOfferEndcustomerEmail($ecplCustomer, $params); } public function setEcplValues($params) { $this->setIsVisible(1); $this->setDescription($params['name']); $helper = Mage::helper('core'); $comment = <<<EOT {$helper->__('Name ')}: {$params['name']} {$helper->__('Email')}: {$params['email']} {$helper->__('Address')}: {$params['address']} {$helper->__('Phone')}: {$params['phone']} {$helper->__('Message')}: {$params['message']} EOT; $this->setComment($comment); $this->save(); } private function _sendRequestOfferSchrackcustomerEmail($ecplCustomer, $params) { $block = Mage::getBlockSingleton('core/template'); $block->setTemplate('wishlist/endcustomerpartslist/email_requestoffer_schrackcustomer.phtml'); $block->assign('params', $params); $block->assign('partslist', $this); $block->assign('ecplCustomer', $ecplCustomer); $html = $block->toHtml(); $mailHelper = Mage::helper('wws/mailer'); $toAddress = $ecplCustomer->getEmail(); if (isset($toAddress)) { Mage::log("_sendRequestOfferEmail sending to $toAddress", null, 'ecpl.log'); Mage::log($html, null, 'ecpl.log'); $args = array('subject' => Mage::helper('wishlist')->__('Kunden Online-Schauraum Anfrage'), 'to' => $toAddress, 'cc' => null, 'bcc' => null, 'body' => $html, 'templateVars' => array() ); if ( self::FIXED_DEBUG_CC ) { $args['cc'] = self::FIXED_DEBUG_CC; } $mailHelper->send($args); } else { throw new Exception('no receiver for checkout request email given'); } } private function _sendRequestOfferEndcustomerEmail($ecplCustomer, $params) { $block = Mage::getBlockSingleton('core/template'); $block->setTemplate('wishlist/endcustomerpartslist/email_requestoffer_endcustomer.phtml'); $block->assign('params', $params); $block->assign('partslist', $this); $block->assign('ecplCustomer', $ecplCustomer); $html = $block->toHtml(); $mailHelper = Mage::helper('wws/mailer'); $toAddress = $params['email']; if (isset($toAddress)) { Mage::log("_sendRequestOfferEndcustomerEmail sending to $toAddress", null, 'ecpl.log'); Mage::log($html, null, 'ecpl.log'); $args = array('subject' => Mage::helper('wishlist')->__('Your Request In The Online Showroom'), 'to' => $toAddress, 'cc' => null, 'bcc' => null, 'body' => $html, 'templateVars' => array() ); if ( self::FIXED_DEBUG_CC ) { $args['cc'] = self::FIXED_DEBUG_CC; } $mailHelper->send($args); } else { throw new Exception('no receiver for checkout request email given'); } } public function sendShareEmail($ecplCustomer, $params) { $block = Mage::getBlockSingleton('core/template'); $block->setTemplate('wishlist/endcustomerpartslist/email_share.phtml'); $block->assign('params', $params); $block->assign('partslist', $this); $html = $block->toHtml(); $mailHelper = Mage::helper('wws/mailer'); $toAddress = $params['email']; Mage::log($html, null, 'xian.log'); if (isset($toAddress)) { $args = array('subject' => Mage::helper('wishlist')->__('Endcustomer partslist'), 'to' => $toAddress, 'cc' => null, 'bcc' => null, 'body' => $html, 'templateVars' => array() ); $mailHelper->send($args); } else { throw new Exception('no receiver for email given'); } } } ?>
import $ivy.`org.typelevel::cats-core:2.0.0` //ref: https://github.com/com-lihaoyi/Ammonite/issues/534 //ref: https://gist.github.com/MateuszKubuszok/a80503b28f289f08f2f6c6c70871e8d3#log-implicits //ref: https://www.scala-lang.org/api/2.12.4/scala-compiler/scala/tools/nsc/Settings.html interp.configureCompiler(_.settings.Ydelambdafy.value ="inline") @ import cats.data.Reader import cats.Eq import cats.instances.all._ import cats.syntax.eq._ //for eq final case class Db( usernames: Map[Int, String], passwords: Map[String, String] ) type DbReader[A] = Reader[Db, A] def findUsername(userId: Int): DbReader[Option[String]] = { Reader(db => db.usernames.get(userId)) } def checkPassword(usernameOpt: Option[String], password: String): DbReader[Boolean] = { Reader(db => usernameOpt.map(username => db.passwords.get(username).exists(i => i === password)) .getOrElse(false) ) } def checkLogin(userId: Int, password: String): DbReader[Boolean] = { for { nameOpt <- findUsername(userId) isValid <- checkPassword(nameOpt, password) } yield { isValid } } val users = Map( 1 -> "dade", 2 -> "kate", 3 -> "margo" ) val passwords = Map( "dade" -> "zerocool", "kate" -> "acidburn", "margo" -> "secret" ) val db = Db(users, passwords) val res1 = checkLogin(1, "zerocool").run(db) // res7: cats.package.Id[Boolean] = true val res2 = checkLogin(4, "davinci").run(db) // res8: cats.package.Id[Boolean] = false println(s"res1: ${res1}, res2: ${res2}")
import * as React from 'react' import Button from '@mui/material/Button' import Dialog from '@mui/material/Dialog' import DialogActions from '@mui/material/DialogActions' import DialogContent from '@mui/material/DialogContent' import DialogContentText from '@mui/material/DialogContentText' import DialogTitle from '@mui/material/DialogTitle' import * as S from './styles' import { TransitionProps } from '@mui/material/transitions' import { Slide } from '@mui/material' // type F = () => void // type PromiseF = () => Promise<void> interface I_Props { children: React.ReactNode open: boolean setOpen: (open: boolean) => void // onSubmit: PromiseF | F title?: string text?: string } const Transition = React.forwardRef(function Transition( props: TransitionProps & { children: React.ReactElement<any, any> }, ref: React.Ref<unknown>, ) { return <Slide direction='up' ref={ref} {...props} /> }) export default function DialogContainer({ children, title, text, open, setOpen, }: // onSubmit, I_Props) { // const [open, setOpen] = React.useState(false) const handleClose = () => { setOpen(false) } // const handleSubmit = async () => { // await onSubmit() // setOpen(false) // } return ( <div> <Dialog open={open} onClose={handleClose} TransitionComponent={Transition} sx={{ '.MuiPaper-root': { maxWidth: 'calc(100% - 64px)' } }} > {title && <DialogTitle>{title}</DialogTitle>} <DialogContent> {text && <DialogContentText>{text}</DialogContentText>} {children} </DialogContent> <DialogActions> {/* <Button onClick={handleClose}>Cancel</Button> */} {/* <Button onClick={handleSubmit}>Submit</Button> */} </DialogActions> </Dialog> </div> ) }
import React from 'react' import { Button } from '@nextui-org/react' import apiBackendUrl from '../../lib/axios' import { useState } from 'react' import { newServiceType } from 'types/ServicesTypes' import Loading from '../Spinner/Loading' import {toast} from "react-toastify" import { userStore } from '../../store/store' import handleError from '../../utils/AxiosErrorFragment' interface Props { update: () => void, goBack: () => void } const AddnewService = ({update, goBack}: Props) => { const [service, setService] = useState<string>("") const [price, setPrice] = useState<number>(0) const [succesMessage, setSuccesMessage] = useState<boolean>(false) const [badMessage, setBadMessage] = useState<boolean>(false) const [message, setMessage] = useState<string>("") const [load, setLoad] = useState<boolean>(false) const user = userStore(state => state.user) const handleInputService = (event: React.ChangeEvent<HTMLInputElement>) => { setService(event.target.value) } const handleInputPrice = (event: React.ChangeEvent<HTMLInputElement>) => { setPrice(Number(event.target.value)) } const sendNewService = async () => { if(service.length === 0) { toast.error("Debes completar todos los campos", { style: { backgroundColor: 'white', color: 'blue' }, pauseOnHover: false, autoClose: 2000 }); } else { setLoad(true) const newService: newServiceType = ({ service: service, price: price, }) try { const {status, data} = await apiBackendUrl.post(`/services/createService/${user?._id}`, newService) if(status === 200) { toast.success(data, { style: { backgroundColor: 'white', color: 'blue' }, pauseOnHover: false, autoClose: 2000 }); update() } } catch (error) { handleError(error, setLoad) } } } return ( <div className='w-full'> <div className='flex justify-start items-center boder-b'> <h5 className='font-medium text-black text-md mt-2'>Creando Nuevo Servicio</h5> </div> <div className='flex flex-col items-start justify-start text-center mt-12 w-full'> <div className='flex gap-12 items-center justify-center'> <div className='flex flex-col items-start justify-start'> <p className="text-black text-md font-medium">Nombre del Servicio</p> <input type="text" name="price" id="price" className=" mt-1s w-80 2xl:w-96 rounded-md border-1 py-1.5 pl-7 pr-20 sm:text-sm sm:leading-6 focus:outline-none" value={service} onChange={handleInputService} /> </div> <div className='flex flex-col items-start justify-start'> <p className="text-black text-md font-medium">Precio</p> <input type="text" name="price" id="price" className=" mt-1s w-80 2xl:w-96 rounded-md border-1 py-1.5 pl-7 pr-20 sm:text-sm sm:leading-6 focus:outline-none" value={price?.toString()} onChange={handleInputPrice} /> </div> </div> <div className='flex items-center justify-center text-center mt-4 gap-2'> <Button className="bg-blue-500 text-white font-medium text-sm w-96 h-10" onClick={() => sendNewService()}>Crear</Button> <Button className="bg-gray-400 text-white font-medium text-sm w-96 h-10" onClick={() => goBack()}>Cancelar</Button> </div> {load ? <div className='flex items-center justify-center mt-4 mb-2'> <Loading/> </div>: null} {badMessage ? <div className='mt-6 mb-2 flex items-center justify-center'> <p className='text-white bg-red-500 w-full text-center font-medium text-md'>{message}</p> </div> : null } {succesMessage ? <div className='mt-6 mb-2 flex items-center justify-center'> <p className='text-white bg-blue-500 w-full text-center font-medium text-md'>{message}</p> </div> : null } </div> </div> ) } export default AddnewService
import { useState } from "react" import PatchInventoryItem from "./PatchInventoryItem"; import PropTypes from 'prop-types'; const UpdateInventoryModal = ({item,onCancel,onSuccess}) => { const [updateName,setUpdateName] = useState(item.name); const [updateCategory,setUpdateCategory] = useState(item.category); const [updateQuantity, setUpdateQuantity] = useState(item.quantity); const [updatePrice, setUpdatePrice] = useState(item.price); const [updateSupplier,setUpdateSupllier] = useState(item.supplier); const [updateStatus, setUpdateStatus] = useState(item.status); UpdateInventoryModal.propTypes = { item: PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, category: PropTypes.string.isRequired, quantity: PropTypes.number.isRequired, price: PropTypes.number.isRequired, supplier: PropTypes.string.isRequired, status: PropTypes.string.isRequired, }).isRequired, onCancel: PropTypes.func.isRequired, onSuccess: PropTypes.func.isRequired }; const handleCancel = () => { onCancel(); } const handleStatusChange = (event) => { setUpdateStatus(event.target.value); }; const handleSubmit = (e) => { e.preventDefault() const updatedFields = { name: updateName, category: updateCategory, quantity: updateQuantity, price: updatePrice, supplier: updateSupplier, status: updateStatus }; PatchInventoryItem(item.id, updatedFields) .then(() => { if(onSuccess){ onSuccess(); } onCancel(); }) .catch((error) => { console.error('Error updating inventory item ', error.message) }) } return( <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center"> <form onSubmit={handleSubmit} className="p-6 max-w-2xl mx-auto bg-white rounded-xl shadow-md overflow-hidden"> <h1 className="text-2xl font-bold text-center mb-6">Create a new Inventory Item</h1> <div className="space-y-4"> <div> <label className="block text-sm font-medium text-gray-700">Inventory Name</label> <input className="mt-1 px-4 py-2 border border-gray-300 rounded-lg w-full focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" value={updateName} type="text" placeholder="Inventory Name" onChange={(e) => setUpdateName(e.target.value)} /> </div> <div> <label className="block text-sm font-medium text-gray-700">Inventory Category</label> <input className="mt-1 px-4 py-2 border border-gray-300 rounded-lg w-full focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" value={updateCategory} type="text" placeholder="Inventory Category" onChange={(e) => setUpdateCategory(e.target.value)} /> </div> <div> <label className="block text-sm font-medium text-gray-700">Inventory Quantity</label> <input className="mt-1 px-4 py-2 border border-gray-300 rounded-lg w-full focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" value={updateQuantity} type="number" onChange={(e) => setUpdateQuantity(e.target.value)} /> </div> <div> <label className="block text-sm font-medium text-gray-700">Inventory Price</label> <input className="mt-1 px-4 py-2 border border-gray-300 rounded-lg w-full focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" value={updatePrice} type="number" onChange={(e) => setUpdatePrice(e.target.value)} /> </div> <div> <label className="block text-sm font-medium text-gray-700">Inventory Supplier</label> <input className="mt-1 px-4 py-2 border border-gray-300 rounded-lg w-full focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" value={updateSupplier} type="text" placeholder="Inventory Supplier" onChange={(e) => setUpdateSupllier(e.target.value)} /> </div> <div> <label className="block text-sm font-medium text-gray-700">Inventory Status</label> <select className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md" value={updateStatus} onChange={handleStatusChange} > <option value="AVAILABLE">Available</option> <option value="OUT_OF_STOCK">Out of Stock</option> <option value="DISCONTINUED">Discontinued</option> </select> </div> <button type="submit" className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"> Update </button> <button type="button" className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" onClick={handleCancel}> Cancel </button> </div> </form> </div> ) } export default UpdateInventoryModal;
# buble sort # data_list = [1,4,2,5,7,6,9,8] # for i in range(len(data_list)): # for j in range(len(data_list)-i-1): # if data_list[j] > data_list[j + 1]: # data_list[j], data_list[j+1] = data_list[j + 1], data_list[j] # print(data_list) # def sorting(list): # n = len(list) # for i in range(n): # for j in range(n-i-1): # if list[j] > list[j+1]: # list[j],list[j+1] = list[j+1], list[j] # return list # heap sorting import time def heapify(arr, n, i): largest = i # Menginisialisasi node terbesar sebagai root left_child = 2 * i + 1 right_child = 2 * i + 2 # Memeriksa apakah left child dari root ada dan lebih besar dari root if left_child < n and arr[left_child] > arr[largest]: largest = left_child # Memeriksa apakah right child dari root ada dan lebih besar dari root if right_child < n and arr[right_child] > arr[largest]: largest = right_child # Jika node terbesar bukan root, lakukan pertukaran dengan root if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Swap heapify(arr, n, largest) def heap_sort(arr): n = len(arr) # Membangun max heap for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # Ekstraksi elemen satu per satu dari heap for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # Swap heapify(arr, i, 0) # Contoh penggunaan arr = [12, 11, 13, 5, 6, 7] print("Array sebelum diurutkan:", arr) mulai = time.time() heap_sort(arr) selesai = time.time() print("Array setelah diurutkan:", arr) print(f"run time {selesai - mulai}") # def heap_sorting(arr,size,index): # parent_index = index # kiri = 2 * index + 1 # kanan = 2 * index + 2 # # cek kiri # if kiri < size and arr[kiri] > arr[parent_index]: # parent_index = kiri # # cek kanan # if kanan < size and arr[kanan] > arr[parent_index]: # parent_index = kanan # if parent_index != size: # arr[index], arr[parent_index] = arr[index], arr[parent_index] # heap_sorting(arr,size,index) # def heap_sort(arr): # n = len(arr) # # max heap # for i in range(n// 2-1,-1,-1): # heap_sorting(arr,n,index)
package com.example.flappybird; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import java.util.ArrayList; /** * This class is used to create the user controlled object "Bird" and draw it onto the canvas. * * @class Bird */ public class Bird extends BaseObject { // Defines an array for the bitmap which stores information about the bird. private ArrayList<Bitmap> arrBms = new ArrayList<>(); // Creates variables which affect the Bird object. private int count, vFlap, idCurrentBitmap; private float drop; /** * Defines variables for the bird object. */ public Bird() { this.count = 0; this.vFlap = 5; this.idCurrentBitmap = 0; this.drop = 0; } /** * Draws the bird onto the game canvas using its x and y variables. * @param canvas the canvas on which the bird is drawn using the bitmap "arrBms". */ public void draw(Canvas canvas) { drop(); canvas.drawBitmap(this.getBm(), this.x, this.y, null); } /** * Increases the drop speed and the bird y variable (larger the value the further down the * screen the bird will appear). */ private void drop() { this.drop += 0.6; this.y += this.drop; } /** * Sets the array "arrBms" to the same as the inputted array. This is looped for the length of * the inputted array. * @param arrBms the inputted array. */ public void setArrBms(ArrayList<Bitmap> arrBms) { this.arrBms = arrBms; for (int i = 0; i < arrBms.size(); i++) { this.arrBms.set(i, Bitmap.createScaledBitmap(this.arrBms.get(i), this.width, this.height, true)); } } /** * Returns the desired bitmap based on the id set in the variable "idCurrentBitmap". This * bitmap is used by the canvas to draw the bird onto. * @return "bitmap" the bitmap which the canvas uses. */ @Override public Bitmap getBm() { count++; if (this.count == this.vFlap) { for (int i = 0; i < arrBms.size(); i++) { if (i == arrBms.size()-1) { this.idCurrentBitmap = 0; break; } else if (this.idCurrentBitmap == i) { idCurrentBitmap = i+1; break; } } count = 0; } if (this.drop < 0) { Matrix matrix = new Matrix(); matrix.postRotate(-25); return Bitmap.createBitmap(arrBms.get(idCurrentBitmap), 0, 0, arrBms.get(idCurrentBitmap).getWidth(), arrBms.get(idCurrentBitmap).getHeight(), matrix, true); } else if (drop >= 0) { Matrix matrix = new Matrix(); if (drop < 70) { matrix.postRotate(-25+(drop*2)); } else { matrix.postRotate(45); } return Bitmap.createBitmap(arrBms.get(idCurrentBitmap), 0, 0, arrBms.get(idCurrentBitmap).getWidth(), arrBms.get(idCurrentBitmap).getHeight(), matrix, true); } return this.arrBms.get(idCurrentBitmap); } /** * Returns the drop value which changes the bird's y variable (y axis / height). * @return drop the drop value. */ public float getDrop() { return drop; } /** * Sets the drop value of the bird to the inputted float value. * @param drop the inputted float value. */ public void setDrop(float drop) { this.drop = drop; } }
package com.example.composepractice.Screens.ExploreScreenComposable.ExploreList import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.composepractice.CommonUI.BoldText import com.example.composepractice.CommonUI.RegularText import com.example.composepractice.Models.ExploreListItem.ExploreListItem import com.example.composepractice.R @Composable fun ExploreMountainsList() { val mountainList = ExploreListItem( "Mountains", "A place to wonder", listOf( "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga", "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga", "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga", "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga", "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga", "Mt.Everest", "Mt.Makalu", "Mt.Kanchenjunga" ) ) Column(modifier = Modifier.padding(bottom = 15.dp)) { BoldText( text = mountainList.title, textSize = 26.sp, modifier = Modifier.padding(start = 10.dp) ) RegularText( text = mountainList.subTitle, textSize = 20.sp, modifier = Modifier.padding(start = 10.dp) ) ExploreRowItemComposable(mountainList.locationList, R.drawable.mountains_img) } }
using System; namespace SDP_Assignment3 { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to the Fashion Boutique!"); Console.WriteLine("Please select a brand to explore: "); Console.WriteLine("1. American Eagle"); Console.WriteLine("2. Dior"); Console.WriteLine("3. Chanel"); Factory selectedFactory = null; bool validInput = false; while (!validInput) { if (int.TryParse(Console.ReadLine(), out int brandChoice)) { switch (brandChoice) { case 1: selectedFactory = new AE_Factory(); validInput = true; break; case 2: selectedFactory = new Dior_Factory(); validInput = true; break; case 3: selectedFactory = new Channel_Factory(); validInput = true; break; default: Console.WriteLine("Invalid brand choice. Please select a valid brand (1, 2, or 3)."); break; } } else { Console.WriteLine("Invalid input. Please enter a numeric choice (1, 2, or 3)."); } } Pants pants = selectedFactory.CreatePants(); Jacket jacket = selectedFactory.CreateJacket(); Shirt shirt = selectedFactory.CreateShirt(); // Call functions for each item Console.WriteLine("Pants:"); pants.Color(); pants.HasZipper(); pants.HasPockets(); pants.Size(); pants.Material(); Console.WriteLine("\n"); Console.WriteLine("Jacket:"); jacket.Material(); jacket.Size(); jacket.Gender(); jacket.Customize(); Console.WriteLine("\n"); Console.WriteLine("Shirt:"); shirt.CollarType(); shirt.HasPattern(); shirt.SleeveType(); } } }
#include <iostream> #include <mutex> class MySingleton { private: static std::once_flag initInstanceFlag; static MySingleton* instance; MySingleton()= default; ~MySingleton()= default; public: MySingleton(const MySingleton&)= delete; MySingleton& operator=(const MySingleton&)= delete; static MySingleton* getInstance() { std::call_once(initInstanceFlag,MySingleton::initSingleton); return instance; } static void initSingleton(){ instance= new MySingleton(); } }; MySingleton* MySingleton::instance = nullptr; std::once_flag MySingleton::initInstanceFlag; int main() { std::cout << std::endl; std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << std::endl; std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << std::endl; std::cout << std::endl; }
package com.example.intentsevensolutionpro import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.example.intentsevensolutionpro.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.btnCallActivity.setOnClickListener(this) binding.btnSendData.setOnClickListener(this) binding.btnSendDataObject.setOnClickListener(this) binding.btnSendPacelObjdect.setOnClickListener(this) binding.btnSendPaceArrayList.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id) { R.id.btnCallActivity -> { val intent = Intent(this, MainActivity2::class.java) startActivity(intent) } R.id.btnSendData -> { val intent = Intent(this, MainActivity2::class.java) intent.putExtra("id", "admin") intent.putExtra("pwd", "123456") startActivity(intent) } R.id.btnSendDataObject -> { val intent = Intent(this, MainActivity2::class.java) //객체를 만들어서 보내야 하기에 두번째 방법을 사용할수 없음. val loginData = LonginData("admin","123456") //만약 데이터 부분에서 Serializable 부분이 없다면 뜨지 않음.(데이터를 외부로 전송시 사용) intent.putExtra("loginData",loginData) intent.putExtra("no",3) startActivity(intent) } R.id.btnSendPacelObjdect -> { val intent = Intent(this, MainActivity2::class.java) val loginDataParcel = LoginDataParcel("admin","123456") intent.putExtra("no",4) intent.putExtra("loginDataParcel",loginDataParcel) startActivity(intent) } R.id.btnSendPaceArrayList -> { val intent = Intent(this, MainActivity2::class.java) val loginDataParcelList = arrayListOf<LoginDataParcel>() loginDataParcelList.add(LoginDataParcel("admin1", "123456-1")) loginDataParcelList.add(LoginDataParcel("admin2", "123456-2")) loginDataParcelList.add(LoginDataParcel("admin3", "123456-3")) loginDataParcelList.add(LoginDataParcel("admin4", "123456-4")) intent.putExtra("no", 5) intent.putExtra("loginDataParcelList", loginDataParcelList) startActivity(intent) } } } //onClick }
<?php namespace App\Http\Controllers\Main; use App\Http\Controllers\Controller; use App\Models\Event; use App\Models\Protocol; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response as HttpResponse; use Illuminate\Support\Facades\Response; use Throwable; final class IndexController extends Controller { protected readonly int $eventsPerPage; protected readonly int $protocolsPerPage; public function __construct() { $this->eventsPerPage = 8; $this->protocolsPerPage = 6; } /** * @throws Throwable */ public function events(Request $request): JsonResponse|HttpResponse { $events = Event::query() ->where('is_active', true) ->with(['location:id,name']) ->orderByDesc('request_access') ->orderByDesc('date_of') ->paginate($this->eventsPerPage); if ($request->ajax()) { return Response::json([ 'content' => view('partials.main.lists.event-list', compact('events'))->render(), 'next' => $events->hasMorePages(), ]); } $meta = [ 'description' => __('meta.index_events.description'), 'keywords' => __('meta.index_events.keywords'), ]; return Response::view('main.index.events', compact('events', 'meta')); } /** * @throws Throwable */ public function protocols(Request $request): JsonResponse|HttpResponse { $protocols = Protocol::query() ->where('is_active', true) ->orderByDesc('updated_at') ->paginate($this->protocolsPerPage); if ($request->ajax()) { return Response::json([ 'content' => view('partials.main.lists.protocol-list', compact('protocols'))->render(), 'next' => $protocols->hasMorePages(), ]); } $meta = [ 'description' => __('meta.index_protocols.description'), 'keywords' => __('meta.index_protocols.keywords'), ]; return Response::view('main.index.protocols', compact('protocols', 'meta')); } }
--- title: "The Ultimate Guide to Selecting Optimal Drones Motors" date: 2024-05-24T08:30:11.311Z updated: 2024-05-25T08:30:11.311Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "This Article Describes The Ultimate Guide to Selecting Optimal Drones Motors" excerpt: "This Article Describes The Ultimate Guide to Selecting Optimal Drones Motors" keywords: "Drone Motor Selection Guide,Optimal Drone Motors Tips,Choosing Best Drones Motors,Ultimate Drone Motor Buying,Top Drone Motors Comparison,Ideal Drones Engine Picking,Prime Motors for Drones" thumbnail: https://www.lifewire.com/thmb/CYuMInxhqGfsz5AC53n9L4-L5n8=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/chris-briggs-Rr6KMv_NYog-unsplash-ca2d5c709f434b72a9e61f973e2edf69.jpg --- ## The Ultimate Guide to Selecting Optimal Drones Motors # Drone Motor: Choose the 5 Best Motors for Your Quadcopter ![author avatar](https://images.wondershare.com/filmora/article-images/max-wales-author.jpg) ##### Max Wales Mar 27, 2024• Proven solutions You might be thinking about the [aerial photography](https://en.wikipedia.org/wiki/Aerial%5Fphotography) capabilities of your drone unit. What makes it capable enough to do so? It is motor unit of your quadcopter that ensures aerial movements so that users can develop Hollywood Style movies with ease. The article below will help you to learn about [ultirotor motor](https://www.kdedirect.com/pages/brushless-motors) basics so that you can choose the best one for your quadcopter. There are so many motor designs available in market, prefer to pick the one that can meet all your requirements and fits to your budget too. * [Part 1: Things to consider when choosing drone motors](#part1) * [Part 2: Types of motors](#part2) * [Part 2: Best Recommendations](#part3) ## Part 1: Things to consider when choosing drone motors #### 1\. Weight of your drone The very first criterion for selection of right motor for your drone is to have clear idea about overall weight of drone itself. You can have approximate weight idea for your drone by simply calculating weight of its individual parts or components. But note that the list must include all parts like payload (if you are connecting gimbals and camera), battery unit, motors, wires, PDB, flight controller and frame of the device. Once you know the overall size of frame then it can help you to determine right propeller size. Whereas the idea about size and weight of propeller will help users to know about the overall thrust of motor that they will need for perfect lifting of drone during flights. Your decision will help to maintain speed of drone in air and this weight will also contribute in flight time adjustments. #### 2\. Thrust to weight ratio Do you know the golden rule for selection of drone motor? It must allow your drone to hover in the midair with half throttle. It clearly means that your selected motor must be capable enough to produce about 50 percent higher thrust as compared to multi rotor. This is a very essential parameter as it means your motor is going to have additional thrust to keep your drone safe during windy weather or at the time of flight maneuvers. Let us consider a situation: suppose your drone have overall weight of 650 grams then we need to pick a motor that can generate at least twice amount of thrust. Means thrust must range somewhere around 1360 Grams where each motor must be capable enough to produce 340 grams thrust. And in case if they are able to produce higher thrust then this rated value, your drone will naturally become able to move with much faster speed. #### 3\. Efficiency The formula used for calculation of motor efficiency is “thrust/power used in W”; its overall unit becomes g/W. now, if you have higher value of g/W rating that means your motor is more efficient and it will assist drone in longer flights. Professionals recommend choosing a motor that has efficiency value near about 7 or above this. There are chances that a motor could be efficient with its lower throttle range; in that case they will lose efficiency with increasing current range at higher limits. When you connect motors having low efficiency to your drone unit then you have to make lots of compromise for flight time as well as energy. It will also cause voltage sags for your batteries. Never forget to check thrust/current ratio while buying new motor for your drone. #### 4\. Torque The torque range helps to define the ability of motor to shift between RPM values. This change ultimately decides responsiveness of drone in air. If your motor has high torque value then it will naturally lead to snappy response as RPM will accept faster changes. It will also lead to lesser propeller wash. If you have high torque value for your motor then it means it is capable enough to run much heavier props but will also suck more current. In case if you try to fir a heavier propeller on low torque type motor, it will not be able to achieve the desired RPM value or will not be able to generate enough torque for spinning. Ultimately, it will end up making lower thrust while drawing lower current from system. However, there is one disadvantage of connection high torque type motors; that is, it generates more oscillations and they cannot be tuned so easily. Note that, high torque type motors are able to generate faster response rate so users can move between different RPM rating easily and efficiently. It may also amplify error and can cause oscillations even at yaw axis. #### 5\. Pole Count Next important consideration is motor pole count. You will generally find two options for this: first one if quadcopter motors that have higher pole count. These types of motors are able to produce greater torque value but at the same time it will demand more voltage for operation. Note that these motors are able to produce lower RPM. Professionals suggest choosing larger blades for such motors. If we talk about the second category, here you will find motors having lower pole count but they deliver higher RPM. Now, these motors will be accompanied by smaller blades and will serve with smaller lift from ground. If you want to get rid of additional gear box then it is essential to start with higher pole count. ## Part 2: Types of motors | Type | Definition | Application | Lifespan | Energy saving | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Brushed DC motor | Brushed DC motors possess a rotating armature that works like a electromagnet having two poles. A rotary switch is connected that helps to reverse current direction for every half cycle so that poles can be pushed or pulled against permanent magnets connected outside motor. | It is commonly used as a power tool for drones. | It can serve users up to 1000 hours or less. | In case of Brushed motor designs, you need to invest upon continuous maintenance for carbon crushes to ensure proper energy consumption and satisfactory operation. | | Brushless DC motor | Brushless DC Motors do not possess brushes, they just have a permanent magnet and it switched with electronic polarity changes. Its movements can be controlled via a dedicated electronic controller and speed feedback mechanism. | These motors are commonly used for drones that demand higher rotation speeds to manage flights. | Brushed DC motors are capable enough to work effectively up to more than 1000 hours | Brusheless motors are highly energy efficient as compared to brushed ones. | **Verdict:** If you are working on a project where motor is expected to be used for very less time, it is recommended to connect brushed DC motor as it will provide sufficient output with cost effectiveness. But in case if you need motors continuously or when your device is going to work on higher power rating then brushless motor will be best idea for long hour flights. ## 5 Best Recommendation for Drone Motors #### 1\. [Coolplay syma x5c-1 x5c x5 motors](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [coolplay syma x5c motors](https://images.wondershare.com/filmora/article-images/coolplay-syma-x5c-motors.jpg) ](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [Check at Amazon](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) **Price:** $8.99 only **Key Features:** * It is designed with brass metal gear that offers super stable performance with ultra high durability. * Their wire colour codes are same as that of original models so replacement task becomes much easier. * Overall performance is rated to be as high as stock motors. * This motor design is compatible with all Syma X models. **Pros:** * Lower Price range. * Great customer service * Ultra durable and super stable design. **Cons:** * Motors create annoying sound. #### 2\. [Hobbymate quadcopter kit motor](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [hobbymate quadcopter kit motor](https://images.wondershare.com/filmora/article-images/hobbymate-quadcopter-kit-motor.jpg) ](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [Check at Amazon](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) **Price:** $58 **Key Features:** * Best choice for FPV QAV quadcopters having 250, 210, 180 size range; and for small drones. * Impressive air suction system. * U clip added to protect loosening issue of bearing. * High precision type CNC machine exquisite design. **Pros:** * Rapid cooling system. * Longer battery life with higher efficiency. * Light weight design. * Offers longer flight time. * Lesser vibrations with low CG design. #### 3\. [Parrot AR Drone 2.0 motor](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [parrot ar drone 2.0 motor](https://images.wondershare.com/filmora/article-images/parrot-ar-drone-2.0-motor.jpg) ](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [Check at Amazon](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) **Price:** $28.99b **Key Features:** * This motor possesses maximum power of 15 watts and can complete about 28000 rotations/minute in air. * Range of these motors begins at 10,350 RPM and it goes up to 41,400 RPM. * Speed of motor is controlled via a 8 bit low power type microcontroller accompanied with 10 bit ADC. **Pros:** * It is much easier to install. * Consumes less power, increased efficiency. * Secured with long and short screw connections. * Offers guaranteed high performance. **Cons:** * Expensive option. #### 4\. [Hobbypower A2212 brushless motor](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [hobbypower a2212 brushless motor](https://images.wondershare.com/filmora/article-images/hobbypower-a2212-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [Check at Amazon](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) **Price:** $15.99 **Key Features:** * This brushless motor ensures service with KV value of 1000. * It comes with 30A advanced speed controller unit. * Can offer maximum speed of 2100000 RPM with 2 poles type BLM and about 70,000 RPM with 6 pole type **Pros:** * Price range is nominal. * It stays cool even during tough flights. * It adds more power to your RC drone unit. **Cons:** * Motor gets heated up within very less time. * It causes lots of vibrations during motor acceleration. #### 5\. [Emax Mt2213 brushless motor](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [emax mt2213 brushless motor](https://images.wondershare.com/filmora/article-images/emax-mt2213-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [Check at Amazon](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) **Price:** $68.25 **Key Features:** * Impressive multi rotor motor design. * Offers classic response performance. * Multi rotor options available like Octo, Hexa, Quad and Tri. * Maximum thrust goes up to 860G. **Pros:** * Easy to set up. * Solid design. * Balanced and smooth motors. **Cons:** * Too costly. * Maximum weight is 55 grams. ![author avatar](https://images.wondershare.com/filmora/article-images/max-wales-author.jpg) Max Wales Max Wales is a writer and a lover of all things video. Follow @Max Wales ##### Max Wales Mar 27, 2024• Proven solutions You might be thinking about the [aerial photography](https://en.wikipedia.org/wiki/Aerial%5Fphotography) capabilities of your drone unit. What makes it capable enough to do so? It is motor unit of your quadcopter that ensures aerial movements so that users can develop Hollywood Style movies with ease. The article below will help you to learn about [ultirotor motor](https://www.kdedirect.com/pages/brushless-motors) basics so that you can choose the best one for your quadcopter. There are so many motor designs available in market, prefer to pick the one that can meet all your requirements and fits to your budget too. * [Part 1: Things to consider when choosing drone motors](#part1) * [Part 2: Types of motors](#part2) * [Part 2: Best Recommendations](#part3) ## Part 1: Things to consider when choosing drone motors #### 1\. Weight of your drone The very first criterion for selection of right motor for your drone is to have clear idea about overall weight of drone itself. You can have approximate weight idea for your drone by simply calculating weight of its individual parts or components. But note that the list must include all parts like payload (if you are connecting gimbals and camera), battery unit, motors, wires, PDB, flight controller and frame of the device. Once you know the overall size of frame then it can help you to determine right propeller size. Whereas the idea about size and weight of propeller will help users to know about the overall thrust of motor that they will need for perfect lifting of drone during flights. Your decision will help to maintain speed of drone in air and this weight will also contribute in flight time adjustments. #### 2\. Thrust to weight ratio Do you know the golden rule for selection of drone motor? It must allow your drone to hover in the midair with half throttle. It clearly means that your selected motor must be capable enough to produce about 50 percent higher thrust as compared to multi rotor. This is a very essential parameter as it means your motor is going to have additional thrust to keep your drone safe during windy weather or at the time of flight maneuvers. Let us consider a situation: suppose your drone have overall weight of 650 grams then we need to pick a motor that can generate at least twice amount of thrust. Means thrust must range somewhere around 1360 Grams where each motor must be capable enough to produce 340 grams thrust. And in case if they are able to produce higher thrust then this rated value, your drone will naturally become able to move with much faster speed. #### 3\. Efficiency The formula used for calculation of motor efficiency is “thrust/power used in W”; its overall unit becomes g/W. now, if you have higher value of g/W rating that means your motor is more efficient and it will assist drone in longer flights. Professionals recommend choosing a motor that has efficiency value near about 7 or above this. There are chances that a motor could be efficient with its lower throttle range; in that case they will lose efficiency with increasing current range at higher limits. When you connect motors having low efficiency to your drone unit then you have to make lots of compromise for flight time as well as energy. It will also cause voltage sags for your batteries. Never forget to check thrust/current ratio while buying new motor for your drone. #### 4\. Torque The torque range helps to define the ability of motor to shift between RPM values. This change ultimately decides responsiveness of drone in air. If your motor has high torque value then it will naturally lead to snappy response as RPM will accept faster changes. It will also lead to lesser propeller wash. If you have high torque value for your motor then it means it is capable enough to run much heavier props but will also suck more current. In case if you try to fir a heavier propeller on low torque type motor, it will not be able to achieve the desired RPM value or will not be able to generate enough torque for spinning. Ultimately, it will end up making lower thrust while drawing lower current from system. However, there is one disadvantage of connection high torque type motors; that is, it generates more oscillations and they cannot be tuned so easily. Note that, high torque type motors are able to generate faster response rate so users can move between different RPM rating easily and efficiently. It may also amplify error and can cause oscillations even at yaw axis. #### 5\. Pole Count Next important consideration is motor pole count. You will generally find two options for this: first one if quadcopter motors that have higher pole count. These types of motors are able to produce greater torque value but at the same time it will demand more voltage for operation. Note that these motors are able to produce lower RPM. Professionals suggest choosing larger blades for such motors. If we talk about the second category, here you will find motors having lower pole count but they deliver higher RPM. Now, these motors will be accompanied by smaller blades and will serve with smaller lift from ground. If you want to get rid of additional gear box then it is essential to start with higher pole count. ## Part 2: Types of motors | Type | Definition | Application | Lifespan | Energy saving | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Brushed DC motor | Brushed DC motors possess a rotating armature that works like a electromagnet having two poles. A rotary switch is connected that helps to reverse current direction for every half cycle so that poles can be pushed or pulled against permanent magnets connected outside motor. | It is commonly used as a power tool for drones. | It can serve users up to 1000 hours or less. | In case of Brushed motor designs, you need to invest upon continuous maintenance for carbon crushes to ensure proper energy consumption and satisfactory operation. | | Brushless DC motor | Brushless DC Motors do not possess brushes, they just have a permanent magnet and it switched with electronic polarity changes. Its movements can be controlled via a dedicated electronic controller and speed feedback mechanism. | These motors are commonly used for drones that demand higher rotation speeds to manage flights. | Brushed DC motors are capable enough to work effectively up to more than 1000 hours | Brusheless motors are highly energy efficient as compared to brushed ones. | **Verdict:** If you are working on a project where motor is expected to be used for very less time, it is recommended to connect brushed DC motor as it will provide sufficient output with cost effectiveness. But in case if you need motors continuously or when your device is going to work on higher power rating then brushless motor will be best idea for long hour flights. ## 5 Best Recommendation for Drone Motors #### 1\. [Coolplay syma x5c-1 x5c x5 motors](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [coolplay syma x5c motors](https://images.wondershare.com/filmora/article-images/coolplay-syma-x5c-motors.jpg) ](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [Check at Amazon](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) **Price:** $8.99 only **Key Features:** * It is designed with brass metal gear that offers super stable performance with ultra high durability. * Their wire colour codes are same as that of original models so replacement task becomes much easier. * Overall performance is rated to be as high as stock motors. * This motor design is compatible with all Syma X models. **Pros:** * Lower Price range. * Great customer service * Ultra durable and super stable design. **Cons:** * Motors create annoying sound. #### 2\. [Hobbymate quadcopter kit motor](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [hobbymate quadcopter kit motor](https://images.wondershare.com/filmora/article-images/hobbymate-quadcopter-kit-motor.jpg) ](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [Check at Amazon](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) **Price:** $58 **Key Features:** * Best choice for FPV QAV quadcopters having 250, 210, 180 size range; and for small drones. * Impressive air suction system. * U clip added to protect loosening issue of bearing. * High precision type CNC machine exquisite design. **Pros:** * Rapid cooling system. * Longer battery life with higher efficiency. * Light weight design. * Offers longer flight time. * Lesser vibrations with low CG design. #### 3\. [Parrot AR Drone 2.0 motor](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [parrot ar drone 2.0 motor](https://images.wondershare.com/filmora/article-images/parrot-ar-drone-2.0-motor.jpg) ](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [Check at Amazon](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) **Price:** $28.99b **Key Features:** * This motor possesses maximum power of 15 watts and can complete about 28000 rotations/minute in air. * Range of these motors begins at 10,350 RPM and it goes up to 41,400 RPM. * Speed of motor is controlled via a 8 bit low power type microcontroller accompanied with 10 bit ADC. **Pros:** * It is much easier to install. * Consumes less power, increased efficiency. * Secured with long and short screw connections. * Offers guaranteed high performance. **Cons:** * Expensive option. #### 4\. [Hobbypower A2212 brushless motor](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [hobbypower a2212 brushless motor](https://images.wondershare.com/filmora/article-images/hobbypower-a2212-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [Check at Amazon](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) **Price:** $15.99 **Key Features:** * This brushless motor ensures service with KV value of 1000. * It comes with 30A advanced speed controller unit. * Can offer maximum speed of 2100000 RPM with 2 poles type BLM and about 70,000 RPM with 6 pole type **Pros:** * Price range is nominal. * It stays cool even during tough flights. * It adds more power to your RC drone unit. **Cons:** * Motor gets heated up within very less time. * It causes lots of vibrations during motor acceleration. #### 5\. [Emax Mt2213 brushless motor](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [emax mt2213 brushless motor](https://images.wondershare.com/filmora/article-images/emax-mt2213-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [Check at Amazon](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) **Price:** $68.25 **Key Features:** * Impressive multi rotor motor design. * Offers classic response performance. * Multi rotor options available like Octo, Hexa, Quad and Tri. * Maximum thrust goes up to 860G. **Pros:** * Easy to set up. * Solid design. * Balanced and smooth motors. **Cons:** * Too costly. * Maximum weight is 55 grams. ![author avatar](https://images.wondershare.com/filmora/article-images/max-wales-author.jpg) Max Wales Max Wales is a writer and a lover of all things video. Follow @Max Wales ##### Max Wales Mar 27, 2024• Proven solutions You might be thinking about the [aerial photography](https://en.wikipedia.org/wiki/Aerial%5Fphotography) capabilities of your drone unit. What makes it capable enough to do so? It is motor unit of your quadcopter that ensures aerial movements so that users can develop Hollywood Style movies with ease. The article below will help you to learn about [ultirotor motor](https://www.kdedirect.com/pages/brushless-motors) basics so that you can choose the best one for your quadcopter. There are so many motor designs available in market, prefer to pick the one that can meet all your requirements and fits to your budget too. * [Part 1: Things to consider when choosing drone motors](#part1) * [Part 2: Types of motors](#part2) * [Part 2: Best Recommendations](#part3) ## Part 1: Things to consider when choosing drone motors #### 1\. Weight of your drone The very first criterion for selection of right motor for your drone is to have clear idea about overall weight of drone itself. You can have approximate weight idea for your drone by simply calculating weight of its individual parts or components. But note that the list must include all parts like payload (if you are connecting gimbals and camera), battery unit, motors, wires, PDB, flight controller and frame of the device. Once you know the overall size of frame then it can help you to determine right propeller size. Whereas the idea about size and weight of propeller will help users to know about the overall thrust of motor that they will need for perfect lifting of drone during flights. Your decision will help to maintain speed of drone in air and this weight will also contribute in flight time adjustments. #### 2\. Thrust to weight ratio Do you know the golden rule for selection of drone motor? It must allow your drone to hover in the midair with half throttle. It clearly means that your selected motor must be capable enough to produce about 50 percent higher thrust as compared to multi rotor. This is a very essential parameter as it means your motor is going to have additional thrust to keep your drone safe during windy weather or at the time of flight maneuvers. Let us consider a situation: suppose your drone have overall weight of 650 grams then we need to pick a motor that can generate at least twice amount of thrust. Means thrust must range somewhere around 1360 Grams where each motor must be capable enough to produce 340 grams thrust. And in case if they are able to produce higher thrust then this rated value, your drone will naturally become able to move with much faster speed. #### 3\. Efficiency The formula used for calculation of motor efficiency is “thrust/power used in W”; its overall unit becomes g/W. now, if you have higher value of g/W rating that means your motor is more efficient and it will assist drone in longer flights. Professionals recommend choosing a motor that has efficiency value near about 7 or above this. There are chances that a motor could be efficient with its lower throttle range; in that case they will lose efficiency with increasing current range at higher limits. When you connect motors having low efficiency to your drone unit then you have to make lots of compromise for flight time as well as energy. It will also cause voltage sags for your batteries. Never forget to check thrust/current ratio while buying new motor for your drone. #### 4\. Torque The torque range helps to define the ability of motor to shift between RPM values. This change ultimately decides responsiveness of drone in air. If your motor has high torque value then it will naturally lead to snappy response as RPM will accept faster changes. It will also lead to lesser propeller wash. If you have high torque value for your motor then it means it is capable enough to run much heavier props but will also suck more current. In case if you try to fir a heavier propeller on low torque type motor, it will not be able to achieve the desired RPM value or will not be able to generate enough torque for spinning. Ultimately, it will end up making lower thrust while drawing lower current from system. However, there is one disadvantage of connection high torque type motors; that is, it generates more oscillations and they cannot be tuned so easily. Note that, high torque type motors are able to generate faster response rate so users can move between different RPM rating easily and efficiently. It may also amplify error and can cause oscillations even at yaw axis. #### 5\. Pole Count Next important consideration is motor pole count. You will generally find two options for this: first one if quadcopter motors that have higher pole count. These types of motors are able to produce greater torque value but at the same time it will demand more voltage for operation. Note that these motors are able to produce lower RPM. Professionals suggest choosing larger blades for such motors. If we talk about the second category, here you will find motors having lower pole count but they deliver higher RPM. Now, these motors will be accompanied by smaller blades and will serve with smaller lift from ground. If you want to get rid of additional gear box then it is essential to start with higher pole count. ## Part 2: Types of motors | Type | Definition | Application | Lifespan | Energy saving | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Brushed DC motor | Brushed DC motors possess a rotating armature that works like a electromagnet having two poles. A rotary switch is connected that helps to reverse current direction for every half cycle so that poles can be pushed or pulled against permanent magnets connected outside motor. | It is commonly used as a power tool for drones. | It can serve users up to 1000 hours or less. | In case of Brushed motor designs, you need to invest upon continuous maintenance for carbon crushes to ensure proper energy consumption and satisfactory operation. | | Brushless DC motor | Brushless DC Motors do not possess brushes, they just have a permanent magnet and it switched with electronic polarity changes. Its movements can be controlled via a dedicated electronic controller and speed feedback mechanism. | These motors are commonly used for drones that demand higher rotation speeds to manage flights. | Brushed DC motors are capable enough to work effectively up to more than 1000 hours | Brusheless motors are highly energy efficient as compared to brushed ones. | **Verdict:** If you are working on a project where motor is expected to be used for very less time, it is recommended to connect brushed DC motor as it will provide sufficient output with cost effectiveness. But in case if you need motors continuously or when your device is going to work on higher power rating then brushless motor will be best idea for long hour flights. ## 5 Best Recommendation for Drone Motors #### 1\. [Coolplay syma x5c-1 x5c x5 motors](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [coolplay syma x5c motors](https://images.wondershare.com/filmora/article-images/coolplay-syma-x5c-motors.jpg) ](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [Check at Amazon](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) **Price:** $8.99 only **Key Features:** * It is designed with brass metal gear that offers super stable performance with ultra high durability. * Their wire colour codes are same as that of original models so replacement task becomes much easier. * Overall performance is rated to be as high as stock motors. * This motor design is compatible with all Syma X models. **Pros:** * Lower Price range. * Great customer service * Ultra durable and super stable design. **Cons:** * Motors create annoying sound. #### 2\. [Hobbymate quadcopter kit motor](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [hobbymate quadcopter kit motor](https://images.wondershare.com/filmora/article-images/hobbymate-quadcopter-kit-motor.jpg) ](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [Check at Amazon](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) **Price:** $58 **Key Features:** * Best choice for FPV QAV quadcopters having 250, 210, 180 size range; and for small drones. * Impressive air suction system. * U clip added to protect loosening issue of bearing. * High precision type CNC machine exquisite design. **Pros:** * Rapid cooling system. * Longer battery life with higher efficiency. * Light weight design. * Offers longer flight time. * Lesser vibrations with low CG design. #### 3\. [Parrot AR Drone 2.0 motor](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [parrot ar drone 2.0 motor](https://images.wondershare.com/filmora/article-images/parrot-ar-drone-2.0-motor.jpg) ](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [Check at Amazon](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) **Price:** $28.99b **Key Features:** * This motor possesses maximum power of 15 watts and can complete about 28000 rotations/minute in air. * Range of these motors begins at 10,350 RPM and it goes up to 41,400 RPM. * Speed of motor is controlled via a 8 bit low power type microcontroller accompanied with 10 bit ADC. **Pros:** * It is much easier to install. * Consumes less power, increased efficiency. * Secured with long and short screw connections. * Offers guaranteed high performance. **Cons:** * Expensive option. #### 4\. [Hobbypower A2212 brushless motor](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [hobbypower a2212 brushless motor](https://images.wondershare.com/filmora/article-images/hobbypower-a2212-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [Check at Amazon](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) **Price:** $15.99 **Key Features:** * This brushless motor ensures service with KV value of 1000. * It comes with 30A advanced speed controller unit. * Can offer maximum speed of 2100000 RPM with 2 poles type BLM and about 70,000 RPM with 6 pole type **Pros:** * Price range is nominal. * It stays cool even during tough flights. * It adds more power to your RC drone unit. **Cons:** * Motor gets heated up within very less time. * It causes lots of vibrations during motor acceleration. #### 5\. [Emax Mt2213 brushless motor](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [emax mt2213 brushless motor](https://images.wondershare.com/filmora/article-images/emax-mt2213-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [Check at Amazon](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) **Price:** $68.25 **Key Features:** * Impressive multi rotor motor design. * Offers classic response performance. * Multi rotor options available like Octo, Hexa, Quad and Tri. * Maximum thrust goes up to 860G. **Pros:** * Easy to set up. * Solid design. * Balanced and smooth motors. **Cons:** * Too costly. * Maximum weight is 55 grams. ![author avatar](https://images.wondershare.com/filmora/article-images/max-wales-author.jpg) Max Wales Max Wales is a writer and a lover of all things video. Follow @Max Wales ##### Max Wales Mar 27, 2024• Proven solutions You might be thinking about the [aerial photography](https://en.wikipedia.org/wiki/Aerial%5Fphotography) capabilities of your drone unit. What makes it capable enough to do so? It is motor unit of your quadcopter that ensures aerial movements so that users can develop Hollywood Style movies with ease. The article below will help you to learn about [ultirotor motor](https://www.kdedirect.com/pages/brushless-motors) basics so that you can choose the best one for your quadcopter. There are so many motor designs available in market, prefer to pick the one that can meet all your requirements and fits to your budget too. * [Part 1: Things to consider when choosing drone motors](#part1) * [Part 2: Types of motors](#part2) * [Part 2: Best Recommendations](#part3) ## Part 1: Things to consider when choosing drone motors #### 1\. Weight of your drone The very first criterion for selection of right motor for your drone is to have clear idea about overall weight of drone itself. You can have approximate weight idea for your drone by simply calculating weight of its individual parts or components. But note that the list must include all parts like payload (if you are connecting gimbals and camera), battery unit, motors, wires, PDB, flight controller and frame of the device. Once you know the overall size of frame then it can help you to determine right propeller size. Whereas the idea about size and weight of propeller will help users to know about the overall thrust of motor that they will need for perfect lifting of drone during flights. Your decision will help to maintain speed of drone in air and this weight will also contribute in flight time adjustments. #### 2\. Thrust to weight ratio Do you know the golden rule for selection of drone motor? It must allow your drone to hover in the midair with half throttle. It clearly means that your selected motor must be capable enough to produce about 50 percent higher thrust as compared to multi rotor. This is a very essential parameter as it means your motor is going to have additional thrust to keep your drone safe during windy weather or at the time of flight maneuvers. Let us consider a situation: suppose your drone have overall weight of 650 grams then we need to pick a motor that can generate at least twice amount of thrust. Means thrust must range somewhere around 1360 Grams where each motor must be capable enough to produce 340 grams thrust. And in case if they are able to produce higher thrust then this rated value, your drone will naturally become able to move with much faster speed. #### 3\. Efficiency The formula used for calculation of motor efficiency is “thrust/power used in W”; its overall unit becomes g/W. now, if you have higher value of g/W rating that means your motor is more efficient and it will assist drone in longer flights. Professionals recommend choosing a motor that has efficiency value near about 7 or above this. There are chances that a motor could be efficient with its lower throttle range; in that case they will lose efficiency with increasing current range at higher limits. When you connect motors having low efficiency to your drone unit then you have to make lots of compromise for flight time as well as energy. It will also cause voltage sags for your batteries. Never forget to check thrust/current ratio while buying new motor for your drone. #### 4\. Torque The torque range helps to define the ability of motor to shift between RPM values. This change ultimately decides responsiveness of drone in air. If your motor has high torque value then it will naturally lead to snappy response as RPM will accept faster changes. It will also lead to lesser propeller wash. If you have high torque value for your motor then it means it is capable enough to run much heavier props but will also suck more current. In case if you try to fir a heavier propeller on low torque type motor, it will not be able to achieve the desired RPM value or will not be able to generate enough torque for spinning. Ultimately, it will end up making lower thrust while drawing lower current from system. However, there is one disadvantage of connection high torque type motors; that is, it generates more oscillations and they cannot be tuned so easily. Note that, high torque type motors are able to generate faster response rate so users can move between different RPM rating easily and efficiently. It may also amplify error and can cause oscillations even at yaw axis. #### 5\. Pole Count Next important consideration is motor pole count. You will generally find two options for this: first one if quadcopter motors that have higher pole count. These types of motors are able to produce greater torque value but at the same time it will demand more voltage for operation. Note that these motors are able to produce lower RPM. Professionals suggest choosing larger blades for such motors. If we talk about the second category, here you will find motors having lower pole count but they deliver higher RPM. Now, these motors will be accompanied by smaller blades and will serve with smaller lift from ground. If you want to get rid of additional gear box then it is essential to start with higher pole count. ## Part 2: Types of motors | Type | Definition | Application | Lifespan | Energy saving | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Brushed DC motor | Brushed DC motors possess a rotating armature that works like a electromagnet having two poles. A rotary switch is connected that helps to reverse current direction for every half cycle so that poles can be pushed or pulled against permanent magnets connected outside motor. | It is commonly used as a power tool for drones. | It can serve users up to 1000 hours or less. | In case of Brushed motor designs, you need to invest upon continuous maintenance for carbon crushes to ensure proper energy consumption and satisfactory operation. | | Brushless DC motor | Brushless DC Motors do not possess brushes, they just have a permanent magnet and it switched with electronic polarity changes. Its movements can be controlled via a dedicated electronic controller and speed feedback mechanism. | These motors are commonly used for drones that demand higher rotation speeds to manage flights. | Brushed DC motors are capable enough to work effectively up to more than 1000 hours | Brusheless motors are highly energy efficient as compared to brushed ones. | **Verdict:** If you are working on a project where motor is expected to be used for very less time, it is recommended to connect brushed DC motor as it will provide sufficient output with cost effectiveness. But in case if you need motors continuously or when your device is going to work on higher power rating then brushless motor will be best idea for long hour flights. ## 5 Best Recommendation for Drone Motors #### 1\. [Coolplay syma x5c-1 x5c x5 motors](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [coolplay syma x5c motors](https://images.wondershare.com/filmora/article-images/coolplay-syma-x5c-motors.jpg) ](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) [Check at Amazon](https://www.amazon.com/gp/product/B01AHQ76A8/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01AHQ76A8&linkId=1f876a249e703fb7564af2e5be99d103) **Price:** $8.99 only **Key Features:** * It is designed with brass metal gear that offers super stable performance with ultra high durability. * Their wire colour codes are same as that of original models so replacement task becomes much easier. * Overall performance is rated to be as high as stock motors. * This motor design is compatible with all Syma X models. **Pros:** * Lower Price range. * Great customer service * Ultra durable and super stable design. **Cons:** * Motors create annoying sound. #### 2\. [Hobbymate quadcopter kit motor](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [hobbymate quadcopter kit motor](https://images.wondershare.com/filmora/article-images/hobbymate-quadcopter-kit-motor.jpg) ](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) [Check at Amazon](https://www.amazon.com/gp/product/B01E56CUSO/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B01E56CUSO&linkId=1777f55f04a1112c2784cc366ed6b8c5) **Price:** $58 **Key Features:** * Best choice for FPV QAV quadcopters having 250, 210, 180 size range; and for small drones. * Impressive air suction system. * U clip added to protect loosening issue of bearing. * High precision type CNC machine exquisite design. **Pros:** * Rapid cooling system. * Longer battery life with higher efficiency. * Light weight design. * Offers longer flight time. * Lesser vibrations with low CG design. #### 3\. [Parrot AR Drone 2.0 motor](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [parrot ar drone 2.0 motor](https://images.wondershare.com/filmora/article-images/parrot-ar-drone-2.0-motor.jpg) ](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) [Check at Amazon](https://www.amazon.com/gp/product/B007HZLM9O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B007HZLM9O&linkId=75c1eaa60a0c0b656b99e3c9e17e5c0b) **Price:** $28.99b **Key Features:** * This motor possesses maximum power of 15 watts and can complete about 28000 rotations/minute in air. * Range of these motors begins at 10,350 RPM and it goes up to 41,400 RPM. * Speed of motor is controlled via a 8 bit low power type microcontroller accompanied with 10 bit ADC. **Pros:** * It is much easier to install. * Consumes less power, increased efficiency. * Secured with long and short screw connections. * Offers guaranteed high performance. **Cons:** * Expensive option. #### 4\. [Hobbypower A2212 brushless motor](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [hobbypower a2212 brushless motor](https://images.wondershare.com/filmora/article-images/hobbypower-a2212-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) [Check at Amazon](https://www.amazon.com/gp/product/B00E7LG85O/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00E7LG85O&linkId=fef6635822f1ff9413fcd086facb08eb) **Price:** $15.99 **Key Features:** * This brushless motor ensures service with KV value of 1000. * It comes with 30A advanced speed controller unit. * Can offer maximum speed of 2100000 RPM with 2 poles type BLM and about 70,000 RPM with 6 pole type **Pros:** * Price range is nominal. * It stays cool even during tough flights. * It adds more power to your RC drone unit. **Cons:** * Motor gets heated up within very less time. * It causes lots of vibrations during motor acceleration. #### 5\. [Emax Mt2213 brushless motor](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [emax mt2213 brushless motor](https://images.wondershare.com/filmora/article-images/emax-mt2213-brushless-motor.jpg) ](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) [Check at Amazon](https://www.amazon.com/gp/product/B00EDHXZSK/ref=as%5Fli%5Ftl?ie=UTF8&tag=vs-flora-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B00EDHXZSK&linkId=221cf30d5120e9a98a968a7371fe464c) **Price:** $68.25 **Key Features:** * Impressive multi rotor motor design. * Offers classic response performance. * Multi rotor options available like Octo, Hexa, Quad and Tri. * Maximum thrust goes up to 860G. **Pros:** * Easy to set up. * Solid design. * Balanced and smooth motors. **Cons:** * Too costly. * Maximum weight is 55 grams. ![author avatar](https://images.wondershare.com/filmora/article-images/max-wales-author.jpg) Max Wales Max Wales is a writer and a lover of all things video. Follow @Max Wales <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://extra-lessons.techidaily.com/hidden-methods-for-dodging-digital-study-vids/"><u>Hidden Methods for Dodging Digital Study Vids</u></a></li> <li><a href="https://extra-lessons.techidaily.com/a-novices-introduction-to-av1-codec/"><u>A Novice's Introduction to AV1 Codec</u></a></li> <li><a href="https://extra-lessons.techidaily.com/balance-quality-and-quickness-with-netflix-speed-modification-tips/"><u>Balance Quality & Quickness with Netflix Speed Modification Tips</u></a></li> <li><a href="https://extra-lessons.techidaily.com/updated-analyzing-investment-for-video-promotion/"><u>[Updated] Analyzing Investment for Video Promotion</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-ace-your-editing-skills-video-enhancer-v22-masterclass/"><u>In 2024, Ace Your Editing Skills Video Enhancer v2.2 Masterclass</u></a></li> <li><a href="https://extra-lessons.techidaily.com/optimal-5-displays-for-immersive-ps5-gaming/"><u>Optimal 5 Displays for Immersive PS5 Gaming</u></a></li> <li><a href="https://extra-lessons.techidaily.com/a-compilation-of-the-best-10-image-sharing-sites/"><u>A Compilation of the Best 10 Image Sharing Sites</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-behind-the-scenes-top-storytelling-channels-on-yt-2023/"><u>2024 Approved Behind-the-Scenes Top Storytelling Channels on YT, 2023</u></a></li> <li><a href="https://extra-lessons.techidaily.com/exclusive-offer-20-free-luts-just-for-dji-mini-and-air-users/"><u>Exclusive Offer 20 FREE LUTS Just for DJI Mini & Air Users</u></a></li> <li><a href="https://extra-lessons.techidaily.com/new-affordable-text-animation-strategies-webreal-world/"><u>[New] Affordable Text Animation Strategies Web/Real World</u></a></li> <li><a href="https://extra-lessons.techidaily.com/giggle-grid-curated-list-of-uproarious-ringtone-sites/"><u>Giggle Grid Curated List of Uproarious Ringtone Sites</u></a></li> <li><a href="https://extra-lessons.techidaily.com/zero-in-on-transparent-design-with-figmas-bg-removal/"><u>Zero In on Transparent Design with Figma's BG Removal</u></a></li> <li><a href="https://extra-lessons.techidaily.com/click-inducing-headline-whiz-for-2024/"><u>Click-Inducing Headline Whiz for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/new-boost-your-photo-skills-with-these-top-pixlr-tricks/"><u>[New] Boost Your Photo Skills with These Top Pixlr Tricks</u></a></li> <li><a href="https://extra-lessons.techidaily.com/top-10-techniques-optimal-live-cricket-broadcasting/"><u>Top 10 Techniques Optimal Live Cricket Broadcasting</u></a></li> <li><a href="https://extra-lessons.techidaily.com/combat-king-t5-vs-heavy-duty-sjcam-s6-showdown/"><u>Combat King T5 Vs Heavy Duty SJCAM S6 Showdown</u></a></li> <li><a href="https://extra-lessons.techidaily.com/discovering-the-best-audio-experiences-top-mac-apps-podcast-edition/"><u>Discovering the Best Audio Experiences Top Mac Apps (Podcast Edition)</u></a></li> <li><a href="https://extra-lessons.techidaily.com/unlocking-vr-advertising-potential/"><u>Unlocking VR Advertising Potential</u></a></li> <li><a href="https://extra-lessons.techidaily.com/action-videography-showdown-hero-5-black-or-km-170-for-2024/"><u>Action Videography Showdown Hero 5 Black or KM-170 for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/top-10-best-4k-gaming-laptops-for-2024/"><u>TOP 10 Best 4K Gaming Laptops for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/investigating-the-innovation-in-burst-mode-filming-techniques/"><u>Investigating the Innovation in Burst Mode Filming Techniques</u></a></li> <li><a href="https://extra-lessons.techidaily.com/digital-dazzle-vertical-panorama-magic-for-mobile/"><u>Digital Dazzle Vertical Panorama Magic for Mobile</u></a></li> <li><a href="https://extra-lessons.techidaily.com/crafting-stunning-visuals-how-to-master-use-of-luts-in-photoshop-suite-for-2024/"><u>Crafting Stunning Visuals How to Master Use of LUTs in Photoshop Suite for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/convert-talk-to-text-the-costless-alternative-for-2024/"><u>Convert Talk to Text The Costless Alternative for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-auditory-enhancements-adding-sound-effectively-powerpoint/"><u>2024 Approved Auditory Enhancements Adding Sound Effectively (PowerPoint)</u></a></li> <li><a href="https://extra-lessons.techidaily.com/from-novice-to-leader-mastering-social-media-marketing-smm-in-10-steps/"><u>From Novice to Leader Mastering Social Media Marketing (SMM) in 10 Steps</u></a></li> <li><a href="https://extra-lessons.techidaily.com/ultimate-list-of-3d-typographic-sites/"><u>Ultimate List of 3D Typographic Sites</u></a></li> <li><a href="https://extra-lessons.techidaily.com/a-comprehensible-approach-to-adding-dates-on-youtube-videos-for-2024/"><u>A Comprehensible Approach to Adding Dates on YouTube Videos for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/crafting-visual-dynamics-illustrator-motion-blur-tips-for-2024/"><u>Crafting Visual Dynamics Illustrator Motion Blur Tips for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/utilizing-tailored-volume-reduction-in-audacity/"><u>Utilizing Tailored Volume Reduction in Audacity</u></a></li> <li><a href="https://extra-lessons.techidaily.com/copyright-free-meditation-music-download/"><u>Copyright-Free Meditation Music Download</u></a></li> <li><a href="https://extra-lessons.techidaily.com/camera-elevation-best-tripods-for-smartphone-shots-for-2024/"><u>Camera Elevation Best Tripods for Smartphone Shots for 2024</u></a></li> <li><a href="https://screen-activity-recording.techidaily.com/updated-in-2024-wincams-capturing-life-at-your-fingertips/"><u>[Updated] In 2024, WinCams Capturing Life at Your Fingertips</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-4-ways-to-sync-contacts-from-apple-iphone-6s-to-ipad-easily-drfone-by-drfone-transfer-from-ios/"><u>In 2024, 4 Ways to Sync Contacts from Apple iPhone 6s to iPad Easily | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/preparation-to-beat-giovani-in-pokemon-go-for-oneplus-nord-n30-5g-drfone-by-drfone-virtual-android/"><u>Preparation to Beat Giovani in Pokemon Go For OnePlus Nord N30 5G | Dr.fone</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-the-complete-blueprint-integrating-real-time-video-on-sites/"><u>[New] The Complete Blueprint Integrating Real-Time Video on Sites</u></a></li> <li><a href="https://android-transfer.techidaily.com/how-to-transfer-photos-from-asus-rog-phone-8-to-laptop-without-usb-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Photos from Asus ROG Phone 8 to Laptop Without USB | Dr.fone</u></a></li> <li><a href="https://tiktok-video-recordings.techidaily.com/updated-capture-stellar-tiktoks-easily-and-effectively/"><u>[Updated] Capture Stellar TikToks Easily & Effectively</u></a></li> <li><a href="https://review-topics.techidaily.com/in-2024-3-things-you-must-know-about-fake-snapchat-location-on-itel-p55-drfone-by-drfone-virtual-android/"><u>In 2024, 3 Things You Must Know about Fake Snapchat Location On Itel P55 | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/tutorial-to-change-asus-rog-phone-7-imei-without-root-a-comprehensive-guide-by-drfone-android/"><u>Tutorial to Change Asus ROG Phone 7 IMEI without Root A Comprehensive Guide</u></a></li> <li><a href="https://screen-activity-recording.techidaily.com/new-in-2024-unleash-retro-game-delights-with-the-leading-android-tools-for-ps2-titles/"><u>[New] In 2024, Unleash Retro Game Delights with the Leading Android Tools for PS2 Titles</u></a></li> <li><a href="https://ios-unlock.techidaily.com/everything-you-need-to-know-about-unlocked-apple-iphone-6-by-drfone-ios/"><u>Everything You Need To Know About Unlocked Apple iPhone 6</u></a></li> <li><a href="https://android-location.techidaily.com/easy-ways-to-manage-your-infinix-smart-8-pro-location-settings-drfone-by-drfone-virtual/"><u>Easy Ways to Manage Your Infinix Smart 8 Pro Location Settings | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/how-to-stream-anything-from-xiaomi-redmi-note-12t-pro-to-apple-tv-drfone-by-drfone-android/"><u>How To Stream Anything From Xiaomi Redmi Note 12T Pro to Apple TV | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-remove-passcode-from-apple-iphone-15-complete-guide-drfone-by-drfone-ios/"><u>In 2024, How To Remove Passcode From Apple iPhone 15? Complete Guide | Dr.fone</u></a></li> <li><a href="https://facebook-video-content.techidaily.com/in-2024-top-tools-for-social-media-marketers-20-free-fb-video-editors/"><u>In 2024, Top Tools for Social Media Marketers 20 Free FB Video Editors</u></a></li> <li><a href="https://blog-min.techidaily.com/5-techniques-to-transfer-data-from-poco-c50-to-iphone-15141312-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>5 Techniques to Transfer Data from Poco C50 to iPhone 15/14/13/12 | Dr.fone</u></a></li> <li><a href="https://video-screen-grab.techidaily.com/in-2024-the-verdict-on-screen-recording-does-obs-surpass-fraps/"><u>In 2024, The Verdict on Screen Recording Does OBS Surpass Fraps?</u></a></li> <li><a href="https://sound-tweaking.techidaily.com/new-2024-approved-disabling-background-chatter-in-tiktok-videos-three-streamlined-techniques/"><u>New 2024 Approved Disabling Background Chatter in TikTok Videos Three Streamlined Techniques</u></a></li> <li><a href="https://facebook-videos.techidaily.com/updated-mastering-facebook-vids-the-top-20-marketing-hacks/"><u>[Updated] Mastering Facebook Vids The Top 20 Marketing Hacks</u></a></li> <li><a href="https://twitter-clips.techidaily.com/new-tweet-centric-viewing-twitters-top-content/"><u>[New] Tweet-Centric Viewing Twitter’s Top Content</u></a></li> <li><a href="https://instagram-video-recordings.techidaily.com/updated-fine-tune-video-quality-for-instagram-excellence/"><u>[Updated] Fine-Tune Video Quality for Instagram Excellence</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-ditch-the-limits-installing-linux-on-your-chromebook-updated-2023-for-2024/"><u>Updated Ditch the Limits Installing Linux on Your Chromebook (Updated 2023) for 2024</u></a></li> <li><a href="https://instagram-video-recordings.techidaily.com/updated-secretive-approach-to-watching-insta-stories/"><u>[Updated] Secretive Approach to Watching Insta-Stories</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/updated-in-2024-10-catchy-pixel-art-wallpapers-and-how-to-custom-your-own/"><u>Updated In 2024, 10 Catchy Pixel Art Wallpapers and How to Custom Your Own</u></a></li> <li><a href="https://fix-guide.techidaily.com/reasons-for-oneplus-11-5g-stuck-on-startup-screen-and-ways-to-fix-them-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Reasons for OnePlus 11 5G Stuck on Startup Screen and Ways To Fix Them | Dr.fone</u></a></li> </ul></div>
### 解题思路 1、核心思想还是找到中间近似值 2、链表采用双指针去取中间值 慢指针走1布 快指针走2布,快指针走到尾部的时候,慢指针走到中间 3、$tmp 是为了保存中间值前一位也就是左子树 4、$tmp->next = null 是为了只截取链表的左子树 5、$slow_ptr->next 是右子树 ### 代码 ```php /** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val) { $this->val = $val; } * } */ /** * Definition for a binary tree node. * class TreeNode { * public $val = null; * public $left = null; * public $right = null; * function __construct($value) { $this->val = $value; } * } */ class Solution { /** * @param ListNode $head * @return TreeNode */ function sortedListToBST($head) { //终止条件 if ($head ==null) return null; if ($head->next ==null) return new TreeNode($head->val); $slow_ptr = $head;//慢指针 $fast_ptr = $head;//快指针 $temp = null; while ($fast_ptr!=null && $fast_ptr->next!=null) { $fast_ptr = $fast_ptr->next->next; $tmp = $slow_ptr; $slow_ptr = $slow_ptr->next; } $left = $head; $right = $slow_ptr->next;//右子树链表 $tmp->next = null;//链表中间位左边一位设为null,此时head 只剩左子树链表 $root = new TreeNode($slow_ptr->val); $root->left = $this->sortedListToBST($left); $root->right = $this->sortedListToBST($right); return $root; } } ```
import { Vector2 } from "../math/Vector2"; import { Rect } from "../math/Rect"; import { GameState } from "./update/states"; export interface Field { rect: Rect; } export interface Goal { team: "red" | "blue"; rect: Rect; center: Vector2; } export interface Player { id: string; team: "red" | "blue"; isGoalkeeper: boolean; canStart: boolean; position: Vector2; animation: { isStationary: boolean; lastPosition: Vector2; direction: 1 | -1; leftLeg: { rotation: number; angularVelocity: number; isStraight: boolean; }; rightLeg: { rotation: number; angularVelocity: number; isStraight: boolean; }; }; defensivePosition: Vector2; offensivePosition: Vector2; speed: number; baseSpeed: number; control: number; baseControl: number; controlRadius: number; accuracy: number; baseAccuracy: number; } export interface Fan { id: string; sector: Sector; position: Vector2; animation: { progress: number; position: Vector2; intensity: number; }; } export interface Sector { id: 1 | 2 | 3 | 4 | 5 | 6; isCheering: boolean; isBooing: boolean; energyRegeneration: number; baseEnergyRegeneration: number; energy: number; fanArea: Rect; playerArea: Rect; displayArea: Rect; fans: Fan[]; } export interface Ball { position: Vector2; velocity: Vector2; rotation: number; owner?: Player; lastTouchedBy: "red" | "blue"; } export interface World { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; gameState: GameState; ball: Ball; field: Field; goals: Goal[]; players: Player[]; fans: Fan[]; sectors: Sector[]; startingTeam: "red" | "blue"; leftTeam: "red" | "blue"; switchedSides: boolean; gameOver: boolean; scores: { red: number; blue: number; }; time: { gameTime: number; paused: boolean; }; banner: { image?: | "blue-goal" | "blue-out" | "red-goal" | "red-out" | "half-time" | "gmtk" | "you-win" | "you-lose"; timeLeft: number; }; ui: { leftTeam?: "red" | "blue"; scores: [number, number]; leftTeamName: HTMLElement; leftTeamScore: HTMLElement; timer: HTMLElement; rightTeamName: HTMLElement; rightTeamScore: HTMLElement; }; }