text
stringlengths
184
4.48M
import React from "react"; import { IMG_URL, MOVIE_DETAIL_URL, options } from "../../../app/constants"; import styles from "./movie-info.module.scss"; import MovieCredits from "./movie-credits"; import Image from "next/image"; import getBase64 from "../../../utils/getBase64"; import LikeButton from "../../likes/like-button"; export const getMovie = async ({ id, type }: { id: string; type: string }) => { const response = await fetch( `${MOVIE_DETAIL_URL}/${type}/${id}?append_to_response=credits&language=ko`, options ); return response.json(); }; export default async function MovieInfo({ id, type, query }) { const movie = await getMovie({ id, type }); const { title, poster_path, name, overview, homepage, vote_average, release_date, runtime, genres, credits, created_by, first_air_date, } = movie; let res = { width: 0, height: 0, base64: "" }; if (poster_path) { res = await getBase64(`${IMG_URL}${poster_path}`); } return ( <div className={styles.container}> {poster_path ? ( <Image className={styles.poster} src={`${IMG_URL}${poster_path}`} alt={title || name} priority={true} width={res.width} height={res.height} sizes='500px' placeholder='blur' blurDataURL={res.base64} /> ) : ( <div className={styles.noImage}>no image</div> )} <div className={styles.info}> <div className={styles.titleBox}> <h1 className={styles.title}>{title || name} </h1> <LikeButton movieId={id} type={type} query={query} /> </div> <div className={styles.genres}> {genres.map((genre, idx) => { return ( <React.Fragment key={idx}> <div className={styles.text} key={genre.id}> {genre.name} </div> {idx !== genres.length - 1 && <span>{" ・ "}</span>} </React.Fragment> ); })} </div> <div className={styles.description}> {vote_average > 0 && ( <> <h3>⭐️{vote_average.toFixed(1)}</h3> <span>|</span> </> )} {release_date ? ( <> <h3>{release_date}</h3> <span>|</span> <h3>{runtime}분</h3> </> ) : ( <> <h3>{first_air_date}</h3> {created_by && created_by[0] && ( <> <span>|</span> <h3>감독 {created_by[0]?.original_name}</h3> </> )} </> )} </div> <div className={styles.overview}>{overview}</div> {homepage && ( <a href={homepage} target={"_blank"}> website </a> )} {credits && <MovieCredits credits={credits} />} </div> <Image className={styles.blurredBg} src={`${IMG_URL}${poster_path}`} alt={title} fill priority={false} sizes='300px' /> </div> ); }
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import KMeans import streamlit as st # Membaca data dari file CSV df = pd.read_csv('Mall_Customers.csv') # Mengganti nama kolom untuk kemudahan df.rename(columns={'Annual Income (k$)': 'Income', 'Spending Score (1-100)': 'Score'}, inplace=True) # Memilih kolom yang relevan X = df[['Income', 'Score']] # Judul dan tampilan data pada Streamlit st.title("Visualisasi KMeans Clustering") st.write("Data yang digunakan:") st.dataframe(X.style.highlight_max(axis=0)) # Inisialisasi list untuk menyimpan inertia dari KMeans cluster = [] # Menghitung inertia untuk berbagai jumlah cluster for i in range(1,11): km = KMeans(n_clusters = i).fit(X) cluster.append(km.inertia_) # Membuat plot untuk menemukan elbow fig, ax = plt.subplots(figsize=(10,6)) sns.lineplot(x=list(range(1,11)), y=cluster, ax=ax) ax.set_title('Elbow Method untuk Menentukan Jumlah Cluster yang Optimal') ax.set_xlabel('Jumlah Cluster') ax.set_ylabel('Inertia') # Menambahkan penjelasan pada elbow elbow_point1 = 3 # Nilai elbow pertama elbow_value1 = cluster[elbow_point1-1] ax.annotate('Elbow 1', xy=(elbow_point1, elbow_value1), xytext=(elbow_point1+1, elbow_value1+50), arrowprops=dict(facecolor='red', shrink=0.05)) elbow_point2 = 5 # Nilai elbow kedua elbow_value2 = cluster[elbow_point2-1] ax.annotate('Elbow 2', xy=(elbow_point2, elbow_value2), xytext=(elbow_point2+1, elbow_value2+50), arrowprops=dict(facecolor='blue', shrink=0.05)) # Menampilkan plot pada Streamlit st.pyplot(fig) # Sidebar untuk input pengguna st.sidebar.subheader("Pengaturan Cluster") clust = st.sidebar.slider("Pilih jumlah cluster:", 1, 10, 3) # Fungsi untuk melakukan KMeans clustering dan menampilkan hasilnya def K_means(n_clust): kmean = KMeans(n_clusters=n_clust).fit(X) X['cluster'] = kmean.labels_ fig, ax = plt.subplots(figsize=(10,8)) sns.scatterplot(data=X, x='Income', y='Score', hue='cluster', style='cluster', sizes=(100, 200), palette=sns.color_palette('hls', n_clust), ax=ax) # Menambahkan label pada centroid for label in X['cluster'].unique(): ax.annotate(label, (X[X['cluster'] == label]['Income'].mean(), X[X['cluster'] == label]['Score'].mean()), horizontalalignment='center', verticalalignment='center', size=20, weight='bold', color='black') st.header("Hasil KMeans Clustering") st.pyplot(fig) st.write("Data dengan label cluster:") st.dataframe(X.style.applymap(lambda x: 'background-color : yellow' if x in X['cluster'].unique() else '')) # Memanggil fungsi KMeans dengan jumlah cluster yang dipilih pengguna K_means(clust)
import mock_catalyst #@UnusedImport from vocollect_core_test.base_test_case import BaseTestCaseCore from vocollect_core.scanning import ScanMode from vocollect_core.dialog.float_prompt import FloatPromptExecutor from vocollect_core.utilities import util_methods, class_factory, obj_factory from vocollect_core.dialog.functions import prompt_float def override_catalyst_multi(): # test multi hints return 2.0 class TestFloatPrompt(BaseTestCaseCore): def setUp(self): # save off original catalyst_version function self._original_catalyst_function = util_methods.catalyst_version # replace function with multi hint version util_methods.catalyst_version = override_catalyst_multi from vocollect_core.utilities.localization import itext itext('') from vocollect_core.utilities.localization import _resources _resources["generic.wrong.scan"] = "Wrong scan" def tearDown(self): # replace function with original version util_methods.catalyst_version = self._original_catalyst_function def test_prompt_float(self): ''' tests from 1.3.0's test_digits_dialogs ''' #----------------------------------------------------------- #test normal entry with decimal places specified, #time out when not enough decimal places entered, no to confirm, #then yes to confirm self.post_dialog_responses('15.1!', '23.45', 'no', '67.89', 'yes') result = prompt_float('Enter value', 'Enter value with 2 decimal places', 2, True, False) self.assertEqual(result, '67.89') self.validate_prompts('Enter value', '15.1 re enter', '<spell>23.45</spell>, correct?', 'Enter value', '<spell>67.89</spell>, correct?') #----------------------------------------------------------- #test normal entry with no decimal places specified self.post_dialog_responses('15.1!', '2345', 'ready', 'yes') result = prompt_float('Enter value', 'Enter value with 2 decimal places', 0, True, False) self.assertEqual(result, '15.12345') # ignored timeout self.validate_prompts('Enter value', '<spell>15.12345</spell>, correct?') #----------------------------------------------------------- #test scanning #scanned value self.post_dialog_responses('#123456789') result, scanned = prompt_float('Enter value', 'Enter value with 2 decimal places', 2, True, True) self.assertEqual(result, '123456789') self.assertEqual(scanned, True) self.validate_prompts('Enter value') #spoken value self.post_dialog_responses('1234567.89', 'yes') result, scanned = prompt_float('Enter value', 'Enter value with 2 decimal places', 2, True, True, max_value = None) self.assertEqual(result, '1234567.89') self.assertEqual(scanned, False) self.validate_prompts('Enter value', '<spell>1234567.89</spell>, correct?') def test_help(self): #----------------------------------------------------------- #test help message self.post_dialog_responses('15.1!', 'talkman help', '2345', 'ready', 'yes') result = prompt_float('Enter value', 'Enter value then ready', 0, True, False) self.assertEqual(result, '15.12345') #ignored timeout self.validate_prompts('Enter value', 'Enter value then ready,, You entered 1 5 . 1 so far', 'Enter value', '<spell>15.12345</spell>, correct?') entry = '15.12345' current = '' dialog_responses = [] prompts = [['Enter value', True]] for c in entry: current += c dialog_responses.append(c + '!') dialog_responses.append('talkman help') prompts.append(['Enter value then ready,, You entered ' + ' '.join(current) + ' so far', False]) prompts.append(['Enter value', False]) dialog_responses.append('ready') dialog_responses.append('yes') prompts.append(['<spell>' + entry + '</spell>, correct?', False]) self.post_dialog_responses(*dialog_responses) result = prompt_float('Enter value', 'Enter value then ready', 0, True, False) self.assertEqual(result, entry) self.validate_prompts(*prompts) def test_range(self): # test min and max values executor, _ = get_test_objects(decimal_places = None, min_value = '3.0', max_value = '4.0') self.post_dialog_responses("1.5", "4.5", "3.5", "yes") result = executor.get_results() self.assertEqual(result, "3.5") self.validate_prompts(["Prompt", True], ["1.5 re enter", False], ["4.5 re enter", False], ["Prompt", False], ["<spell>3.5</spell>, correct?", False]) # test min and max range equivalent executor, _ = get_test_objects(min_value = '3.0', max_value = '3.00') self.post_dialog_responses("3.1!", "3.01", "3.00", "yes") result = executor.get_results() self.assertEqual("3.00", result) self.validate_prompts(["Prompt", True], ["3.1 re enter", False], ["3.01 re enter", False], ["Prompt", False], ["<spell>3.00</spell>, correct?", False]) def test_custom_decimal_point(self): self.post_dialog_responses("15,25!", "yes") result = prompt_float_comma("Prompt", "Speak a value", decimal_places = None) self.assertEqual("15,25", result) self.validate_prompts(["Prompt", True], ["<spell>15,25</spell>, correct?", False]) def test_feedback_length(self): # feedback length of 2 which handles insertions but still provides reasonable feedback self.post_dialog_responses("1!", "15!", "15.!", "15.1!", "yes") result = prompt_float("Prompt", "Speak a value", decimal_places = None, min_value = "0.0", max_value = "99.9") self.assertEqual(result, "15.1") self.validate_prompts(["Prompt", True], # "1" treated as insertion ["15 re enter", False], ["15. re enter", False], ["Prompt", False], ["<spell>15.1</spell>, correct?", False]) # feedback length of 1 self.post_dialog_responses("1!", "15!", "15.!", "15.1!", "yes") result = prompt_float_feedback("Prompt", "Speak a value", decimal_places = None, min_value = "0.0", max_value = "99.9") self.assertEqual(result, "15.1") self.validate_prompts(["Prompt", True], ["1 re enter", False], # insertion reported as wrong ["15 re enter", False], ["Prompt", False], ["15. re enter", False], ["<spell>15.1</spell>, correct?", False]) # feedback length of 4 with total min length > 4 self.post_dialog_responses("1.1!", "15.1!", "135.531", "yes") result = prompt_float_quiet("Prompt", "Speak a value", decimal_places = None, min_value = "000.000", max_value = "999.999") self.assertEqual(result, "135.531") self.validate_prompts(["Prompt", True], ["15.1 re enter", False], ["<spell>135.531</spell>, correct?", False]) # feedback length of 4 with total min length < 4 self.post_dialog_responses("1.1!", "yes") result = prompt_float_quiet("Prompt", "Speak a value", decimal_places = None, min_value = "0.0", max_value = "9.99") self.assertEqual(result, "1.1") self.validate_prompts(["Prompt", True], ["<spell>1.1</spell>, correct?", False]) def get_test_objects(prompt = "Prompt", priority_prompt = True, help_message = "Help", decimal_places = 2, additional_vocab = {}, confirm=True, scan=ScanMode.Off, skip_prompt = False, hints = None, anchor_words = None, min_value = None, max_value = None): ''' retrieves an executor and dialog ''' executor = FloatPromptExecutor(prompt, priority_prompt, help_message, decimal_places, additional_vocab, confirm,scan,skip_prompt, hints, anchor_words, min_value, max_value) return executor, executor.dialog # testing ',' as decimal point char class CommaFloatPromptExecutor(class_factory.get(FloatPromptExecutor)): def _configure_dialog(self): self.dialog.decimal_point_char = ',' super()._configure_dialog() def prompt_float_comma(prompt, help_message, decimal_places = 2, confirm = True, scan = ScanMode.Off, additional_vocab = {}, skip_prompt = False, priority_prompt = True, hints = None, min_value = '0,0', max_value = '9999,99'): # Note: min_value and max_value must use decimal_point_char executor = obj_factory.get(CommaFloatPromptExecutor, prompt=prompt, priority_prompt=priority_prompt, help_message=help, decimal_places=decimal_places, additional_vocab=additional_vocab, confirm=confirm, scan=scan, skip_prompt=skip_prompt, hints=hints, min_value=min_value, max_value=max_value) return executor.get_results() # testing feedback after every recognition which does not handle insertions gracefully class FeedbackFloatPromptExecutor(class_factory.get(FloatPromptExecutor)): def _configure_dialog(self): self.dialog.min_feedback_length = 1 super()._configure_dialog() def prompt_float_feedback(prompt, help_message, decimal_places = 2, confirm = True, scan = ScanMode.Off, additional_vocab = {}, skip_prompt = False, priority_prompt = True, hints = None, min_value = '0.0', max_value = '9999.99'): executor = obj_factory.get(FeedbackFloatPromptExecutor, prompt=prompt, priority_prompt=priority_prompt, help_message=help, decimal_places=decimal_places, additional_vocab=additional_vocab, confirm=confirm, scan=scan, skip_prompt=skip_prompt, hints=hints, min_value=min_value, max_value=max_value) return executor.get_results() # testing too large min_feedback_length class QuietFloatPromptExecutor(class_factory.get(FloatPromptExecutor)): def _configure_dialog(self): self.dialog.min_feedback_length = 4 super()._configure_dialog() def prompt_float_quiet(prompt, help_message, decimal_places = 2, confirm = True, scan = ScanMode.Off, additional_vocab = {}, skip_prompt = False, priority_prompt = True, hints = None, min_value = '0.0', max_value = '9999.99'): executor = obj_factory.get(QuietFloatPromptExecutor, prompt=prompt, priority_prompt=priority_prompt, help_message=help, decimal_places=decimal_places, additional_vocab=additional_vocab, confirm=confirm, scan=scan, skip_prompt=skip_prompt, hints=hints, min_value=min_value, max_value=max_value) return executor.get_results()
import random from higher_lower_data import data from higher_lower_art import logo, vs def format_data(account): """ Takes the account data into printable format """ account_name = account["name"] account_descr = account["description"] account_country = account["country"] return f"{account_name}, a {account_descr}, from {account_country}" def check_answer(guess, a_followers, b_followers): """ Take the user guess and follower counts and returns if they got it right """ if a_followers > b_followers: return guess == "a" else: return guess == "b" # Display art print(logo) score = 0 game_should_continue = True account_b = random.choice(data) while game_should_continue: # Generate a random account from the game data # Making account at position B become the next account at position A account_a = account_b account_b = random.choice(data) # in case there's a duplicate while account_a == account_b: account_b = random.choice(data) print(f"Compare A: {format_data(account_a)}") print(vs) print(f"Compare B: {format_data(account_b)}") # Ask user for a guess guess = input("Who has more followers? Type 'A' or 'B': ").lower() # Check if user is correct ## Get follower count of each account ## User if statement to check if user is correct a_follower_count = account_a["follower_count"] b_follower_count = account_b["follower_count"] is_correct = check_answer(guess, a_follower_count, b_follower_count) # Give user feedback on their guesses # Score keeping if is_correct: score += 1 print(f"You're right! Current score: {score}") else: game_should_continue = False print(f"Sorry, that's wrong. Final score: {score}")
import { render, RenderResult, screen, fireEvent } from '@testing-library/react' import ActionButton, { ActionButtonProps } from '../ActionButton' describe('ActionButton', () => { const getProps = (): ActionButtonProps => ({ text: 'ANY_BUTTON_TEXT', onClick: jest.fn(), }) const renderActionButton = (props = getProps()): RenderResult => { return render(<ActionButton {...props} />) } it('Deve desenhar o componente corretamente', () => { renderActionButton() expect(document.body).toMatchSnapshot() }) it('Deve chamar o onClick ao clicar no botão', () => { const props = getProps() renderActionButton(props) const button = screen.getByRole('button') fireEvent.click(button) expect(props.onClick).toHaveBeenCalled() }) })
<template> <div> <!-- <h1 class="header">通过您的ID登录</h1> <div id="hiddenContainer1" style="display:none;"></div> --> <div> <el-form label-width="100px" style="max-width: 460px;position: relative;margin: auto;"> <el-form-item label="账号" > <el-input type="tel" v-model="loginUsername" placeholder="请输入账号" required/> </el-form-item> <el-form-item label="密码"> <el-input type="password" show-password v-model="loginPassword" placeholder="请输入密码" required/> </el-form-item> <div class="submit-button" style="max-width: 120px;margin: auto;"> <el-button type="default" round="true" :icon="Pointer" @click="login_id">提交</el-button> </div> </el-form> </div> </div> </template> <script lang="ts" setup> import axios from 'axios'; import {ref} from 'vue'; //import { useRouter } from 'vue-router'; import { Pointer } from '@element-plus/icons-vue' import { ElMessage,ElMessageBox } from 'element-plus'; import type {Action} from 'element-plus'; import { useRouter } from 'vue-router'; const loginUsername=ref('') const loginPassword=ref('') const router = useRouter(); //const router=useRouter() const user_id = ref(); const login_id = async ()=> { axios.get('http://localhost:8084/api/user/login?USERNAME='+loginUsername.value+'&PASSWORD='+loginPassword.value) .then(response => { // console.log('Request URL:', response.config.baseURL + response.config.url); console.log("username",loginUsername.value); console.log(response.data); if(response.data.message==='该用户已经被封禁') { console.log('blocked.'); sessionStorage.setItem("user_id",response.data.user_ID ); router.push({ path:'/BlockUserPage', }); } else if(response.data.message==='success'){ /*------------------------*/ /*登录成功后编辑此处跳转界面*/ /*------------------------*/ if (response.data.role=='1'){ //sessionStorage.removeItem("soc_id"); sessionStorage.removeItem("username"); sessionStorage.removeItem("user_role"); sessionStorage.setItem("username", loginUsername.value); sessionStorage.setItem("user_role", response.data.role); sessionStorage.setItem("socId", response.data.id); router.push({ path:'/society' }); } else if (response.data.role=='0'){ //sessionStorage.removeItem("sto_id"); sessionStorage.removeItem("username"); sessionStorage.removeItem("user_role"); sessionStorage.setItem("username", loginUsername.value); sessionStorage.setItem("user_role", response.data.role); sessionStorage.setItem("stuId", response.data.id); console.log("loginUsername.value:"+loginUsername.value) /*获取用户账号*/ user_id.value = response.data.user_ID; router.push({ path:'/home' }); // 确保 fetchLocationData 完成后再进行页面跳转 // fetchLocationData() // .then(() => { // router.push({ // path: '/home', // }); // }) // .catch((error) => { // console.error('Fetch location data failed:', error); // }); } else if (response.data.role == '2') { sessionStorage.removeItem("username"); sessionStorage.removeItem("user_role"); sessionStorage.setItem("username", loginUsername.value); sessionStorage.setItem("user_role", response.data.role); router.push({ path:'/administrator' }); } } else { ElMessageBox.alert(response.data.message, '登录失败', { confirmButtonText: 'OK', callback: (action: Action) => { ElMessage({ type: 'info', message: `action: ${action}`, }) }, }) } }) .catch((error) => { console.log('An error occurred:', error); }); }; </script> <style scoped> .total-layout{ display: flex; flex-direction:column; } .form-layout{ display: flex; justify-content: center; } .header{ display: flex; justify-content: center; align-items: center; } .submit-button{ display: flex; /*width: 90px; /*justify-content: center;*/ } #hiddenContainer1 { display: none; } </style>
/* * Nightfall - Real-time strategy game * * Copyright (c) 2008 Marcus Klang, Alexander Toresson and Leonard Wickmark * * This file is part of Nightfall. * * Nightfall is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Nightfall is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Nightfall. If not, see <http://www.gnu.org/licenses/>. */ #include "gamewindow.h" #include "dimension.h" #include "font.h" #include "aibase.h" #include "vector3d.h" #include "terrain.h" #include "audio.h" #include "unit.h" #include "environment.h" #include "console.h" #include "gamegui.h" #include "networking.h" #include "textures.h" #include "aipathfinding.h" #include "camera.h" #include "unitrender.h" #include "scenegraph.h" #include "ogrexmlmodel.h" #include "game.h" #include <iostream> #include <fstream> #include <cmath> #include <cassert> #include <sstream> using namespace Window::GUI; using namespace std; namespace Game { namespace Rules { GameWindow* GameWindow::pInstance = NULL; GameWindow* GameWindow::Instance() { if (GameWindow::pInstance == NULL) GameWindow::pInstance = new GameWindow; return GameWindow::pInstance; } bool GameWindow::IsNull() { if (GameWindow::pInstance == NULL) return true; return false; } void GameWindow::Destroy() { if (GameWindow::pInstance == NULL) return; delete GameWindow::pInstance; GameWindow::pInstance = NULL; } Window::GUI::ConsoleBuffer* GameWindow::GetConsoleBuffer() const { return pConsole; } //New GUI Code int GameMain() { GameMenu *pMenu = new GameMenu(); GameInGameMenu *pInGameMenu = new GameInGameMenu(); SwitchState nextState = startState; GameWindow *mainWindow = NULL; //GameTest *mainTestin = new GameTest(); NetworkJoinOrCreate *multiplayer = new NetworkJoinOrCreate(); NetworkJoin *networkJoin = new NetworkJoin(); NetworkCreate *networkCreate = new NetworkCreate(); while(nextState != QUIT) { switch(nextState) { case MENU: { Audio::PlayList("menu"); nextState = (SwitchState)pMenu->RunLoop(); Audio::StopAll(); break; } case NEWGAME: { if (CurGame::New()->StartGame() == SUCCESS) { nextState = GAME; } else { nextState = QUIT; } break; } case LOADGAME: { if (CurGame::New()->StartGame("save.xml") == SUCCESS) { nextState = GAME; } else { nextState = QUIT; } break; } case ENDGAME: { CurGame::Instance()->EndGame(); nextState = MENU; break; } case GAME: { Audio::PlayList("ingame"); mainWindow = GameWindow::Instance(); nextState = (SwitchState)mainWindow->RunLoop(); Audio::StopAll(); break; } case INGAMEMENU: { Audio::PlayList("menu"); nextState = (SwitchState)pInGameMenu->RunLoop(); Audio::StopAll(); break; } case MULTIPLAYER: { Networking::isNetworked = true; nextState = (SwitchState)multiplayer->RunLoop(); if(nextState == MENU) Networking::isNetworked = false; break; } case NETWORKCREATE: { Networking::isNetworked = true; if (CurGame::New()->StartGame("", true, Networking::SERVER) == SUCCESS) { nextState = (SwitchState)networkCreate->RunLoop(); } else { nextState = QUIT; } break; } case NETWORKJOIN: { Networking::isNetworked = true; if (Networking::StartNetwork(Networking::CLIENT) == SUCCESS) { nextState = (SwitchState)networkJoin->RunLoop(); } else { nextState = QUIT; } break; } default: { nextState = QUIT; break; } } } GameWindow::Destroy(); delete pMenu; return SUCCESS; } void WaitForNetwork() { Window::GUI::LoadWindow *pLoading = new Window::GUI::LoadWindow(1.0f); pLoading->SetMessage(_("Awaiting network...")); pLoading->SetProgress(0.0f); float counter = 0.0f; while(Networking::isReadyToStart == false) { Networking::PerformPregameNetworking(); counter += 0.05f; if(counter > 1.0f) counter = 0.0f; pLoading->SetProgress(counter); pLoading->Update(); SDL_Delay(16); } delete pLoading; } GameWindow::GameWindow() { frames = 0; last_status_time = 0; start_drag_x = 0; start_drag_y = 0; end_drag_x = 0; end_drag_y = 0; is_pressing_lmb = false; goto_x = 0.0f; goto_y = 0.0f; build_x = -1; build_y = -1; goto_time = 0; buildingUnit = NULL; pGameInput = NULL; renderMutex = SDL_CreateMutex(); renderMutex2 = SDL_CreateMutex(); pauseRendering = false; InitGUI(); } int GameWindow::InitGUI() { // float increment = 0.1f / 3.0f; //0.1 (10%) divided on 1 update; //Initate Panel and place GameInput pMainGame = new Window::GUI::Panel(); pGameInput = new GameInput(this); SetPanel(pMainGame); float sizes[2] = {0.04f, 0.2f}; pConsole = new Window::GUI::ConsoleBuffer(); consoleID = pMainGame->Add(pConsole); pMainGame->SetConstraintPercent(consoleID, 0.0f, 0.0f, 1.0f, 1.0f); pMainGame->SetVisible(consoleID, false); int mainWidget = pMainGame->Add(pGameInput); pMainGame->SetConstraintPercent(mainWidget, 0.0f, sizes[0], 1.0f, 1.0f - sizes[0] - sizes[1]); pMainGame->SetFocus(mainWidget); pMainGame->SetFocusEnabled(false); pTopBar = new GameTopBar(); pPlayBar = new GamePlayBar(this); int topBar = pMainGame->Add(pTopBar); pMainGame->SetConstraintPercent(topBar, 0.0f, 0.0f, 1.0f, sizes[0]); p_lblMoney = new Window::GUI::InfoLabel(); p_lblMoney->AttachHandler(&GetMoney); p_lblMoney->SetTooltip(_("Resource: Money")); p_lblPower = new Window::GUI::InfoLabel(); p_lblPower->AttachHandler(&GetPower); p_lblPower->SetTooltip(_("Resource: Power")); p_lblTime = new Window::GUI::InfoLabel(); p_lblTime->AttachHandler(&GetTime); p_lblTime->SetTooltip(_("Time")); sell = new Window::GUI::TextButton(); sell->SetText(_("Sell")); sell->AttachHandler(&Sell); sell->SetTag(this); sell->SetType(1); int lblmoney = pTopBar->Add(p_lblMoney); int lblpower = pTopBar->Add(p_lblPower); int lbltime = pTopBar->Add(p_lblTime); int sellid = pTopBar->Add(sell); pTopBar->SetConstraintPercent(lblpower, 0.0f, 0.0f, 0.25f, 0.8f); pTopBar->SetConstraintPercent(lblmoney, 0.25f, 0.0f, 0.25f, 0.8f); pTopBar->SetConstraintPercent(lbltime, 0.5f, 0.0f, 0.25f, 0.8f); pTopBar->SetConstraintPercent(sellid, 0.75f, 0.0f, 0.25f, 0.8f); int playBar = pMainGame->Add(pPlayBar); pMainGame->SetConstraintPercent(playBar, 0.0f, 1.0f - sizes[1], 1.0f, sizes[1]); // pLoading->Increment(increment); pTopBar->init(); // pLoading->Increment(increment); pPlayBar->init(); pPlayBar->SwitchSelected(NULL); pConsole->SetType(0); pConsole->PrepareBuffer(); console.WriteLine(_("Nightfall (Codename Twilight)")); // pLoading->Increment(increment); return SUCCESS; } void GameWindow::Sell(Window::GUI::EventType evt, void* arg) { if (Networking::isNetworked) { Networking::PrepareSell(Dimension::GetCurrentPlayer(), 100); } else { Dimension::SellPower(Dimension::GetCurrentPlayer(), 100); } } void GameWindow::DestroyGUI() { //Initate Panel and place GameInput delete pMainGame; delete pGameInput; delete pConsole; delete pPlayBar; delete pTopBar; delete p_lblMoney; delete p_lblPower; delete p_lblTime; delete sell; } GameWindow::~GameWindow() { DestroyGUI(); } bool GameWindow::ProcessEvents() { //SDL Events SDL_Event event; while (SDL_PollEvent(&event)) { if(pMainPanel != NULL) { switch(event.type) { case SDL_KEYDOWN: { pMainPanel->HandleEvent(KB_DOWN, &event, NULL); break; } case SDL_KEYUP: { pMainPanel->HandleEvent(KB_UP, &event, NULL); break; } case SDL_MOUSEMOTION: { //Translate position TranslatedMouse *ptr; pMainPanel->HandleEvent(MOUSE_MOVE, &event, ptr = TranslateMouseCoords(event.motion.x, event.motion.y)); delete ptr; break; } case SDL_MOUSEBUTTONDOWN: { TranslatedMouse *ptr; if(event.button.button == SDL_BUTTON_WHEELUP || event.button.button == SDL_BUTTON_WHEELDOWN) { pMainPanel->HandleEvent(MOUSE_SCROLL, &event, ptr = TranslateMouseCoords(event.button.x, event.button.y)); } else { pMainPanel->HandleEvent(MOUSE_DOWN, &event, ptr = TranslateMouseCoords(event.button.x, event.button.y)); } delete ptr; break; } case SDL_MOUSEBUTTONUP: { TranslatedMouse *ptr; pMainPanel->HandleEvent(MOUSE_UP, &event, ptr = TranslateMouseCoords(event.button.x, event.button.y)); delete ptr; break; } } } switch(event.type) { case SDL_QUIT: { go = false; break; } } } //Key States operations if (input.GetKeyState(SDLK_UP)) Dimension::Camera::instance.Fly(-1.5f * time_since_last_render_frame); else if (input.GetKeyState(SDLK_DOWN)) Dimension::Camera::instance.Fly(1.5f * time_since_last_render_frame); if (input.GetKeyState(SDLK_LEFT)) Dimension::Camera::instance.FlyHorizontally(-Game::Dimension::cameraFlySpeed * time_since_last_render_frame); else if (input.GetKeyState(SDLK_RIGHT)) Dimension::Camera::instance.FlyHorizontally(Game::Dimension::cameraFlySpeed * time_since_last_render_frame); if (input.GetKeyState(SDLK_PAGEUP)) Dimension::Camera::instance.Zoom(Game::Dimension::cameraZoomSpeed * time_since_last_render_frame); else if (input.GetKeyState(SDLK_PAGEDOWN)) Dimension::Camera::instance.Zoom(-Game::Dimension::cameraZoomSpeed * time_since_last_render_frame); if (input.GetKeyState(SDLK_HOME)) Dimension::Camera::instance.Rotate(Game::Dimension::cameraRotationSpeed * time_since_last_render_frame); else if (input.GetKeyState(SDLK_END)) Dimension::Camera::instance.Rotate(-Game::Dimension::cameraRotationSpeed * time_since_last_render_frame); return true; } bool GameWindow::PaintAll() { // nollställ backbufferten och depthbufferten glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // nollställ vyn glLoadIdentity(); Audio::PlaceSoundNodes(Dimension::Camera::instance.GetPosVector()); GUINode::instance.SetParams(pMainPanel, w, h); Scene::Graph::Node::TraverseFullTree(); SDL_GL_SwapBuffers(); return true; } void GameWindow::PauseRendering() { SDL_LockMutex(renderMutex2); pauseRendering = true; SDL_LockMutex(renderMutex); } void GameWindow::ResumeRendering() { pauseRendering = false; SDL_UnlockMutex(renderMutex); SDL_UnlockMutex(renderMutex2); } int GameWindow::RunLoop() { // Uint32 last_save = SDL_GetTicks(); if (!Game::Rules::noGraphics) glClearColor( 0.2f, 0.2f, 0.2f, 0.7f ); CurGame::Instance()->StartGameLogicThread(); while (!CurGame::Instance()->AtLeastOneFrameCalculated()) { SDL_Delay(1); } go = true; Uint32 lastFrameTime = SDL_GetTicks(); SDL_LockMutex(renderMutex); while(go) { time_since_last_render_frame = (SDL_GetTicks() - lastFrameTime) / 1000.0; lastFrameTime = SDL_GetTicks(); if (Game::Rules::noGraphics) SDL_Delay(1); else PaintAll(); ProcessEvents(); if (pauseRendering) { SDL_UnlockMutex(renderMutex); SDL_LockMutex(renderMutex2); // Force a context switch; renderMutex2 is locked SDL_UnlockMutex(renderMutex2); SDL_LockMutex(renderMutex); } frames++; if (SDL_GetTicks() - last_status_time >= 1000) { int avgcount = 0; if (AI::numPaths) { avgcount = AI::cCount / AI::numPaths; } // if (Game::Rules::noGraphics) cout << "Fps: " << ((float) frames / (((float) (SDL_GetTicks() - last_status_time)) / 1000.0f)) << " " << Dimension::pWorld->vUnits.size() << " " << AI::currentFrame << " c: " << AI::cCount << " t: " << AI::tCount << " f: " << AI::fCount << " p: " << AI::pCount << " n: " << AI::numPaths << " q: " << AI::GetQueueSize() << " f: " << AI::numFailed << " a: " << avgcount << " nrf: " << AI::notReachedFlood << " nrp: " << AI::notReachedPath << " nsc: " << Dimension::numSentCommands << " ngs1: " << AI::numGreatSuccess1 << " ngs2: " << AI::numGreatSuccess2 << " ntf: " << AI::numTotalFrames << endl; // else console << "Fps: " << ((float) frames / (((float) (SDL_GetTicks() - last_status_time)) / 1000.0f)) << " " << Dimension::pWorld->vUnits.size() << Console::nl; AI::cCount = 0; AI::tCount = 0; AI::fCount = 0; AI::pCount = 0; AI::numPaths = 0; AI::numFailed = 0; AI::notReachedFlood = 0; AI::notReachedPath = 0; Dimension::numSentCommands = 0; AI::numGreatSuccess1 = 0; AI::numGreatSuccess2 = 0; AI::numTotalFrames = 0; frames = 0; last_status_time = SDL_GetTicks(); } /* if (SDL_GetTicks() - last_save >= 300000) { bool exists; time_t rawtime; time(&rawtime); char* time_string = ctime(&rawtime); if (time_string[strlen(time_string)-1] == '\n') { time_string[strlen(time_string)-1] = '\0'; } std::string filename = Utilities::GetWritableDataFile("autosaves/Autosave " + (std::string) time_string + ".xml", exists); if (filename.length()) { Dimension::SaveGame(filename); system(("bzip2 \"" + filename + "\"").c_str()); } last_save = SDL_GetTicks(); }*/ } SDL_UnlockMutex(renderMutex); // SDL_WaitThread(gameThread, NULL); return returnValue; } GameWindow::GUINode::GUINode() : pMainPanel(NULL), w(0), h(0) { } void GameWindow::GUINode::Render() { matrices[MATRIXTYPE_MODELVIEW].Apply(); if(pMainPanel != NULL) { Utilities::SwitchTo2DViewport(w, h); pMainPanel->Paint(); pMainPanel->PaintTooltip(); Utilities::RevertViewport(); } } void GameWindow::GUINode::SetParams(Panel* pMainPanel, float w, float h) { this->pMainPanel = pMainPanel; this->w = w; this->h = h; } GameWindow::GUINode GameWindow::GUINode::instance; GameWindow::GUINode& GameWindow::GetGUINode() { return GUINode::instance; } } }
// This file is a part of Chroma. // Copyright (C) 2016-2018 Matthew Murray // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <memory> #include <vector> #include <string> #include "common/CommonTypes.h" #include "common/CommonEnums.h" #include "gb/core/Enums.h" namespace Emu { class SdlContext; } namespace Gb { class CartridgeHeader; class Timer; class Serial; class Lcd; class Joypad; class Audio; class Memory; class Cpu; class Logging; class GameBoy { public: GameBoy(const Console _console, const CartridgeHeader& header, Emu::SdlContext& context, const std::string& save_path, const std::vector<u8>& rom, bool enable_iir, LogLevel log_level); ~GameBoy(); const Console console; const GameMode game_mode; std::unique_ptr<Timer> timer; std::unique_ptr<Serial> serial; std::unique_ptr<Lcd> lcd; std::unique_ptr<Joypad> joypad; std::unique_ptr<Audio> audio; std::unique_ptr<Memory> mem; std::unique_ptr<Cpu> cpu; std::unique_ptr<Logging> logging; void EmulatorLoop(); void SwapBuffers(std::vector<u16>& back_buffer); void Screenshot() const; void HardwareTick(unsigned int cycles); void HaltedTick(unsigned int cycles); bool ConsoleDmg() const { return console == Console::DMG; } bool ConsoleCgb() const { return console == Console::CGB || console == Console::AGB; } bool GameModeDmg() const { return game_mode == GameMode::DMG; } bool GameModeCgb() const { return game_mode == GameMode::CGB; } // Speed Switch and STOP mode functions. bool JoypadPress() const; void StopLcd(); void SpeedSwitch(); private: Emu::SdlContext& sdl_context; std::vector<u16> front_buffer; bool quit = false; bool pause = false; bool old_pause = false; bool frame_advance = false; u8 lcd_on_when_stopped = 0x00; void RegisterCallbacks(); }; } // End namespace Gb
import { faVolumeMute, faVolumeUp } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useState } from "react"; type SpeechButtonProps = { text: string; }; const SpeechButton = ({ text }: SpeechButtonProps) => { const [isSpeaking, setIsSpeaking] = useState(false); let utterance: SpeechSynthesisUtterance | null = null; const handleSpeech = () => { if (isSpeaking) { speechSynthesis.cancel(); setIsSpeaking(false); } else { utterance = new SpeechSynthesisUtterance(text); utterance.lang = "en-US"; utterance.rate = 1; // Adjust the rate (speed) of the speech if necessary utterance.onend = () => setIsSpeaking(false); speechSynthesis.speak(utterance); setIsSpeaking(true); } }; return ( <button onClick={handleSpeech} className="text-white"> <FontAwesomeIcon icon={isSpeaking ? faVolumeMute : faVolumeUp} size="lg" /> </button> ); }; export default SpeechButton;
import seedrandom from "seedrandom"; import { NumberLiteralType } from "typescript"; import { IHero, IResource, IStory } from "../storage/types"; import { addHero, selectHeroes, openAdventure, openStory, updateNPCs, addSpells, selectSpells, addResources, generateDeck, generateEnemy, generateEnemyDeck, generateFight, } from "./actions"; import { IGameData, IEventPlayer, IUserEvent, IPlayerAdventure, IPStartFightEvent, IPFinishDialogueEvent, IPFinishReelEvent, IPWinFightEvent, IPLooseFightEvent, } from "./types"; export const createUserEvent = async ( gameData: IGameData, player: IEventPlayer, event: IUserEvent ): Promise<IEventPlayer> => { console.log("createUserEvent"); let newPlayer = player; const initNPC = { npc_id: 0, dialogue_id: 6 }; const initResources = [ { resource_id: 8, quantity: 5 }, { resource_id: 9, quantity: 5 }, { resource_id: 5, quantity: 3 }, ]; const initHero = 0; const initAdv = 0; newPlayer.player.created_at = new Date(event.created_at); newPlayer.player.updated_at = new Date(); newPlayer.player.id = event.player_id; newPlayer.player.life = 10; newPlayer.player.maxlife = 10; newPlayer.player.mana = 10; newPlayer.player.maxmana = 10; newPlayer.player.rank = 1; newPlayer.heroes = addHero(newPlayer.heroes, gameData.heroes, initHero); newPlayer.heroes = selectHeroes(newPlayer.heroes, [initHero], 1); newPlayer.adventures = openAdventure( newPlayer.adventures, gameData.adventures, initAdv ); newPlayer.adventures = openStory(newPlayer.adventures, initAdv, 0); newPlayer.npcs = updateNPCs( newPlayer.npcs, gameData.characters, gameData.dialogues, [initNPC] ); newPlayer.spells = addSpells( newPlayer.spells, gameData.spells, [7, 7, 7, 8, 8, 9] ); newPlayer.spells = selectSpells(newPlayer.spells, [0, 1, 3, 4, 5], 5); newPlayer.resources = addResources( newPlayer.resources, gameData.resources, initResources ); return newPlayer; }; const getHash = (input: string) => { let hash = 0, len = input.length; for (var i = 0; i < len; i++) { hash = (hash << 5) - hash + input.charCodeAt(i); hash |= 0; // to 32bit integer } return hash; }; const generateLoot = (seed: string, resources: IResource[]) => { //generate loot based on event creation date if (resources.length !== 10) throw new Error(`Can't generate reward, requires 10 resources options`); // console.log("generate loot imput, seed:", seed); const rng = seedrandom(seed); const items: number[] = []; for (let i = 0; i < 3; i++) { let rand = Math.round(rng() * 9); while (items.indexOf(rand) !== -1) { rand = Math.round(rng() * 9); } items.push(rand); } // console.log("items", items); const generated = []; for (let i = 0; i < items.length; i++) { const resource = resources[items[i]]; generated[i] = { resource_id: resource.id, quantity: Math.round(rng() * 8) + 1, }; } // console.log("generated reward", generated); return generated; }; export const startFightEvent = async ( gameData: IGameData, player: IEventPlayer, event: IPStartFightEvent ): Promise<IEventPlayer> => { let newPlayer = player; newPlayer.currentfight = generateFight( gameData, player, event.adventure_id, event.fight_id, event.heroes, event.spells, event.id ); return newPlayer; }; export const finishDialogueEvent = async ( gameData: IGameData, player: IEventPlayer, event: IPFinishDialogueEvent ): Promise<IEventPlayer> => { let newPlayer = finishStory( gameData, player, event.adventure_id, event.story_id ); // console.log("finishDialogueEvent", event); return newPlayer; }; export const finishReelEvent = async ( gameData: IGameData, player: IEventPlayer, event: IPFinishReelEvent ): Promise<IEventPlayer> => { let newPlayer = finishStory( gameData, player, event.adventure_id, event.story_id ); // console.log("finishReelEvent", event); return newPlayer; }; export const finishStory = async ( gameData: IGameData, player: IEventPlayer, adventure_id: number, story_id: number ): Promise<IEventPlayer> => { let newPlayer = player; // console.log("finishStory"); const story = player.adventures ?.find((a: IPlayerAdventure) => a.id === adventure_id) ?.stories?.find((s: IStory) => s.id === story_id); if (!story) { throw new Error( `Can't apply finish story event, can't find story ${story_id} in adventure ${adventure_id}` ); } // if (story.type === "fight") { // console.log("applying a fight result"); // Calculate experience. Sort enemy cards based on amount on updates. Give 1 for every non-updated card, 1x3 for every 1updated, 1x5 for every 2 updated and 1x8 for every 3 updated. // Possible multpliers - no redraw (+5), no damage (+10) // const common = gameData.resources.filter( // (r: IResource) => r.commonality === 10 && r.school.id < 5 // ); // const loot = generateLoot( // `${event.event_id}${event.player_id}${event.adventure_id}${event.story_id}`, // common // ); // console.log("loot", loot); // TODO Modifiers have to improve your loot // player.resources = addResources(player.resources, gameData.resources, loot); // } switch (story_id) { case 0: newPlayer.npcs = updateNPCs( newPlayer.npcs, gameData.characters, gameData.dialogues, [ { npc_id: 0, dialogue_id: null }, { npc_id: 6, dialogue_id: 7 }, ] ); newPlayer.adventures = openStory( newPlayer.adventures, adventure_id, story_id + 1 ); break; case 1: newPlayer.heroes = addHero(newPlayer.heroes, gameData.heroes, 1); newPlayer.spells = addSpells( newPlayer.spells, gameData.spells, [10, 10, 10, 11, 11, 12] ); newPlayer.adventures = openStory( newPlayer.adventures, adventure_id, story.next_id ? story.next_id : 1 ); break; default: newPlayer.adventures = openStory( newPlayer.adventures, adventure_id, story_id + 1 ); } return newPlayer; };
#include <stdio.h> #include <stdlib.h> // Chj: // This program does experiment as p89 suggests: we call __syncthreads() // for odd threads only, but NOT for even threads. Let's see whether // the "odd"(pun) __syncthreads() would freeze/hang. // // The code body is adapted from add_loop_gpu.cu . #include "../common/book.h" #define N 10 __global__ void add( int *a, int *b, int *c, bool is_half_sync ) { int tid = threadIdx.x; // this thread handles the data at its thread id if (tid < N) c[tid] = a[tid] + b[tid]; // Experiment for unbalanced __syncthreads() if( is_half_sync && (threadIdx.x % 2 == 1) ) { __syncthreads(); } } int main( int argc, char *argv[] ) { if(argc==1) { printf("To run normally, type:\n"); printf(" unbalanced_syncthreads 0\n"); printf(""); printf("To run normally, type:\n"); printf(" unbalanced_syncthreads 1\n"); return 1; } bool is_half_sync = (argv[1][0]=='1') ? true : false; int a[N], b[N], c[N]; int *dev_a, *dev_b, *dev_c; // allocate the memory on the GPU HANDLE_ERROR( cudaMalloc( (void**)&dev_a, N * sizeof(int) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_b, N * sizeof(int) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_c, N * sizeof(int) ) ); // fill the arrays 'a' and 'b' on the CPU for (int i=0; i<N; i++) { a[i] = -i; b[i] = i * i; } // copy the arrays 'a' and 'b' to the GPU HANDLE_ERROR( cudaMemcpy( dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b, b, N * sizeof(int), cudaMemcpyHostToDevice ) ); add<<<1, N>>>( dev_a, dev_b, dev_c, is_half_sync ); // copy the array 'c' back from the GPU to the CPU HANDLE_ERROR( cudaMemcpy( c, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost ) ); // display the results for (int i=0; i<N; i++) { printf( ">> %d + %d = %d\n", a[i], b[i], c[i] ); } // free the memory allocated on the GPU HANDLE_ERROR( cudaFree( dev_a ) ); HANDLE_ERROR( cudaFree( dev_b ) ); HANDLE_ERROR( cudaFree( dev_c ) ); return 0; }
import useForm from 'src/core/hooks/use-form'; import useSubmit from 'src/core/hooks/use-submit'; import { memo, useEffect, useState } from 'react'; import Modal from 'src/core/components/modal/modal'; import Form from 'src/core/components/form/form'; import Grid from 'src/core/components/grid/grid'; import Button from 'src/core/components/button/button'; import roleService from 'src/api/role-service'; import Feedback from 'src/core/components/feedback/feedback'; import Spinner from 'src/core/components/spinner/spinner'; import { STATES, useAlert } from 'src/core/hooks/alert-context'; import userService from 'src/api/user-service'; import { Gender, IUser, Status } from 'src/interfaces/user'; import ConfirmationDialog from 'src/shared/demo-management/confirmation-dialog'; import { HiOutlineExclamationCircle } from 'react-icons/hi'; import Tooltip from 'src/core/components/tooltip/tooltip'; import { getFormatDate } from 'src/core/functions/get-format-date'; export enum ACTIONS { EDIT = 'edit', ADD = 'add', } const emptyUserValues = { userId: '', username: '', email: '', displayName: '', imageURL: '', status: '', gender: '', phone: '', title: '', position: '', roles: [], dateOfBirth: '1990/01/01', }; interface UserFormDialogProps { fieldId?: string | number; openDialog: boolean; onClose: () => void; action: ACTIONS; onSubmitSuccess?: (responseData?: any, error?: string) => void; } const UserFormDialog = memo(({ openDialog, onClose, action, onSubmitSuccess, fieldId }: UserFormDialogProps) => { const [roleOptions, setRoleOptions] = useState<Array<any>>([]); const [openConfirm, setOpenConfirm] = useState(false); const [initialValues, setInitialValues] = useState<IUser>(emptyUserValues); const [loadingErrorMsg, setLoadingErrorMsg] = useState<string | undefined>(undefined); const { fieldProps, isDirty, handleSubmit, setErrors, values, handleChange, submitState } = useSubmit( useForm({ initialValues }), action === ACTIONS.EDIT ? fieldId ? (formData: IUser, config?: any) => userService.update(fieldId, formData, config) : () => {} : userService.add, ); useEffect(() => { if (action === ACTIONS.EDIT && fieldId) { const getDetail = async () => { try { const response = await userService.getSingle(fieldId); const _initialValues = response.data; _initialValues['dateOfBirth'] = getFormatDate(_initialValues['dateOfBirth'] || '1990-01-01', 'yyyy-MM-dd'); response && setInitialValues(response.data); const responseRoleOptions = await roleService.get(); let newRoleOptions = responseRoleOptions.data.list; responseRoleOptions && setRoleOptions(newRoleOptions); } catch (error: any) { setLoadingErrorMsg(error.message); } }; getDetail(); } setErrors({}); setInitialValues(emptyUserValues); // eslint-disable-next-line react-hooks/exhaustive-deps }, [action, fieldId]); const { showMessage } = useAlert(); useEffect(() => { if (!submitState?.loading && submitState?.data) { onSubmitSuccess && onSubmitSuccess(submitState.data); showMessage('Successfully', STATES.SUCCESS); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [submitState?.loading]); const handleCloseConfirm = (value: any) => { setOpenConfirm(false); if (value === 'ok') { onClose(); } }; const handleClose = () => { if (isDirty()) { setOpenConfirm(true); return; } onClose(); }; return ( <> <Modal open={openDialog} onClose={handleClose} animation> <Form noValidate onSubmit={handleSubmit}> <Modal.Header>{action === 'edit' ? 'Edit user' : 'Add user'}</Modal.Header> <Modal.Body> <Grid row spacing={1}> <Grid xs={12} sm={6}> <Form.Control disabled placeholder="User Id" name="userId" {...(fieldProps('userId', { required: true }) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Username" label={'Username'} name="username" {...(fieldProps('username', { required: true }) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Email" label={'Email'} name="email" {...(fieldProps('email', {}) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Phone" name="phone" {...(fieldProps('phone', {}) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Display Name" name="displayName" {...(fieldProps('displayName', {}) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Select placeholder="Status" name="status" value={values['status']} onChange={handleChange('status')} > <Form.Select.Option value={Status.Active}>Active</Form.Select.Option> <Form.Select.Option value={Status.Inactive}>Inactive</Form.Select.Option> <Form.Select.Option value={Status.Suspense}>Suspense</Form.Select.Option> <Form.Select.Option value="">None</Form.Select.Option> </Form.Select> </Grid> <Grid xs={12} sm={6}> <Form.Select placeholder="Gender" name="gender" value={values['gender']} onChange={handleChange('gender')} > <Form.Select.Option value="">None</Form.Select.Option> <Form.Select.Option value={Gender.Female}>Female</Form.Select.Option> <Form.Select.Option value={Gender.Male}>Male</Form.Select.Option> </Form.Select> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Title" name="title" {...(fieldProps('title', {}) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Control placeholder="Position" name="position" {...(fieldProps('position', {}) as any)} /> </Grid> <Grid xs={12} sm={6}> <Form.Select placeholder="Roles" name="roles" value={values['roles'] || []} onChange={handleChange('roles')} > {roleOptions.map((value) => ( <Form.Select.Option key={value.roleId} value={value.roleId}> {value.roleName} </Form.Select.Option> ))} </Form.Select> </Grid> <Grid xs={12} sm={6}> <Form.Control type="date" placeholder="DOB" name="dateOfBirth" {...(fieldProps('dateOfBirth', {}) as any)} /> </Grid> </Grid> </Modal.Body> <Modal.Footer> <Button onClick={handleClose} disabled={submitState?.loading} color="danger"> Cancel </Button> <Button type="submit" disabled={submitState?.loading} color="primary"> Save {submitState?.loading && <Spinner size="sm" />} </Button> </Modal.Footer> </Form> </Modal> <ConfirmationDialog size="sm" open={openConfirm} onClose={handleCloseConfirm} backdrop={false} dialogClassName="shadow-lg" content={<p>Are you want to discard changes?</p>} cancelText="Back" confirmText="Discard" headerText={ <h5 className="d-flex align-items-center"> <Tooltip text="Hello"> <div className="me-2"> <HiOutlineExclamationCircle /> </div> </Tooltip>{' '} Confirm your action </h5> } /> </> ); }); export default UserFormDialog;
// SnakeGame.tsx import React, { useState, useEffect, useRef, KeyboardEvent } from 'react'; import './SnakeGame.css'; interface Snake { x: number; y: number; } interface Food { x: number; y: number; } const generateFoodPosition = (): Food => { const x = Math.floor(Math.random() * 10); const y = Math.floor(Math.random() * 10); return { x, y }; }; const SnakeGame: React.FC = () => { const [snake, setSnake] = useState<Snake[]>([{ x: 0, y: 0 }]); const [food, setFood] = useState<Food>(generateFoodPosition()); const [direction, setDirection] = useState<'UP' | 'DOWN' | 'LEFT' | 'RIGHT'>('RIGHT'); const [gameOver, setGameOver] = useState<boolean>(false); const [score, setScore] = useState<number>(0); const gameIntervalRef = useRef<number | null>(null); useEffect(() => { if (!gameOver) { gameIntervalRef.current = setInterval(moveSnake, 300); return () => clearInterval(gameIntervalRef.current!); } }, [snake, food, gameOver]); const moveSnake = () => { const newSnake = [...snake]; const head = { ...newSnake[0] }; switch (direction) { case 'UP': head.y -= 1; break; case 'DOWN': head.y += 1; break; case 'LEFT': head.x -= 1; break; case 'RIGHT': head.x += 1; break; default: break; } if (head.x === food.x && head.y === food.y) { setFood(generateFoodPosition()); newSnake.unshift(head); setScore(score + 1); } else { newSnake.unshift(head); newSnake.pop(); } if ( head.x < 0 || head.y < 0 || head.x >= 10 || head.y >= 10 || checkCollision(newSnake.slice(1), head) ) { setGameOver(true); } setSnake(newSnake); }; const checkCollision = (snakeSegments: Snake[], head: Snake): boolean => { return snakeSegments.some((segment) => segment.x === head.x && segment.y === head.y); }; const handleKeyDown = (event: KeyboardEvent) => { switch (event.key) { case 'ArrowUp': setDirection('UP'); break; case 'ArrowDown': setDirection('DOWN'); break; case 'ArrowLeft': setDirection('LEFT'); break; case 'ArrowRight': setDirection('RIGHT'); break; default: break; } }; const handleRestart = () => { setSnake([{ x: 0, y: 0 }]); setFood(generateFoodPosition()); setDirection('RIGHT'); setGameOver(false); setScore(0); }; return ( <div className={`snake-game ${gameOver ? 'game-over' : ''}`} onKeyDown={handleKeyDown} tabIndex={0} > <h1>Snake Game</h1> <div className="score">Score: {score}</div> <div className="game-board"> {Array.from({ length: 10 }).map((_, rowIndex) => ( <div key={rowIndex} className="row"> {Array.from({ length: 10 }).map((_, colIndex) => ( <div key={colIndex} className={`cell ${ snake.some( (segment) => segment.x === colIndex && segment.y === rowIndex ) ? 'snake' : '' } ${ food.x === colIndex && food.y === rowIndex ? 'food' : '' }`} ></div> ))} </div> ))} </div> {gameOver && ( <div> <p className="game-over-message">Game Over!</p> <button className="restart-button" onClick={handleRestart}> Restart </button> </div> )} </div> ); }; export default SnakeGame;
import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import dayjs from 'dayjs/esm'; import { isPresent } from 'app/core/util/operators'; import { ApplicationConfigService } from 'app/core/config/application-config.service'; import { createRequestOption } from 'app/core/request/request-util'; import { IArrosage, getArrosageIdentifier } from '../arrosage.model'; export type EntityResponseType = HttpResponse<IArrosage>; export type EntityArrayResponseType = HttpResponse<IArrosage[]>; @Injectable({ providedIn: 'root' }) export class ArrosageService { protected resourceUrl = this.applicationConfigService.getEndpointFor('api/arrosages'); constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {} create(arrosage: IArrosage): Observable<EntityResponseType> { const copy = this.convertDateFromClient(arrosage); return this.http .post<IArrosage>(this.resourceUrl, copy, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } update(arrosage: IArrosage): Observable<EntityResponseType> { const copy = this.convertDateFromClient(arrosage); return this.http .put<IArrosage>(`${this.resourceUrl}/${getArrosageIdentifier(arrosage) as number}`, copy, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } partialUpdate(arrosage: IArrosage): Observable<EntityResponseType> { const copy = this.convertDateFromClient(arrosage); return this.http .patch<IArrosage>(`${this.resourceUrl}/${getArrosageIdentifier(arrosage) as number}`, copy, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } find(id: number): Observable<EntityResponseType> { return this.http .get<IArrosage>(`${this.resourceUrl}/${id}`, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } query(req?: any): Observable<EntityArrayResponseType> { const options = createRequestOption(req); return this.http .get<IArrosage[]>(this.resourceUrl, { params: options, observe: 'response' }) .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res))); } delete(id: number): Observable<HttpResponse<{}>> { return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); } addArrosageToCollectionIfMissing(arrosageCollection: IArrosage[], ...arrosagesToCheck: (IArrosage | null | undefined)[]): IArrosage[] { const arrosages: IArrosage[] = arrosagesToCheck.filter(isPresent); if (arrosages.length > 0) { const arrosageCollectionIdentifiers = arrosageCollection.map(arrosageItem => getArrosageIdentifier(arrosageItem)!); const arrosagesToAdd = arrosages.filter(arrosageItem => { const arrosageIdentifier = getArrosageIdentifier(arrosageItem); if (arrosageIdentifier == null || arrosageCollectionIdentifiers.includes(arrosageIdentifier)) { return false; } arrosageCollectionIdentifiers.push(arrosageIdentifier); return true; }); return [...arrosagesToAdd, ...arrosageCollection]; } return arrosageCollection; } protected convertDateFromClient(arrosage: IArrosage): IArrosage { return Object.assign({}, arrosage, { date: arrosage.date?.isValid() ? arrosage.date.toJSON() : undefined, }); } protected convertDateFromServer(res: EntityResponseType): EntityResponseType { if (res.body) { res.body.date = res.body.date ? dayjs(res.body.date) : undefined; } return res; } protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType { if (res.body) { res.body.forEach((arrosage: IArrosage) => { arrosage.date = arrosage.date ? dayjs(arrosage.date) : undefined; }); } return res; } }
package model import ( "testing" "github.com/stretchr/testify/assert" ) func TestCounterGetStringValue(t *testing.T) { tests := []struct { name string want string metric CounterMetric }{ { name: "pozitive number", metric: CounterMetric{Name: "", Value: 1}, want: "1", }, { name: "negative number", metric: CounterMetric{Name: "", Value: -1}, want: "-1", }, { name: "negative zero", metric: CounterMetric{Name: "", Value: -0}, want: "0", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.want, test.metric.GetStringValue()) }) } } func TestGetCounterValue(t *testing.T) { tests := []struct { name string metric CounterMetric want int64 }{ { name: "data type is int", metric: CounterMetric{Name: "test", Value: 1}, want: 1, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.want, test.metric.GetValue()) }) } }
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet'; import React, { Suspense } from 'react'; import { StyleSheet } from 'react-native'; import FlashMessage from 'react-native-flash-message'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { TamaguiProvider, Text, Theme } from 'tamagui'; import { NavigationContainer } from '@/components'; import { useSelectedTheme } from '@/hooks'; import tamaguiConfig from '../../tamagui.config'; import { APIProvider } from './api-provider'; type RootProviderProps = { children: React.ReactNode; }; export function RootProvider({ children }: RootProviderProps) { const { selectedTheme } = useSelectedTheme(); return ( <SafeAreaProvider> <TamaguiProvider defaultTheme={selectedTheme} config={tamaguiConfig}> <GestureHandlerRootView style={styles.container}> <Suspense fallback={<Text>Loading...</Text>}> <Theme name="red"> <BottomSheetModalProvider> <APIProvider> <NavigationContainer> {children} <FlashMessage position="top" /> </NavigationContainer> </APIProvider> </BottomSheetModalProvider> </Theme> </Suspense> </GestureHandlerRootView> </TamaguiProvider> </SafeAreaProvider> ); } const styles = StyleSheet.create({ container: { flex: 1, }, });
import { ArrowLeft, Bell, Menu, Mic, Search, Upload, User } from "lucide-react"; import logo from "../assets/logo.svg"; import secondLogo from "../assets/logo-without-name.svg"; import Button from "./Button"; import { useState } from "react"; import { useSidebarContext } from "../contexts/SidebarContext"; const Header = () => { const [showSearchInput, setSearchInput] = useState(false); return ( <header className="flex gap-10 max-md:gap-4 lg:gap-20 justify-between pt-2 mb-6 mx-7"> <HeaderFirstSection hidden={showSearchInput} /> <form className={`gap-4 flex-grow justify-center ${ showSearchInput ? "flex" : "hidden md:flex" }`} > <Button onClick={() => setSearchInput(false)} type="button" size="icon" variant="ghost" className={`flex-shrink-0 ${showSearchInput ? "block" : "hidden"}`} > <ArrowLeft /> </Button> <div className="flex flex-grow max-w-[600px]"> <input type="search" placeholder="Search" className="border rounded-l-full border-secondary-border shadow-inner shadow-secondary py-1 px-4 text-lg w-full focus:border-secondary-dark-hover outline-none" /> <Button className="py-2 px-4 rounded-r-full border-secondary-border border border-1-0 flex-shrink-0"> <Search /> </Button> </div> <Button type="button" size="icon" className="flex-shrink-0"> <Mic /> </Button> </form> <div className={`flex-shrink-0 md:gap-2 ${ showSearchInput ? "hidden" : "flex" }`} > <Button onClick={() => setSearchInput(true)} size="icon" variant="ghost" className="md:hidden" > <Search /> </Button> <Button size="icon" variant="ghost"> <Upload /> </Button> <Button size="icon" variant="ghost"> <Bell /> </Button> <Button size="icon" variant="ghost"> <User /> </Button> </div> </header> ); }; type HeaderFirstSectionProps = { hidden?: boolean; }; export function HeaderFirstSection({ hidden = false, }: HeaderFirstSectionProps) { const { toggle } = useSidebarContext(); return ( <div className={`flex gap-1 sm:gap-4 items-center flex-shrink-0 ${ hidden ? "hidden" : "flex" }`} > <Button onClick={toggle} variant={"ghost"} size={"icon"}> <Menu /> </Button> <a href="/backtube"> <img src={logo} alt="logo" className="h-8 max-sm:hidden" /> </a> <a href="/backtube"> <img src={secondLogo} alt="logo" className="h-8 sm:hidden" /> </a> </div> ); } export default Header;
import { IsNotEmpty, MaxLength } from 'class-validator'; import { Column, Entity } from 'typeorm'; import { AbstractEntity } from '../vendors/base/abstract.entity'; export enum OS { NA = 'N/A', IOS = 'iOS', ANDROID = 'Android', } export enum STATUS { AVAILABLE = 'Available', LEASED = 'Leased', BROKEN = 'Broken', } @Entity('devices') export class DevicesEntity extends AbstractEntity { @Column({ type: 'varchar', length: 255, nullable: true, name: 'device_name' }) deviceName: string; @IsNotEmpty({ message: 'OS can not be null or empty' }) @Column({ name: 'os', type: 'enum', enum: OS, nullable: false, default: OS.NA }) os: OS; @IsNotEmpty({ message: 'uuid can not be null or empty' }) @MaxLength(255, { message: 'The length must be less than 255 characters' }) @Column({ type: 'varchar', length: 255, nullable: false, unique: true }) uuid: string; @MaxLength(255, { message: 'The length must be less than 255 characters' }) @IsNotEmpty({ message: 'os version can not be null or empty' }) @Column({ type: 'varchar', nullable: false, length: 255 }) osVersion: string; @MaxLength(255, { message: 'The length must be less than 255 characters' }) @IsNotEmpty({ message: 'manufacturer can not be null or empty' }) @Column({ type: 'varchar', nullable: false, length: 255 }) manufacturer: string; @IsNotEmpty({ message: 'status can not be null or empty' }) @Column({ name: 'status', type: 'enum', enum: STATUS, nullable: false, default: STATUS.AVAILABLE }) status: STATUS; }
import { useContext, useState } from "react"; import AuthContent from "../components/Auth/AuthContent"; import { authenticate } from "../util/auth"; import LoadingOverlay from "../components/ui/LoadingOverlay"; import { Alert } from "react-native"; import { AuthContext } from "../store/auth-context"; function LoginScreen() { const [isAuthenticating, setIsAuthenticating] = useState(false); const authContext = useContext(AuthContext); async function loginHandler({ email, password }) { setIsAuthenticating(true); try { const responseToken = await authenticate(email, password); authContext.authenticate(responseToken); } catch (error) { Alert.alert("An error occurred while authenticating"); console.log(error); setIsAuthenticating(false); } } if (isAuthenticating) { return <LoadingOverlay message="Loggin in user..." />; } return <AuthContent isLogin onAuthenticate={loginHandler} />; } export default LoginScreen;
######################################################################## # # # This software is part of the ast package # # Copyright (c) 1982-2012 AT&T Intellectual Property # # Copyright (c) 2020-2021 Contributors to ksh 93u+m # # and is licensed under the # # Eclipse Public License, Version 1.0 # # by AT&T Intellectual Property # # # # A copy of the License is available at # # http://www.eclipse.org/org/documents/epl-v10.html # # (with md5 checksum b35adb5213ca9657e911e9befb180842) # # # # Information and Software Systems Research # # AT&T Research # # Florham Park NJ # # # # David Korn <dgk@research.att.com> # # # ######################################################################## . "${SHTESTS_COMMON:-${0%/*}/_common}" # These are tests for the interactive shell, run in a pseudoterminal utility # called 'pty', which allows for scripting interactive sessions and which is # installed in arch/*/bin while building. To understand these tests, first # read the pty manual by running: arch/*/bin/pty --man # # Do not globally set the locale; these tests must pass for all locales. # # The # err_exit # comments are to enable shtests to count the tests. # the trickiest part of the tests is avoiding typeahead # in the pty dialogue whence -q pty || { warning "pty command not found -- tests skipped"; exit 0; } case $(uname -s) in Darwin | FreeBSD | Linux ) ;; * ) warning "pty not confirmed to work correctly on this system -- tests skipped" exit 0 ;; esac # On some systems, the stty command does not appear to work correctly on a pty pseudoterminal. # To avoid false regressions, we have to set 'erase' and 'kill' on the real terminal. if test -t 0 2>/dev/null </dev/tty && stty_restore=$(stty -g </dev/tty) then trap 'stty "$stty_restore" </dev/tty' EXIT # note: on ksh, the EXIT trap is also triggered for termination due to a signal stty erase ^H kill ^X else warning "cannot set tty state -- tests skipped" exit 0 fi bintrue=$(whence -p true) x=$( "$SHELL" 2>&1 <<- \EOF trap 'exit 0' EXIT bintrue=$(whence -p true) set -o monitor { eval $'command set -o vi 2>/dev/null\npty $bintrue' } < /dev/null & pid=$! jobs kill $$ EOF ) [[ $x == *Stop* ]] && err_exit "monitor mode enabled incorrectly causes job to stop (got $(printf %q "$x"))" if [[ -o xtrace ]] then debug=--debug=1 else debug= fi function tst { integer lineno=$1 offset typeset text pty $debug --dialogue --messages='/dev/fd/1' $SHELL | while read -r text do if [[ $text == *debug* ]] then print -u2 -r -- "$text" else offset=${text/*: line +([[:digit:]]):*/\1} err\_exit "$lineno" "${text/: line $offset:/: line $(( lineno + offset)):}" fi done } # VISUAL, or if that is not set, EDITOR, automatically sets vi, gmacs or emacs mode if # its value matches *[Vv][Ii]*, *gmacs* or *macs*, respectively. See put_ed() in init.c. unset EDITOR if ((SHOPT_VSH)) then export VISUAL=vi elif ((SHOPT_ESH)) then export VISUAL=emacs else unset VISUAL fi export PS1=':test-!: ' PS2='> ' PS4=': ' ENV=/./dev/null EXINIT= HISTFILE= TERM=dumb if ! pty $bintrue < /dev/null then warning "pty command hangs on $bintrue -- tests skipped" exit 0 fi # err_exit # tst $LINENO <<"!" L POSIX sh 026(C) # If the User Portability Utilities Option is supported: When the # POSIX locale is specified and a background job is suspended by a # SIGTSTP signal then the <state> field in the output message is set to # Stopped, Suspended, Stopped(SIGTSTP) or Suspended(SIGTSTP). d 15 I ^\r?\n$ p :test-1: w sleep 60 & u [[:digit:]]\r?\n$ s 100 p :test-2: w kill -TSTP $! u (Stopped|Suspended) p :test-3: w kill -KILL $! w wait u (Killed|Done) ! # err_exit # tst $LINENO <<"!" L POSIX sh 028(C) # If the User Portability Utilities Option is supported: When the # POSIX locale is specified and a background job is suspended by a # SIGTTIN signal then the <state> field in the output message is set to # Stopped(SIGTTIN) or Suspended(SIGTTIN). I ^\r?\n$ p :test-1: w sleep 60 & u [[:digit:]]\r?\n$ s 100 p :test-2: w kill -TTIN $! u (Stopped|Suspended) \(SIGTTIN\) p :test-3: w kill -KILL $! w wait u (Killed|Done) ! # err_exit # tst $LINENO <<"!" L POSIX sh 029(C) # If the User Portability Utilities Option is supported: When the # POSIX locale is specified and a background job is suspended by a # SIGTTOU signal then the <state> field in the output message is set to # Stopped(SIGTTOU) or Suspended(SIGTTOU). I ^\r?\n$ p :test-1: w sleep 60 & u [[:digit:]]\r?\n$ s 100 p :test-2: w kill -TTOU $! u (Stopped|Suspended) \(SIGTTOU\) p :test-3: w kill -KILL $! w wait u (Killed|Done) ! # err_exit # tst $LINENO <<"!" L POSIX sh 091(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode an entered # character other than <newline>, erase, interrupt, kill, control-V, # control-W, backslash \ (followed by erase or kill), end-of-file and # <ESC> is inserted in the current command line. d 15 c echo h c ell w o u ^hello\r?\n$ ! # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L POSIX sh 093(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: After termination of a previous # command, sh is entered in insert mode. w echo hello\E u ^hello\r?\n$ c echo goo c dby w e u ^goodbye\r?\n$ ! # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L POSIX sh 094(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode an <ESC> # switches sh into command mode. c echo he\E s 400 w allo u ^hello\r?\n$ ! if [[ $(id -u) == 0 ]] then warning "running as root: skipping test POSIX sh 096(C)" else # err_exit # tst $LINENO <<"!" L POSIX sh 096(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in command mode the # interrupt character causes sh to terminate command line editing on # the current command line, re-issue the prompt on the next line of the # terminal and to reset the command history so that the command that # was interrupted is not entered in the history. I ^\r?\n$ p :test-1: w echo first p :test-2: w stty intr ^C p :test-3: c echo bad\E s 400 c \cC w echo scrambled p :test-4: w history u echo first r stty intr \^C r echo r history ! fi # err_exit # tst $LINENO <<"!" L POSIX sh 097(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode a <newline> # causes the current command line to be executed. d 15 c echo ok\n u ^ok\r?\n$ ! if [[ $(id -u) == 0 ]] then warning "running as root: skipping test POSIX sh 099(C)" else # err_exit # tst $LINENO <<"!" L POSIX sh 099(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode the interrupt # character causes sh to terminate command line editing on the current # command line, re-issue the prompt on the next line of the terminal # and to reset the command history so that the command that was # interrupted is not entered in the history. I ^\r?\n$ p :test-1: w echo first u ^first p :test-2: w stty intr ^C r p :test-3: c echo bad\cC w echo last p :test-4: w history u echo first r stty intr \^C r echo last r history ! fi # err_exit # tst $LINENO <<"!" L POSIX sh 100(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode the kill # character clears all the characters from the input line. p :test-1: w stty kill ^X p :test-2: c echo bad\cX w echo ok u ^ok\r?\n$ ! # err_exit # ((SHOPT_VSH || SHOPT_ESH)) && tst $LINENO <<"!" L POSIX sh 101(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode a control-V # causes the next character to be inserted even in the case that the # character is a special insert mode character. # Testing Requirements: The assertion must be tested with at least the # following set of characters: <newline>, erase, interrupt, kill, # control-V, control-W, end-of-file, backslash \ (followed by erase or # kill) and <ESC>. d 15 p :test-1: w stty erase ^H intr ^C kill ^X p :test-2: w echo erase=:\cV\cH: u ^erase=:\r?\n$ p :test-3: w echo kill=:\cV\cX: u ^kill=:\cX:\r?\n$ p :test-4: w echo control-V=:\cV\cV: u ^control-V=:\cV:\r?\n$ p :test-5: w echo control-W:\cV\cW: u ^control-W:\cW:\r?\n$ p :test-6: w echo EOF=:\cV\cD: u ^EOF=:\004:\r?\n$ p :test-7: w echo backslash-erase=:\\\cH: u ^backslash-erase=:\r?\n$ p :test-8: w echo backslash-kill=:\\\cX: u ^backslash-kill=:\cX:\r?\n$ p :test-9: w echo ESC=:\cV\E: u ^ESC=:\E:\r?\n$ p :test-10: w echo interrupt=:\cV\cC: u ^interrupt=:\cC:\r?\n$ ! # err_exit # tst $LINENO <<"!" L POSIX sh 104(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in insert mode an # end-of-file at the beginning of an input line is interpreted as the # end of input. p :test-1: w trap 'echo done >&2' EXIT p :test-2: s 100 c \cD u ^done\r?\n$ ! if [[ $(id -u) == 0 ]] then warning "running as root: skipping test POSIX sh 111(C)" else # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L POSIX sh 111(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in command mode, # inserts # the character # at the beginning of the command line and causes the # line to be treated as a comment and the line is entered in the # command history. p :test-1: c echo save\E s 400 c # p :test-2: w history u #echo save r history ! fi if [[ $(id -u) == 0 ]] then warning "running as root: skipping test POSIX sh 251(C)" else # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L POSIX sh 251(C) # If the User Portability Utilities Option is supported and shell # command line editing is supported: When in command mode, then the # command N repeats the most recent / or ? command, reversing the # direction of the search. p :test-1: w echo repeat-1 u ^repeat-1\r?\n$ p :test-2: w echo repeat-2 u ^repeat-2\r?\n$ p :test-3: s 100 c \E s 400 w /rep u echo repeat-2 c n r echo repeat-1 c N r echo repeat-2 w dd p :test-3: w echo repeat-3 u ^repeat-3\r?\n$ p :test-4: s 100 c \E s 400 w ?rep r echo repeat-2 c N r echo repeat-1 c n r echo repeat-2 c n r echo repeat-3 ! fi # This test freezes the 'less' pager on OpenBSD, which is not a ksh bug. : <<\disabled whence -q less && TERM=vt100 tst $LINENO <<"!" L process/terminal group exercise w m=yes; while true; do echo $m-$m; done | less u :$|:\E|lines c \cZ r Stopped w fg u yes-yes ! disabled # err_exit # # Test file name completion in vi mode if((SHOPT_VSH)); then mkdir "/tmp/fakehome_$$" && tst $LINENO <<! L vi mode file name completion # Completing a file name in vi mode that contains '~' and has a # base name the same length as the home directory's parent directory # shouldn't fail. w set -o vi; HOME=/tmp/fakehome_$$; touch ~/testfile_$$ w echo ~/tes\t u ^/tmp/fakehome_$$/testfile_$$\r?\n$ ! rm -r "/tmp/fakehome_$$" fi # SHOPT_VSH # err_exit # VISUAL='' tst $LINENO <<"!" L raw Bourne mode literal tab characters # With wide characters (e.g. UTF-8) disabled, raw mode is handled by ed_read() # in edit.c; it does not expand tab characters on the command line. # With wide characters enabled, and if vi mode is compiled in, raw mode is # handled by ed_viread() in vi.c (even though vi mode is off); it expands tab # characters to spaces on the command line. See slowread() in io.c. p :test-1: w true /de\tv/nu\tl\tl r ^:test-1: true (/de\tv/nu\tl\tl|/de v/nu l l)\r\n$ p :test-2: ! # err_exit # VISUAL='' tst $LINENO <<"!" L raw Bourne mode backslash handling # The escaping backslash feature should be disabled in the raw Bourne mode. # This is tested with both erase and kill characters. p :test-1: w stty erase ^H kill ^X p :test-2: w true string\\\\\cH\cH r ^:test-2: true string\r\n$ p :test-3: w true incorrect\\\cXtrue correct r ^:test-3: true correct\r\n$ ! # err_exit # # err_exit # set -- ((SHOPT_VSH)) && set -- "$@" vi ((SHOPT_ESH)) && set -- "$@" emacs gmacs for mode do VISUAL=$mode tst $LINENO << ! L escaping backslashes in $mode mode # Backslashes should only be escaped if the previous input was a backslash. # Other backslashes stored in the input buffer should be erased normally. d 15 p :test-1: w stty erase ^H p :test-2: w true string\\\\\\\\\\cH\\cH\\cH r ^:test-2: true string\\r\\n$ ! done # err_exit # tst $LINENO <<"!" L notify job state changes # 'set -b' should immediately notify the user about job state changes. p :test-1: w set -b; sleep .01 & u Done ! # err_exit # # Tests for 'test -t'. These were moved here from bracket.sh because they require a tty. cat >test_t.sh <<"EOF" integer n redirect {n}< /dev/tty [[ -t $n ]] && echo OK0 || echo "[[ -t n ]] fails when n > 9" # _____ Verify that [ -t 1 ] behaves sensibly inside a command substitution. # This is the simple case that doesn't do any redirection of stdout within # the command substitution. Thus the [ -t 1 ] test should be false. expect=$'begin\nend' actual=$(echo begin; [ -t 1 ] || test -t 1 || [[ -t 1 ]] && echo -t 1 is true; echo end) [[ $actual == "$expect" ]] && echo OK1 || echo 'test -t 1 in comsub fails' \ "(expected $(printf %q "$expect"), got $(printf %q "$actual"))" actual=$(echo begin; [ -n X -a -t 1 ] || test -n X -a -t 1 || [[ -n X && -t 1 ]] && echo -t 1 is true; echo end) [[ $actual == "$expect" ]] && echo OK2 || echo 'test -t 1 in comsub fails (compound expression)' \ "(expected $(printf %q "$expect"), got $(printf %q "$actual"))" # Same for the ancient compatibility hack for 'test -t' with no arguments. actual=$(echo begin; [ -t ] || test -t && echo -t is true; echo end) [[ $actual == "$expect" ]] && echo OK3 || echo 'test -t in comsub fails' \ "(expected $(printf %q "$expect"), got $(printf %q "$actual"))" actual=$(echo begin; [ -n X -a -t ] || test -n X -a -t && echo -t is true; echo end) [[ $actual == "$expect" ]] && echo OK4 || echo 'test -t in comsub fails (compound expression)' \ "(expected $(printf %q "$expect"), got $(printf %q "$actual"))" # This is the more complex case that does redirect stdout within the command # substitution to the actual tty. Thus the [ -t 1 ] test should be true. actual=$(echo begin; exec >/dev/tty; [ -t 1 ] && test -t 1 && [[ -t 1 ]]) \ && echo OK5 || echo 'test -t 1 in comsub with exec >/dev/tty fails' actual=$(echo begin; exec >/dev/tty; [ -n X -a -t 1 ] && test -n X -a -t 1 && [[ -n X && -t 1 ]]) \ && echo OK6 || echo 'test -t 1 in comsub with exec >/dev/tty fails (compound expression)' # Same for the ancient compatibility hack for 'test -t' with no arguments. actual=$(echo begin; exec >/dev/tty; [ -t ] && test -t) \ && echo OK7 || echo 'test -t in comsub with exec >/dev/tty fails' actual=$(echo begin; exec >/dev/tty; [ -n X -a -t ] && test -n X -a -t) \ && echo OK8 || echo 'test -t in comsub with exec >/dev/tty fails (compound expression)' # The broken ksh2020 fix for [ -t 1 ] (https://github.com/att/ast/pull/1083) caused # [ -t 1 ] to fail in non-comsub virtual subshells. ( test -t 1 ) && echo OK9 || echo 'test -t 1 in virtual subshell fails' ( test -t ) && echo OK10 || echo 'test -t in virtual subshell fails' EOF tst $LINENO <<"!" L test -t 1 inside command substitution p :test-1: d 15 w . ./test_t.sh r ^:test-1: \. \./test_t\.sh\r\n$ r ^OK0\r\n$ r ^OK1\r\n$ r ^OK2\r\n$ r ^OK3\r\n$ r ^OK4\r\n$ r ^OK5\r\n$ r ^OK6\r\n$ r ^OK7\r\n$ r ^OK8\r\n$ r ^OK9\r\n$ r ^OK10\r\n$ r ^:test-2: ! # err_exit # tst $LINENO <<"!" L race condition while launching external commands # Test for bug in ksh binaries that use posix_spawn() while job control is active. # See discussion at: https://github.com/ksh93/ksh/issues/79 p :test-1: d 15 w printf '%s\\n' 1 2 3 4 5 | while read; do ls /dev/null; done r ^:test-1: printf '%s\\n' 1 2 3 4 5 | while read; do ls /dev/null; done\r\n$ r ^/dev/null\r\n$ r ^/dev/null\r\n$ r ^/dev/null\r\n$ r ^/dev/null\r\n$ r ^/dev/null\r\n$ r ^:test-2: ! # err_exit # ((SHOPT_ESH)) && [[ -o ?backslashctrl ]] && tst $LINENO <<"!" L nobackslashctrl in emacs d 15 w set -o emacs --nobackslashctrl # --nobackslashctrl shouldn't be ignored by reverse search p :test-2: w \cR\\\cH\cH r ^:test-2: \r\n$ ! # err_exit # ((SHOPT_ESH)) && tst $LINENO <<"!" L emacs backslash escaping d 15 w set -o emacs # Test for too many backslash deletions in reverse-search mode p :test-2: w \cRset\\\\\\\\\cH\cH\cH\cH\cH r ^:test-2: set -o emacs$ # \ should escape the interrupt character (usually Ctrl+C) w true \\\cC r true \^C ! # err_exit # ((SHOPT_VSH)) && touch vi_completion_A_file vi_completion_B_file && tst $LINENO <<"!" L vi filename completion menu d 15 c ls vi_co\t\t r ls vi_completion\r\n$ r ^1) vi_completion_A_file\r\n$ r ^2) vi_completion_B_file\r\n$ w 2\t r ^:test-1: ls vi_completion_B_file \r\n$ r ^vi_completion_B_file\r\n$ # 93v- bug: tab completion writes past input buffer # https://github.com/ksh93/ksh/issues/195 # ...reproducer 1 c ls vi_compl\t\t r ls vi_completion\r\n$ r ^1) vi_completion_A_file\r\n$ r ^2) vi_completion_B_file\r\n$ w aB_file r ^:test-2: ls vi_completion_B_file\r\n$ r ^vi_completion_B_file\r\n$ # ...reproducer 2 c \rls vi_comple\t\t u ls vi_completion\r\n$ r ^1) vi_completion_A_file\r\n$ r ^2) vi_completion_B_file\r\n$ w 0$aA_file r ^:test-3: ls vi_completion_A_file\r\n$ r ^vi_completion_A_file\r\n$ ! # err_exit # tst $LINENO <<"!" L syntax error added to history file # https://github.com/ksh93/ksh/issues/209 d 15 p :test-1: w do something r ^:test-1: do something\r\n$ r : syntax error: `do' unexpected\r\n$ w fc -lN1 r ^:test-2: fc -lN1\r\n$ r \tdo something\r\n$ ! # err_exit # tst $LINENO <<"!" L value of $? after the shell uses a variable with a discipline function w PS1.get() { true; }; PS2.get() { true; }; false u PS1.get\(\) \{ true; \}; PS2.get\(\) \{ true; \}; false w echo "Exit status is: $?" u Exit status is: 1 w LINES.set() { return 13; } u LINES.set\(\) \{ return 13; \} w echo "Exit status is: $?" u Exit status is: 0 # It's worth noting that the test below will always fail in ksh93u+ and ksh2020, # even when $PS2 lacks a discipline function (see https://github.com/ksh93/ksh/issues/117). # After that bug was fixed the test below could still fail if PS2.get() existed. w false w ( w exit w ) w echo "Exit status is: $?" u Exit status is: 1 ! # err_exit # ((SHOPT_ESH)) && ((SHOPT_VSH)) && tst $LINENO <<"!" L crash after switching from emacs to vi mode # In ksh93r using the vi 'r' command after switching from emacs mode could # trigger a memory fault: https://bugzilla.opensuse.org/show_bug.cgi?id=179917 d 15 p :test-1: w exec "$SHELL" -o emacs r ^:test-1: exec "\$SHELL" -o emacs\r\n$ p :test-1: w set -o vi r ^:test-1: set -o vi\r\n$ p :test-2: c \Erri w echo Success r ^:test-2: echo Success\r\n$ r ^Success\r\n$ ! # err_exit # ((SHOPT_VSH || SHOPT_ESH)) && tst $LINENO <<"!" L value of $? after tilde expansion in tab completion # Make sure that a .sh.tilde.set discipline function # cannot influence the exit status. w .sh.tilde.set() { true; } w HOME=/tmp w false ~\t u false /tmp w echo "Exit status is: $?" u Exit status is: 1 w (exit 42) w echo $? ~\t u 42 /tmp ! # err_exit # ((SHOPT_MULTIBYTE && (SHOPT_VSH || SHOPT_ESH))) && [[ ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} =~ [Uu][Tt][Ff]-?8 ]] && touch $'XXX\xc3\xa1' $'XXX\xc3\xab' && tst $LINENO <<"!" L autocomplete should not fill partial multibyte characters # https://github.com/ksh93/ksh/issues/223 d 15 p :test-1: w : XX\t r ^:test-1: : XXX\r\n$ ! # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L Using b, B, w and W commands in vi mode # https://github.com/att/ast/issues/1467 d 15 p :test-1: w set -o vi r ^:test-1: set -o vi\r\n$ w echo asdf\EbwBWa r ^:test-2: echo asdf\r\n$ r ^asdf\r\n$ ! # err_exit # ((SHOPT_ESH)) && mkdir -p emacstest/123abc && VISUAL=emacs tst $LINENO <<"!" L autocomplete stops numeric input # https://github.com/ksh93/ksh/issues/198 d 15 p :test-1: w cd emacste\t123abc r ^:test-1: cd emacstest/123abc\r\n$ ! # err_exit # echo '((' >$tmp/synerror ENV=$tmp/synerror tst $LINENO <<"!" L syntax error in profile causes exit on startup # https://github.com/ksh93/ksh/issues/281 d 15 r /synerror: syntax error: `\(' unmatched\r\n$ p :test-1: w echo ok r ^:test-1: echo ok\r\n$ r ^ok\r\n$ ! # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L split on quoted whitespace when extracting words from command history # https://github.com/ksh93/ksh/pull/291 d 15 p :test-1: w true ls One\\ "Two Three"$'Four Five'.mp3 r ^:test-1: true ls One\\ "Two Three"\$'Four Five'\.mp3\r\n$ p :test-2: w :\E_ r ^:test-2: : One\\ "Two Three"\$'Four Five'\.mp3\r\n$ ! # err_exit # ((SHOPT_VSH)) && tst $LINENO <<"!" L crash when entering comment into history file (vi mode) # https://github.com/att/ast/issues/798 d 15 p :test-1: c foo \E# r ^:test-1: #foo\r\n$ w hist -lnN 1 r ^:test-2: hist -lnN 1\r\n$ r \t#foo\r\n$ r \thist -lnN 1\r\n$ ! # err_exit # ((SHOPT_VSH || SHOPT_ESH)) && tst $LINENO <<"!" L tab completion while expanding ${.sh.*} variables # https://github.com/att/ast/issues/1461 d 15 p :test-1: w test \$\{.sh.level\t r ^:test-1: test \$\{.sh.level\}\r\n$ ! # err_exit # ((SHOPT_VSH || SHOPT_ESH)) && tst $LINENO <<"!" L tab completion executes command substitutions # https://github.com/ksh93/ksh/issues/268 d 15 p :test-1: w $(echo true)\t r ^:test-1: \$\(echo true\)\r\n$ p :test-2: w `echo true`\t r ^:test-2: `echo true`\r\n$ ! # err_exit # ((SHOPT_ESH)) && VISUAL=emacs tst $LINENO <<"!" L emacs: keys with repeat parameters repeat extra steps # https://github.com/ksh93/ksh/issues/292 d 15 p :test-1: w : foo bar delete add\1\6\6\E3\Ed r ^:test-1: : add\r\n$ p :test-2: w : foo bar delete add\E3\Eh r ^:test-2: : foo \r\n$ p :test-3: w : test_string\1\6\6\E3\E[3~ r ^:test-3: : t_string\r\n$ p :test-4: w : test_string\1\E6\E[C\4 r ^:test-4: : teststring\r\n$ ! # ====== exit $((Errors<125?Errors:125))
package com.komorowskidev.tuicodechallenge.githubrepo.api import com.komorowskidev.tuicodechallenge.githubrepo.domain.GithubRepoService import com.komorowskidev.tuicodechallenge.githubrepo.domain.type.Repository import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Flux @RestController @RequestMapping("/api") class GithubRepositoryController(private val githubRepoService: GithubRepoService) { @GetMapping( value = ["users/{userName}/repositories"], produces = [MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE], ) fun getRepositoriesByUserName( @PathVariable userName: String, @RequestHeader("Accept") acceptHeader: String, ): Flux<Repository> { if (acceptHeader.contains(MediaType.APPLICATION_XML_VALUE)) { throw XmlResponseException("Format $acceptHeader is not supported") } return githubRepoService.readRepositories(userName) } }
import React, { useState } from "react" const ToBeDeleted=()=> { // React Hooks declarations const [searches, setSearches] = useState([]) const [query, setQuery] = useState("") const handleClick = () => { // Save search term state to React Hooks // Add the search term to the list onClick of Search button // (Actually searching would require an API call here) // Save search term state to React Hooks setSearches(searches => [...searches, query]) // setSearches(searches => searches.concat(query)) } const updateQuery = ({ target }) => { // Update query onKeyPress of input box setQuery(target.value) } const keyPressed = ({ key }) => { // Capture search on Enter key if (key === "Enter") { handleClick() } } const submitHandler = e => { // Prevent form submission on Enter key e.preventDefault() } const Search = ({ query }) => <li>{query}</li> return ( <div className="App"> <h1>Array.concat() to update state in React</h1> <h2>Previous searches: (React Hooks)</h2> <ul className="previousSearch"> {searches.map((query, i) => ( <Search query={query} // Prevent duplicate keys by appending index: key={query + i} /> ))} </ul> <div className="break" /> <form onSubmit={submitHandler}> <div> <input className="search-field-input" placeholder="Search for..." type="text" onChange={updateQuery} onKeyPress={keyPressed} /> <button className="search-field-button" type="button" onClick={handleClick} > Search </button> </div> </form> </div> ) } export default ToBeDeleted;
import request from 'supertest'; import jwt, { Secret } from 'jsonwebtoken'; import app from '../../app'; import { users } from '../../seeds/inmemDB'; import User from '../../models/dto/User'; import MockDB from '../../services/mockDbservice'; const db = new MockDB(); let adminToken: string; let simpleToken: string; function generateAccessToken(user: User) { const token = jwt.sign( { user, }, process.env.TOKEN_SECRET as Secret, { expiresIn: '1h' } ); return token; } function initializeUserDatabase() { users.push(new User(1, 'first', 'first@gmail.com', 'firstPassword', true)); users.push( new User(2, 'second', 'second@gmail.com', 'secondPassword', false) ); db.setConfigValue(true); adminToken = generateAccessToken(users[0]); simpleToken = generateAccessToken(users[1]); } function clearUserDatabase() { users.splice(0, users.length); } function createAuthToken(user: User) { const token = jwt.sign( { user, }, process.env.TOKEN_SECRET as Secret, { expiresIn: '1h' } ); return token; } beforeAll(() => { clearUserDatabase(); }); beforeEach(() => { initializeUserDatabase(); }); afterEach(() => { clearUserDatabase(); }); test("POST user, can't create admin", async () => { const res = await request(app).post('/api/users').send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', isAdmin: true, }); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.id).toEqual(3); expect(res.body.name).toEqual('random'); expect(res.body.email).toEqual('random@gmail.com'); expect(res.body.password).toEqual('randomPassword'); expect(res.body.isAdmin).toBeFalsy(); }); test('POST user by admin', async () => { const res = await request(app) .post('/api/users') .send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', isAdmin: true, }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.id).toEqual(3); expect(res.body.name).toEqual('random'); expect(res.body.email).toEqual('random@gmail.com'); expect(res.body.password).toEqual('randomPassword'); expect(res.body.isAdmin).toBeTruthy(); }); test('incomplete User POST', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Random', password: 'randomPass', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(400); }); test('incomplete User POST', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Random', password: 'randomPass', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(400); }); test('incomplete User POST, isAdmin missing', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Random', email: 'random@gmail.com', password: 'randomPass', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(400); }); test('GET user by id, user is author', async () => { const res = await request(app) .get('/api/users/2') .set('Authorization', `Bearer ${simpleToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.name).toEqual(users[1].name); expect(res.body.email).toEqual(users[1].email); expect(res.body.password).toEqual(users[1].password); expect(res.body.isAdmin).toBeFalsy(); }); test('GET user by id, user is not admin or author', async () => { const res = await request(app) .get('/api/users/1') .set('Authorization', `Bearer ${simpleToken}`); expect(res.statusCode).toBe(403); }); test('GET user by id, user is admin', async () => { const res = await request(app) .get('/api/users/1') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.name).toEqual(users[0].name); expect(res.body.email).toEqual(users[0].email); expect(res.body.password).toEqual(users[0].password); expect(res.body.isAdmin).toBeTruthy(); }); test('bad GET by id request', async () => { const res = await request(app) .get('/api/users/4') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(404); }); test('GET users, by admin, only 2 users in list', async () => { const res = await request(app) .get('/api/users?page=1&limit=2') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('first'); expect(res.body.result[0].email).toEqual('first@gmail.com'); expect(res.body.result[0].password).toEqual('firstPassword'); expect(res.body.result[0].isAdmin).toBeTruthy(); expect(res.body.result[1].name).toEqual('second'); expect(res.body.result[1].email).toEqual('second@gmail.com'); expect(res.body.result[1].password).toEqual('secondPassword'); expect(res.body.result[1].isAdmin).toBeFalsy(); expect(res.body.hasNext).toBeFalsy(); expect(res.body.hasPrevious).toBeFalsy(); }); test('GET users, by admin, only 2 users in list, limit is 5', async () => { const res = await request(app) .get('/api/users?page=1&limit=5') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('first'); expect(res.body.result[0].email).toEqual('first@gmail.com'); expect(res.body.result[0].password).toEqual('firstPassword'); expect(res.body.result[0].isAdmin).toBeTruthy(); expect(res.body.result[1].name).toEqual('second'); expect(res.body.result[1].email).toEqual('second@gmail.com'); expect(res.body.result[1].password).toEqual('secondPassword'); expect(res.body.result[1].isAdmin).toBeFalsy(); expect(res.body.result[2]).toBeUndefined(); expect(res.body.hasNext).toBeFalsy(); expect(res.body.hasPrevious).toBeFalsy(); }); test('GET users, by admin, only 2 users in list, page 1, limit 1', async () => { const res = await request(app) .get('/api/users?page=1&limit=1') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('first'); expect(res.body.result[0].email).toEqual('first@gmail.com'); expect(res.body.result[0].password).toEqual('firstPassword'); expect(res.body.result[0].isAdmin).toBeTruthy(); expect(res.body.hasNext).toBeTruthy(); expect(res.body.hasPrevious).toBeFalsy(); }); test('GET users, by admin, only 2 users in list, page 2, limit 1', async () => { const res = await request(app) .get('/api/users?page=2&limit=1') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('second'); expect(res.body.result[0].email).toEqual('second@gmail.com'); expect(res.body.result[0].password).toEqual('secondPassword'); expect(res.body.result[0].isAdmin).toBeFalsy(); expect(res.body.hasNext).toBeFalsy(); expect(res.body.hasPrevious).toBeTruthy(); }); test('GET users, by admin, only 2 users in list, page 2, limit 1', async () => { await request(app) .post('/api/users') .send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', isAdmin: false, }) .set('Authorization', `Bearer ${adminToken}`); const res = await request(app) .get('/api/users?page=2&limit=1') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('second'); expect(res.body.result[0].email).toEqual('second@gmail.com'); expect(res.body.result[0].password).toEqual('secondPassword'); expect(res.body.result[0].isAdmin).toBeFalsy(); expect(res.body.hasNext).toBeTruthy(); expect(res.body.hasPrevious).toBeTruthy(); }); test('GET users, middle user in list does not match search', async () => { await request(app) .post('/api/users') .send({ name: 'fi', email: 'zzzz@gmail.com', password: 'randomPassword', isAdmin: false, }) .set('Authorization', `Bearer ${adminToken}`); const res = await request(app) .get('/api/users?page=1&limit=5&name=fi') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('first'); expect(res.body.result[0].email).toEqual('first@gmail.com'); expect(res.body.result[0].password).toEqual('firstPassword'); expect(res.body.result[0].isAdmin).toBeTruthy(); expect(res.body.result[1].name).toEqual('fi'); expect(res.body.result[1].email).toEqual('zzzz@gmail.com'); expect(res.body.result[1].password).toEqual('randomPassword'); expect(res.body.result[1].isAdmin).toBeFalsy(); expect(res.body.hasNext).toBeFalsy(); expect(res.body.hasPrevious).toBeFalsy(); }); test('GET users, name given does not match name or email in list', async () => { const res = await request(app) .get('/api/users?page=1&limit=2&name=SomethingThatIsIncorrect') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result).toEqual([]); expect(res.body.hasNext).toBeFalsy(); expect(res.body.hasPrevious).toBeFalsy(); }); test('GET users, by simple user', async () => { const res = await request(app) .get('/api/users?page=1&limit=5') .set('Authorization', `Bearer ${simpleToken}`); expect(res.statusCode).toBe(403); }); test('search users, by admin', async () => { await request(app) .post('/api/users') .send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', isAdmin: false, }) .set('Authorization', `Bearer ${adminToken}`); await request(app) .post('/api/users') .send({ name: 'notOrm', email: 'notRandtom@gmail.com', password: 'notOrmPassword', isAdmin: false, }) .set('Authorization', `Bearer ${adminToken}`); await request(app) .post('/api/users') .send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', isAdmin: false, }) .set('Authorization', `Bearer ${adminToken}`); const res = await request(app) .get('/api/users/?page=1&limit=2&name=random') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body.result[0].name).toEqual('random'); expect(res.body.result[0].email).toEqual('random@gmail.com'); expect(res.body.result[0].password).toEqual('randomPassword'); expect(res.body.result[0].isAdmin).toBeFalsy(); expect(res.body.result[1].name).toEqual('random'); expect(res.body.result[1].email).toEqual('random@gmail.com'); expect(res.body.result[1].password).toEqual('randomPassword'); expect(res.body.result[1].isAdmin).toBeFalsy(); expect(res.body.result[2]).toBeUndefined(); }); test('PUT change only name information by admin', async () => { const res = await request(app) .put('/api/users/2') .send({ name: 'new name', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('new name'); expect(res.body.email).toEqual('second@gmail.com'); expect(res.body.password).toEqual('secondPassword'); expect(res.body.isAdmin).toBeFalsy(); }); test('PUT change only name information by simple user', async () => { const res = await request(app) .put('/api/users/2') .send({ name: 'new name', }) .set('Authorization', `Bearer ${simpleToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('new name'); expect(res.body.email).toEqual('second@gmail.com'); expect(res.body.password).toEqual('secondPassword'); expect(res.body.isAdmin).toBeFalsy(); }); test('PUT change only email information', async () => { const res = await request(app) .put('/api/users/2') .send({ email: 'newMail@gmail.com', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('second'); expect(res.body.email).toEqual('newMail@gmail.com'); expect(res.body.password).toEqual('secondPassword'); expect(res.body.isAdmin).toBeFalsy(); }); test('PUT change only password information', async () => { const res = await request(app) .put('/api/users/2') .send({ password: 'newPassword', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('second'); expect(res.body.email).toEqual('second@gmail.com'); expect(res.body.password).toEqual('newPassword'); expect(res.body.isAdmin).toBeFalsy(); }); test('PUT change only isAdmin information', async () => { const res = await request(app) .put('/api/users/2') .send({ isAdmin: true, }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('second'); expect(res.body.email).toEqual('second@gmail.com'); expect(res.body.password).toEqual('secondPassword'); expect(res.body.isAdmin).toBeTruthy(); }); test('PUT change only isAdmin information', async () => { const res = await request(app) .put('/api/users/2') .send({ isAdmin: true, }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(200); expect(res.body.name).toEqual('second'); expect(res.body.email).toEqual('second@gmail.com'); expect(res.body.password).toEqual('secondPassword'); expect(res.body.isAdmin).toBeTruthy(); }); test('PUT change all information', async () => { const res = await request(app) .put('/api/users/2') .send({ name: 'something', email: 'something@gmail.com', password: 'somePassword', isAdmin: true, }) .set('Authorization', `Bearer ${adminToken}`); expect(res.body.name).toEqual('something'); expect(res.body.email).toEqual('something@gmail.com'); expect(res.body.password).toEqual('somePassword'); expect(res.body.isAdmin).toBeTruthy(); }); test('incomplete PUT request', async () => { const token = createAuthToken(users[0]); const res = await request(app) .put('/api/posts/1') .set('Authorization', `Bearer ${token}`) .send({}); expect(res.statusCode).toBe(400); }); test('PUT, id is missing', async () => { const res = await request(app) .put('/api/posts') .send({ name: 'something', email: 'something@gmail.com', password: 'somePassword', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(404); }); test('wrong PUT id', async () => { const res = await request(app) .put('/api/posts/4') .send({ name: 'newName', email: 'newMail', }) .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(400); }); test('Delete user successful', async () => { const res = await request(app) .delete('/api/users/2') .set('Authorization', `Bearer ${adminToken}`); expect(res.body[1]).toBeUndefined(); }); test('bad DELETE by wrong ID', async () => { const res = await request(app) .delete('/api/users/4') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(404); }); test('DELETE, id is missing', async () => { const res = await request(app) .delete('/api/users/4') .set('Authorization', `Bearer ${adminToken}`); expect(res.statusCode).toBe(404); }); test('bad GET users', async () => { db.setConfigValue(false); const res = await request(app).get('/api/users'); expect(res.statusCode).toBe(404); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body).toEqual({ error: 'Database is not configured!' }); }); test('bad GET user by id when database is not configured', async () => { db.setConfigValue(false); const res = await request(app).get('/api/users/1'); expect(res.statusCode).toBe(404); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body).toEqual({ error: 'Database is not configured!' }); }); test('bad POST user when database is not configured', async () => { db.setConfigValue(false); const res = await request(app).post('/api/users').send({ name: 'random', email: 'random@gmail.com', password: 'randomPassword', }); expect(res.statusCode).toBe(404); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body).toEqual({ error: 'Database is not configured!' }); }); test('bad PUT user when database is not configured', async () => { db.setConfigValue(false); const res = await request(app).put('/api/users/2').send({ name: 'something', email: 'something@gmail.com', password: 'somePassword', }); expect(res.statusCode).toBe(404); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body).toEqual({ error: 'Database is not configured!' }); }); test('bad DELETE when database is not configured', async () => { db.setConfigValue(false); const res = await request(app).get('/api/users/delete/1'); expect(res.statusCode).toBe(404); expect(res.headers['content-type']).toEqual(expect.stringContaining('json')); expect(res.body).toEqual({ error: 'Database is not configured!' }); });
import React from 'react'; import { Link } from 'react-router-dom'; import { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux' import SearchBar from '../SearchBar/SearchBar'; import { getAllGames, getGenres, setGenreFilter, setOriginFilter, setOrders } from '../../redux/actions'; import './NavBar.css' export default function NavBar() { const dispatch = useDispatch(); const genres = useSelector((state) => state.genres) useEffect(() => { dispatch(getAllGames()) }, []); useEffect(() => { dispatch(getGenres()) }, []); function handleOriginOnChange(e) { dispatch(setOriginFilter(e.target.options[e.target.options.selectedIndex].value)) } function handleGenreOnChange(e) { dispatch(setGenreFilter(e.target.options[e.target.options.selectedIndex].value)) } function handleOrdersOnChange(e) { dispatch(setOrders(e.target.options.selectedIndex)) } return ( <> <div className='container-gf'> <div className='selectors-bar-child'> <SearchBar /> </div> <div className='container-nav-father'> <div className='selectors-child'> <select defaultValue='' onChange={handleGenreOnChange}> <option value=''>genre</option> { genres?.map(g => ( <option value={g.name}> {g.name} </option> )) } </select> <select defaultValue="All" onChange={handleOriginOnChange}> <option value="All">All</option> <option value="Api">RAWG</option> <option value="Db">Data Base</option> </select> <select defaultValue="1" onChange={handleOrdersOnChange}> <option>A-Z</option> <option>Z-A</option> <option>Rating Asc</option> <option>Rating Desc</option> </select> <Link to="/create"> <button>Create your videogame</button> </Link> </div> </div> </div> </> ) }
<!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <title>Node Practice</title> </head> <body> <h1 class="text-center mt-3 mb-3 display-4">Full stack Practice</h1> <p class="text-center mt-3 mb-3 display-6">Form to create products.</p> <!-- Optional JavaScript; choose one of the two! --> <form action="#" id="productForm"> <div class="container w-50 d-flex flex-column gap-3"> <div class="form-floating"> <input type="text" class="form-control" id="title" name="title" placeholder="title" /> <label for="title">Title:</label> </div> <div class="form-floating"> <input type="text" class="form-control" id="description" name="description" placeholder="description" /> <label for="description">Description:</label> </div> <div class="form-floating"> <input type="number" class="form-control" id="price" name="price" placeholder="price" /> <label for="price">Price:</label> </div> <div class="form-floating"> <input type="text" class="form-control" id="category" name="category" placeholder="category" /> <label for="category">Category:</label> </div> <div class="form-floating"> <input type="text" class="form-control" id="image" name="image" placeholder="image" /> <label for="image">Image Url:</label> </div> <div> <button type="submit" class="btn btn-primary" id="submit"> Submit </button> <button type="reset" class="btn btn-primary" id="reset">Reset</button> <a href="./product.html"> <button type="button" class="btn btn-primary" id="products"> All products </button> </a> </div> </div> </form> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous" ></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous" ></script> <!-- my script file --> <script src="./formScript.js"></script> </body> </html>
import UIKit class CommentBottomTextView: UITextView { // MARK: - Properties let placeholderLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 16) //label.font = UIFont(name: "NanumMuGungHwa", size: 25) label.textColor = .darkGray label.text = "댓글을 적어주세요" return label }() // MARK: - LifeCycle override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { self.backgroundColor = .white font = UIFont.systemFont(ofSize: 16) //self.font = UIFont(name: "NanumMuGungHwa", size: 25) self.isScrollEnabled = true //heightAnchor.constraint(equalToConstant: 600).isActive = true //heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height).isActive = true self.addSubview(self.placeholderLabel) self.placeholderLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 8), self.placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 4), //placeholderLabel.anchor(top:topAnchor, left: leftAnchor, paddingTop:8, paddingLeft:4) ]) } // MARK: - Selectors @objc func handleTextInputChange() { placeholderLabel.isHidden = !text.isEmpty // 텍스트의 위치에 레이블을 따라 움직이도록 코드를 추가 // 이동 레이블 (placeholderLabel)을 입력한 텍스트의 위치에 맞게 조정 let topOffset: CGFloat = text.isEmpty ? 8 : 0 let leadingOffset: CGFloat = text.isEmpty ? 4 : 0 UIView.animate(withDuration: 0.2) { self.placeholderLabel.transform = CGAffineTransform(translationX: leadingOffset, y: topOffset) } } func validateText() -> Bool { guard let text = self.text else { return false } let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines) // 텍스트 길이를 180자로 제한 guard trimmedText.count <= 180 else { return false } // 최소 10자 이상이어야 함 return trimmedText.count >= 10 } func showAlert(message: String) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: nil)) if let viewController = self.findViewController() { viewController.present(alertController, animated: true, completion: nil) } } } extension UIResponder { func findViewController() -> UIViewController? { if let viewController = self as? UIViewController { return viewController } else if let next = self.next { return next.findViewController() } else { return nil } } }
import Link from "next/link"; type Props = { title: String; description: String; date: String; slug: String; tags: String[]; }; function SinglePost(props: Props) { const { title, description, date, slug, tags } = props; return ( <Link href={`post/${slug}`}> <div className="p-7"> <div className=""></div> <div className="text-xs">{date}</div> <ul className="flex gap-2 mt-3"> {tags.map((tag, index) => ( <span key={index} className="text-xs px-2 py-1 bg-slate-100 rounded-lg " > {tag} </span> ))} </ul> <h2 className="font-bold mt-4">{title}</h2> </div> <p>{description}</p> </Link> ); } export default SinglePost;
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.wearable; import android.annotation.NonNull; import android.app.wearable.WearableSensingManager; import android.content.ComponentName; import android.os.Binder; import android.os.ParcelFileDescriptor; import android.os.PersistableBundle; import android.os.RemoteCallback; import android.os.ShellCommand; import android.util.Slog; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.time.Duration; final class WearableSensingShellCommand extends ShellCommand { private static final String TAG = WearableSensingShellCommand.class.getSimpleName(); static final TestableCallbackInternal sTestableCallbackInternal = new TestableCallbackInternal(); @NonNull private final WearableSensingManagerService mService; private static ParcelFileDescriptor[] sPipe; WearableSensingShellCommand(@NonNull WearableSensingManagerService service) { mService = service; } /** Callbacks for WearableSensingService results used internally for testing. */ static class TestableCallbackInternal { private int mLastStatus; public int getLastStatus() { return mLastStatus; } @NonNull private RemoteCallback createRemoteStatusCallback() { return new RemoteCallback(result -> { int status = result.getInt(WearableSensingManager.STATUS_RESPONSE_BUNDLE_KEY); final long token = Binder.clearCallingIdentity(); try { mLastStatus = status; } finally { Binder.restoreCallingIdentity(token); } }); } } @Override public int onCommand(String cmd) { if (cmd == null) { return handleDefaultCommands(cmd); } switch (cmd) { case "create-data-stream": return createDataStream(); case "destroy-data-stream": return destroyDataStream(); case "provide-data-stream": return provideDataStream(); case "write-to-data-stream": return writeToDataStream(); case "provide-data": return provideData(); case "get-last-status-code": return getLastStatusCode(); case "get-bound-package": return getBoundPackageName(); case "set-temporary-service": return setTemporaryService(); case "set-data-request-rate-limit-window-size": return setDataRequestRateLimitWindowSize(); default: return handleDefaultCommands(cmd); } } @Override public void onHelp() { PrintWriter pw = getOutPrintWriter(); pw.println("WearableSensingCommands commands: "); pw.println(" help"); pw.println(" Print this help text."); pw.println(); pw.println(" create-data-stream: Creates a data stream to be provided."); pw.println(" destroy-data-stream: Destroys a data stream if one was previously created."); pw.println(" provide-data-stream USER_ID: " + "Provides data stream to WearableSensingService."); pw.println(" write-to-data-stream STRING: writes string to data stream."); pw.println(" provide-data USER_ID KEY INTEGER: provide integer as data with key."); pw.println(" get-last-status-code: Prints the latest request status code."); pw.println(" get-bound-package USER_ID:" + " Print the bound package that implements the service."); pw.println(" set-temporary-service USER_ID [PACKAGE_NAME] [COMPONENT_NAME DURATION]"); pw.println(" Temporarily (for DURATION ms) changes the service implementation."); pw.println(" To reset, call with just the USER_ID argument."); pw.println(" set-data-request-rate-limit-window-size WINDOW_SIZE"); pw.println(" Set the window size used in data request rate limiting to WINDOW_SIZE" + " seconds."); pw.println(" positive WINDOW_SIZE smaller than 20 will be automatically set to 20."); pw.println(" To reset, call with 0 or a negative WINDOW_SIZE."); } private int createDataStream() { Slog.d(TAG, "createDataStream"); try { sPipe = ParcelFileDescriptor.createPipe(); } catch (IOException e) { Slog.d(TAG, "Failed to createDataStream.", e); } return 0; } private int destroyDataStream() { Slog.d(TAG, "destroyDataStream"); try { if (sPipe != null) { sPipe[0].close(); sPipe[1].close(); } } catch (IOException e) { Slog.d(TAG, "Failed to destroyDataStream.", e); } return 0; } private int provideDataStream() { Slog.d(TAG, "provideDataStream"); if (sPipe != null) { final int userId = Integer.parseInt(getNextArgRequired()); mService.provideDataStream(userId, sPipe[0], sTestableCallbackInternal.createRemoteStatusCallback()); } return 0; } private int writeToDataStream() { Slog.d(TAG, "writeToDataStream"); if (sPipe != null) { final String value = getNextArgRequired(); try { ParcelFileDescriptor writePipe = sPipe[1].dup(); OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(writePipe); os.write(value.getBytes()); } catch (IOException e) { Slog.d(TAG, "Failed to writeToDataStream.", e); } } return 0; } private int provideData() { Slog.d(TAG, "provideData"); final int userId = Integer.parseInt(getNextArgRequired()); final String key = getNextArgRequired(); final int value = Integer.parseInt(getNextArgRequired()); PersistableBundle data = new PersistableBundle(); data.putInt(key, value); mService.provideData(userId, data, null, sTestableCallbackInternal.createRemoteStatusCallback()); return 0; } private int getLastStatusCode() { Slog.d(TAG, "getLastStatusCode"); final PrintWriter resultPrinter = getOutPrintWriter(); int lastStatus = sTestableCallbackInternal.getLastStatus(); resultPrinter.println(lastStatus); return 0; } private int setTemporaryService() { final PrintWriter out = getOutPrintWriter(); final int userId = Integer.parseInt(getNextArgRequired()); final String serviceName = getNextArg(); if (serviceName == null) { mService.resetTemporaryService(userId); out.println("WearableSensingManagerService temporary reset. "); return 0; } final int duration = Integer.parseInt(getNextArgRequired()); mService.setTemporaryService(userId, serviceName, duration); out.println("WearableSensingService temporarily set to " + serviceName + " for " + duration + "ms"); return 0; } private int getBoundPackageName() { final PrintWriter resultPrinter = getOutPrintWriter(); final int userId = Integer.parseInt(getNextArgRequired()); final ComponentName componentName = mService.getComponentName(userId); resultPrinter.println(componentName == null ? "" : componentName.getPackageName()); return 0; } private int setDataRequestRateLimitWindowSize() { Slog.d(TAG, "setDataRequestRateLimitWindowSize"); int windowSizeSeconds = Integer.parseInt(getNextArgRequired()); if (windowSizeSeconds <= 0) { mService.resetDataRequestRateLimitWindowSize(); } else { // 20 is the minimum window size supported by the rate limiter. // It is defined by com.android.server.utils.quota.QuotaTracker#MIN_WINDOW_SIZE_MS if (windowSizeSeconds < 20) { windowSizeSeconds = 20; } mService.setDataRequestRateLimitWindowSize(Duration.ofSeconds(windowSizeSeconds)); } return 0; } }
import { Body, Controller, Delete, Get, Param, Post, Query, UploadedFiles, UseInterceptors, } from '@nestjs/common'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { ObjectId } from 'mongoose'; import { AlbumService } from './album.service'; import { CreateAlbumDto } from './dto/create-album.dto'; @Controller('/albums') export class AlbumController { constructor(private albumService: AlbumService) {} @Post() @UseInterceptors(FileFieldsInterceptor([{ name: 'picture', maxCount: 1 }])) create(@UploadedFiles() files, @Body() dto: CreateAlbumDto) { const { picture } = files; return this.albumService.create(dto, picture[0]); } @Post('/update/:id') @UseInterceptors(FileFieldsInterceptor([{ name: 'picture', maxCount: 1 }])) update( @Param('id') id: ObjectId, @UploadedFiles() files, @Body() dto: CreateAlbumDto, ) { let { picture } = files || {}; picture = !picture ? [] : picture; return this.albumService.updateAlbum(id, dto, picture[0]); } @Get() getAll(@Query('count') count: number, @Query('offset') offset: number) { return this.albumService.getAll(count, offset); } @Get('/search') search(@Query('query') query: string) { return this.albumService.search(query); } @Get(':id') getOne(@Param('id') id: ObjectId) { return this.albumService.getOne(id); } @Delete(':id') delete(@Param('id') id: ObjectId) { return this.albumService.delete(id); } }
"use client" import React from "react" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import * as z from "zod" import { newsletter } from "@/lib/airtable" import { cn } from "@/lib/utils" import { Button } from "@/components/ui/button" import { Form, FormControl, FormField, FormItem, FormMessage, } from "@/components/ui/form" import Heading from "@/components/ui/heading" import { Input } from "@/components/ui/input" import { Icons } from "./icons" const formSchema = z.object({ email: z.string().email().min(2, { message: "Username must be at least 2 characters.", }), }) const NewsLetter = () => { const [isLoading, setIsLoading] = React.useState(false) const [isError, setIsError] = React.useState(false) const [isSuccess, setIsSuccess] = React.useState(false) const form = useForm<z.infer<typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues: { email: "", }, }) async function onSubmit(values: z.infer<typeof formSchema>) { setIsLoading(true) setIsError(false) setIsSuccess(false) try { const response = await newsletter.create([ { fields: { Email: values.email, }, }, ]) setIsSuccess(true) setIsLoading(false) form.reset() console.log(response) return response } catch (error) { setIsLoading(false) console.log(error) form.reset() setIsError(true) } } return ( <section className="py-32 border-b bg-black/50 backdrop-blur-sm border-border/20"> <div className="container"> <div className="grid items-end gap-16 md:grid-cols-2"> <div className="space-y-3"> <Heading as="div" className="leading-none tracking-tighter text-left" > Join Our <span className="text-muted">Newsletter </span> &nbsp; {/* todo: add icn like 📨 */} </Heading> <p className="text-muted/80"> Never miss a beat and be the first to receive exciting updates, exclusive offers, and insider content—join our newsletter today and stay connected with us! </p> </div> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-full max-w-xl ml-auto" > <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <div className={cn( "flex items-center w-full gap-2", "rounded-full relative" )} > <FormControl> <Input type="email" placeholder="Your email..." className="h-20 pl-5 pr-32 rounded-3xl border-border/50" {...field} /> </FormControl> <Button type="submit" className="absolute inset-y-4 right-4 rounded-2xl" > {isLoading ? ( <> Submitting...{" "} <Icons.spinner className="w-5 h-5 animate-spin" /> </> ) : ( <span>Subscribe</span> )} </Button> </div> {/* <FormDescription>Enter your country here</FormDescription> */} <FormMessage className="ml-3.5" /> </FormItem> )} /> {/* Alert */} {(isError || isSuccess) && ( <div className={cn( isError && "bg-yellow-200/30 border-yellow-400/80", isSuccess && "bg-green-200/30 border-green-400/80", "text-center text-sm font-medium p-2.5 border rounded-xl mt-3" )} > <p> {isError && "Something went wrong! 😕"} {isSuccess && "Thanks! your message has been sent 🎊"} </p> </div> )} </form> </Form> </div> </div> </section> ) } export default NewsLetter
document.addEventListener('DOMContentLoaded', () => { const chatDisplay = document.getElementById('chat-display'); const messageForm = document.getElementById('message-form'); const messageInput = document.getElementById('message'); const termsModal = document.getElementById('terms-modal'); const agreeCheckbox = document.getElementById('agree-checkbox'); // Show the terms modal on page load termsModal.style.display = 'block'; // Function to close the terms modal window.closeTermsModal = function () { if (agreeCheckbox.checked) { // If the user agrees, hide the modal and proceed termsModal.style.display = 'none'; } else { // If the user doesn't agree, you might want to handle this case (e.g., display an error message) alert('You must agree to the Terms and Conditions to continue.'); } }; const socket = io(); messageForm.addEventListener('submit', function (event) { event.preventDefault(); const messageText = messageInput.value.trim(); if (messageText !== '') { socket.emit('chat message', messageText); messageInput.value = ''; } }); socket.on('chat message', function (message) { displayMessage(message); }); function displayMessage(message) { const messageElement = document.createElement('div'); messageElement.classList.add('message-entry'); messageElement.textContent = `> ${message}`; chatDisplay.appendChild(messageElement); chatDisplay.scrollTop = chatDisplay.scrollHeight; } function displayMessages() { // Clear the chat display chatDisplay.innerHTML = ''; // Get the current timestamp const currentTime = new Date().getTime(); // Display messages from the last hour const lastHourMessages = messages.filter( msg => currentTime - msg.timestamp < 60 * 60 * 1000 ); lastHourMessages.forEach(({ message }) => { const messageElement = document.createElement('div'); messageElement.classList.add('message-entry'); messageElement.textContent = `> ${message}`; chatDisplay.appendChild(messageElement); // Trigger reflow before applying animation void messageElement.offsetWidth; // Apply animation only to the newly added message messageElement.style.animation = 'fadeIn 0.5s ease-in-out forwards'; }); // Scroll to the bottom of the chat display chatDisplay.scrollTop = chatDisplay.scrollHeight; } });
import * as RadixCollapsible from "@radix-ui/react-collapsible"; import { useCallback, useState } from "react"; import { collapsibleContentAnimation } from "./styles.css"; import type { ReactNode } from "react"; export type CollapsibleProps = { /** * Dialog content */ children: ReactNode | Array<ReactNode>; /** * Allow collapsible to act as a controlled component */ isOpen?: boolean; /** * Function called with new state when state changes. */ onOpenChange?: (openState: boolean) => void; /** * Element to use as Dialog trigger. Note: Must accept a ref. */ triggerNode: ReactNode; }; /** * An unstyled, primitive component for creating a collapsible UI element. */ export function Collapsible({ children, isOpen, onOpenChange, triggerNode }: CollapsibleProps) { const [localOpenState, setLocalOpenState] = useState(isOpen); const handleOpenChange = useCallback( (openState: boolean) => { setLocalOpenState(openState); if (onOpenChange) { onOpenChange(openState); } }, [onOpenChange] ); return ( <RadixCollapsible.Root onOpenChange={handleOpenChange} open={localOpenState} > {/** * Allow custom trigger node. Must accept a ref. * ToDo: Figure out a tidy way to require triggerNode to accept ref, * or to wrap triggerNode so it is always able to accept a ref. */} <RadixCollapsible.Trigger asChild>{triggerNode}</RadixCollapsible.Trigger> <RadixCollapsible.Content className={collapsibleContentAnimation}> {children} </RadixCollapsible.Content> </RadixCollapsible.Root> ); }
using System.Collections.Generic; using UnityEngine; using System; using UnityEditor; using AstralCandle.Entity; using System.Linq; using AstralCandle.Animation; using UnityEngine.Events; /* --- This code has has been written by Joshua Thompson (https://joshgames.co.uk) --- --- Copyright ©️ 2024-2025 AstralCandle Games. All Rights Reserved. --- */ public class GameLoop : MonoBehaviour{ public static GameLoop instance; [HideInInspector] public List<EntityStructure> playerStructures = new(); [HideInInspector] public List<Entity> allEntities = new(); #region EDITOR VARIABLES [SerializeField] bool showDebug; [SerializeField] Transform map; [SerializeField] Settings settings; [SerializeField] WaveProfile[] waves; [SerializeField] EntityCharacter humanEntity; [SerializeField] int humansToStartWith = 2; [SerializeField] bool startOnPlay; [SerializeField] UnityEvent Win, Lose; #endregion #region COSMETIC Vector3 previousScale, targetScale; #endregion #region PRIVATE VARIABLES const int NUMBER_OF_SPAWN_DIRECTIONS = 4; // UP, DOWN, LEFT, RIGHT readonly int[] RESOURCE_NODE_DIRECTIONS = new int[4]{0, 90, 180, 270}; int _wave = -1; float _mapScale, previousMapScale; [SerializeField] Pause pauseState; [HideInInspector] public WinLose state; #endregion public float MapScale{ get => _mapScale; private set{ if(value == _mapScale){ return; } _mapScale = value; settings.scaleAnimation.ResetTime(); previousScale = targetScale; targetScale = new(value, map.localScale.y, value); } } /// <summary> /// The concurrent wave we are on /// </summary> public int Wave{ get => _wave; private set{ if(value == _wave){ return; } _wave = value; } } /// <summary> /// The current wave we are playing on /// </summary> public Game CurrentGame{ get; private set; } //--- FUNCTIONS /// <summary> /// Scales the map in size to match the 'TargetScale' vector /// </summary> void PlayMapAnimation(){ float value = settings.scaleAnimation.Play(); map.localScale = Vector3.LerpUnclamped(previousScale, targetScale, value); } public List<Vector3> CalculateResourceSpawnLocations(){ // Calculate resource spawning locations HashSet<Vector3> resourceSpawnLocations = new(); int maxMapSize = (int)Grid.RoundToGrid(MapScale / 2, settings.cellSize) - settings.cellSize; int minMapSize = (int)Grid.RoundToGrid(previousMapScale / 2, settings.cellSize); for(int i = minMapSize; i < maxMapSize; i += settings.cellSize){ for(int x = -i; x < i; x+= settings.cellSize){ resourceSpawnLocations.Add(new(x, 0, i)); resourceSpawnLocations.Add(new(-x, 0, -i)); } for(int z = -i; z < i; z+= settings.cellSize){ resourceSpawnLocations.Add(new(i, 0, z)); resourceSpawnLocations.Add(new(-i, 0, z)); } } System.Random random = new(); return resourceSpawnLocations.OrderBy(e => random.NextDouble()).ToList(); // Shuffles list } public void SpawnEntities(ref List<Vector3> spawnPositions, params Entity[] entities){ Transform parentFolder = GameObject.Find("_GAME_RESOURCES_").transform; spawnPositions ??= CalculateResourceSpawnLocations(); foreach(Entity e in entities){ if(spawnPositions.Count <= 0){ continue; } Vector3 position = spawnPositions[0]; spawnPositions.RemoveAt(0); Entity newE = Instantiate(e, position, Quaternion.identity, parentFolder); PlayerControls.instance.entities.SubscribeToEntities(newE); Collider col = newE.GetComponent<Collider>(); Vector3 newPos = position; newPos.y = (map.localScale.y /2) + col.bounds.extents.y; newE.transform.position = newPos; Vector3 euler = newE.transform.eulerAngles; euler.y = RESOURCE_NODE_DIRECTIONS[UnityEngine.Random.Range(0, RESOURCE_NODE_DIRECTIONS.Length-1)]; newE.transform.eulerAngles = euler; } } public void SpawnEntities(ref List<Vector3> spawnPositions, params ResourceSettings[] settings){ spawnPositions ??= CalculateResourceSpawnLocations(); for(int i = 0; i < settings.Length; i++){ ResourceSettings r = settings[i]; int fillAmount = Mathf.FloorToInt(spawnPositions.Count * r.resourcePopulation); for(int x = 0; x < fillAmount && x < spawnPositions.Count; x++){ SpawnEntities(ref spawnPositions, r.resourceNode); } } } public void NewGame(){ Wave++; MapScale = Utilities.Remap(Wave + 1, 0, waves.Length, settings.mapSize.min, settings.mapSize.max); CurrentGame = new Game(waves[Wave], map.position, MapScale, (Wave + 1).ToString()); // Spawn resources Transform parentFolder = GameObject.Find("_GAME_RESOURCES_").transform; List<Vector3> rLocations = CalculateResourceSpawnLocations(); SpawnEntities(ref rLocations, settings.resources); // Spawn starting humans if(Wave == 0){ for(int i = 0; i < humansToStartWith; i++){ SpawnEntities(ref rLocations, humanEntity); } } } // RUNS ALL ENTITIES private void FixedUpdate() { if(state != WinLose.In_Game || PlayerControls.instance.Paused){ return; } for(int i = allEntities.Count-1; i > -1; i--){ allEntities[i].Run(state); } } void Awake() => instance = this; /// <summary> /// Initiates this script /// </summary> void Start(){ MapScale = Utilities.Remap(Wave + 1, 0, waves.Length, settings.mapSize.min, settings.mapSize.max); previousMapScale = Grid.RoundToGrid((float)settings.mapSize.min * settings.resourceSpawnSubtractMin, settings.cellSize); if(startOnPlay){ NewGame(); } pauseState.Initiate(); } private void Update() { PlayMapAnimation(); pauseState.OnPause(PlayerControls.instance?.Paused == true); if(PlayerControls.instance?.Paused == true){ return; } if((state == WinLose.Win || state == WinLose.Lose) && (Tutorial.instance.CompletedWave || startOnPlay)){ return; } Keep keepInstance = Keep.instance; bool keepExists = keepInstance; bool hasOccupants = false; // Should check all structures List<Entity> s = PlayerControls.instance?.entities.GetAllOfType(Keep.instance as EntityStructure); foreach(Entity structure in s){ EntityStructure thisS = structure as EntityStructure; if(!thisS){ continue; } if(thisS.GetOccupants() >0){ hasOccupants = true; break; } } bool hasHumansOnField = PlayerControls.instance?.entities.GetAllOfType(humanEntity).Count > 0; state = (keepExists && (hasOccupants || hasHumansOnField))? WinLose.In_Game : WinLose.Lose; // If keep exists and we either have occupants OR occupants on field if(Wave >= waves.Length-1 && CurrentGame.CalculateProgress() >= 1){ state = WinLose.Win; Win?.Invoke(); return; } else if(state == WinLose.Lose && (Tutorial.instance.CompletedWave || startOnPlay)){ Lose?.Invoke(); return; } // Ensures the game is always running if(CurrentGame != null && CurrentGame.Run() && Wave < waves.Length-1 && state == WinLose.In_Game){ previousMapScale = MapScale; NewGame(); return; } } private void OnDrawGizmos() { #if UNITY_EDITOR if(!showDebug || !map){ return; } Handles.DrawWireCube(map.position, new Vector3(settings.mapSize.min, map.localScale.y, settings.mapSize.min)); Handles.DrawWireCube(map.position, new Vector3(settings.mapSize.max, map.localScale.y, settings.mapSize.max)); #endif } public enum GameState{ Init, Break, Wave } public enum WinLose{ In_Game, Win, Lose } /// <summary> /// Used to setup each wave /// </summary> public class Game{ #region CLASS_VARIABLES GameState _state; public GameState State{ get => _state; private set{ if(value == _state){ return; } _state = value; ProgressBar.instance.UpdateState(State.ToString()); ProgressBar.instance.UpdateColour((value == GameState.Break)? wave.intermissionColour : wave.waveColour); if(value == GameState.Wave){ ProgressBar.instance.UpdateValue(waveName); ProgressBar.instance.UpdateTarget(0); } } } Vector3 position; float scale; string waveName; float intermission; /// <summary> /// Shows how long the intermission is /// </summary> WaveProfile wave; #region ENTITY COUNTERS /// <summary> /// IDs of the characters /// </summary> public HashSet<int> aliveEntities{ get; private set; } /// <summary> /// The entities remaining for this wave /// </summary> int totalEntities; int _entitiesCleared; /// <summary> /// The number of entities cleared in this wave. | UPDATES THE PROGRESS BAR WHEN SET /// </summary> int EntitiesCleared{ get => _entitiesCleared; set{ _entitiesCleared = value; ProgressBar.instance.UpdateTarget(CalculateProgress()); } } #endregion int spawnGroupIndex; float elapsedSpawnDelay; #endregion /// <summary> /// Constructor to create a new game /// </summary> /// <param name="waveData">Information about this wave</param> /// <param name="position">The base position of the map</param> /// <param name="scale">The map scale so we can spawn the entities on the edges</param> public Game(WaveProfile waveData, Vector3 position, float scale, string waveName = null){ this.wave = waveData; aliveEntities = new(); this.intermission = waveData.intermission; this.totalEntities = waveData.CalculateEntities(); this.spawnGroupIndex = 0; this.EntitiesCleared = 0; this.position = position; this.scale = scale; waveName ??= waveData.name; this.waveName = waveName; } /// <summary> /// Returns the group data of the given index for this wave /// </summary> WaveProfile.SpawnGroupData GetWaveGroup() => wave.waveData[Mathf.Clamp(spawnGroupIndex, 0, wave.waveData.Length-1)]; /// <summary> /// Calculates a position on the edge of the map to spawn an entity /// </summary> /// <returns>The position we should spawn an entity at</returns> Vector3 CalculatePosition(){ int spawnDirection = (int)GetWaveGroup().spawnDirection; bool isHorizontal = spawnDirection == 1 || spawnDirection == 3; float angle = Utilities.CalculateRadianAngle(spawnDirection, NUMBER_OF_SPAWN_DIRECTIONS); Vector3 offset = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * (scale/2); float rndValue = UnityEngine.Random.Range(-1f, 1f); float offsetf = rndValue * scale/3; offset.x = (isHorizontal)? offsetf: offset.x; // Left/Right offset.y = 1.25f; offset.z = (!isHorizontal)? offsetf: offset.z; // Up/Down return position + offset; } /// <summary> /// Spawns an entity on the edge of the map on a given direction /// </summary> /// <param name="character">The entity we wish to spawn</param> void SpawnEntity(EntityCharacter character){ // Spawns the character and adds it to alive entities list aliveEntities.Add( Instantiate( character, CalculatePosition(), Quaternion.identity, GameObject.Find("_GAME_RESOURCES_").transform ).GetInstanceID() ); } /// <summary> /// Attempts to remove the entity from the 'aliveEntities' hashSet so we can see how complete the wave is /// </summary> /// <param name="id">The transform ID of the entity</param> public void RemoveEntity(int id){ if(!aliveEntities.Contains(id)){ return; } aliveEntities.Remove(id); EntitiesCleared++; } /// <summary> /// Calculates wave progression /// </summary> /// <return>Value between 0-1</return> public float CalculateProgress() => Mathf.Clamp01((float)EntitiesCleared / totalEntities); /// <summary> /// Runs this wave; Spawning entities /// </summary> public bool Run(){ if(CalculateProgress() >= 1){ return true; } // Completed wave! intermission -= Time.deltaTime; State = (intermission >0)? GameState.Break : GameState.Wave; switch(State){ case GameState.Break: ProgressBar.instance.UpdateValue(Mathf.Ceil(intermission).ToString()); ProgressBar.instance.UpdateTarget(intermission / wave.intermission); break; case GameState.Wave: // Spawning WaveProfile.SpawnGroupData groupData = GetWaveGroup(); elapsedSpawnDelay -= (elapsedSpawnDelay >0)? Time.deltaTime : 0; if(elapsedSpawnDelay <= 0 && spawnGroupIndex <= wave.waveData.Length-1){ for(int i = 0; i < groupData.quantity; i++){ foreach(IWave _char in groupData.group.entities.Cast<IWave>()){ if(_char == null){ continue; } // Stops any non-'IWave' entites from being spawned SpawnEntity(_char as EntityCharacter); } } elapsedSpawnDelay = groupData.spawnDelay; spawnGroupIndex++; } break; } return false; } } /// <summary> /// The settings which controls this game loop /// </summary> [Serializable] public class Settings{ public AnimationInterpolation scaleAnimation; public Utilities.MinMax mapSize = new(15, 100); [Tooltip("The distance up to the min map scale where we will start to spawn resources"), Range(0, 1)]public float resourceSpawnSubtractMin; public ResourceSettings[] resources; public int cellSize = 1; } [Serializable] public class ResourceSettings{ [Tooltip("The resource we want to spawn")] public EntityResourceNode resourceNode; [Tooltip("The % quantity of this resource which will spawn"), Range(0, 1)] public float resourcePopulation = 0.05f; } /// <summary> /// Maps positions to a grid /// </summary> public static class Grid{ public static float RoundToGrid(float value, int cellSize) => Mathf.RoundToInt(value / cellSize) * cellSize; public static Vector3 RoundToGrid(Vector3 value, int cellSize) => new Vector3(RoundToGrid(value.x, cellSize), RoundToGrid(value.y, cellSize), RoundToGrid(value.z, cellSize)); public static float FloorToGrid(float value, int cellSize) => Mathf.FloorToInt(value / cellSize) * cellSize; public static Vector3 FloorToGrid(Vector3 value, int cellSize) => new Vector3(FloorToGrid(value.x, cellSize), FloorToGrid(value.y, cellSize), FloorToGrid(value.z, cellSize)); } [Serializable] public class Pause{ [Header("SFX Settings")] public AudioSource source; [Range(0, 1)] public float onPauseVolume = 0.05f; [Range(0, 1)] public float onPausePitch = 0.65f; public AnimationInterpolation transitionSettings; [HideInInspector] public float defaultVolume; [HideInInspector] public float defaultPitch; public void Initiate(){ defaultVolume = source.volume; defaultPitch = source.pitch; } public void OnPause(bool isPaused){ float value = transitionSettings.Play(!isPaused); source.volume = Mathf.LerpUnclamped(defaultVolume, onPauseVolume, value); source.pitch = Mathf.LerpUnclamped(defaultPitch, onPausePitch, value); } } [Serializable] public class AudioSettings{ public AudioClip[] type; public Utilities.MinMaxF cooldown; public Utilities.MinMaxF pitch = new Utilities.MinMaxF(1, 1); public float ActualCooldown{ get; set; } public void PlaySound(AudioSource s){ if(ActualCooldown > 0 || type.Length <= 0 || !s) { return; } ActualCooldown = UnityEngine.Random.Range(cooldown.min, cooldown.max); s.clip = type[UnityEngine.Random.Range(0, type.Length)]; s.pitch = UnityEngine.Random.Range(pitch.min, pitch.max); s.Play(); } public void PlaySoundWithIncrease(AudioSource s, float value, float step = -1){ if(ActualCooldown > 0 || type.Length <= 0 || !s) { return; } ActualCooldown = UnityEngine.Random.Range(cooldown.min, cooldown.max); s.clip = type[UnityEngine.Random.Range(0, type.Length)]; float val = Utilities.Remap(Mathf.Clamp01(value), 0, 1, pitch.min, pitch.max); s.pitch = (step > 0)? (float)Math.Round(val / step, 1) * step : val; s.Play(); } } }
import React from 'react'; import { CarContainer, HeaderContainer, LogoContainer, Menu, MenuOpenUser } from './style/HeaderStyle'; import Logo from '../../assets/logo/logo.svg'; import Burger from '../../assets/header/burger.svg'; import { Link } from 'react-router-dom'; import { GlobalContext } from '../../Context/GlobalContext'; import Car from './ComponentsInHeader/Car/Car'; import LoginAndRegisterContainer from './ComponentsInHeader/LoginAndRegisterContainer/LoginAndRegisterContainer'; const Header = () => { const { bag, car, setCar, carUserOpen, setCarUserOpen, localizationContainer, openLoginAndRegisterContainer, setOpenLoginAndRegisterContainer, setLogin, setRegister, setNameRegister, setEmailRegister, setEnderecoRegister, setComplementoRegister, setBairroRegister, setCepRegister, setTelefoneRegister, setEmail, setPassword } = React.useContext(GlobalContext); const [ numberItems, setNumberItems ] = React.useState(''); React.useEffect(()=>{ if(bag.length >= 1){ setCar(true); const totalValuesInArray = []; for(let i = 0; i<bag.length; i++){ totalValuesInArray.push(bag[i].quantidade); } const filterTotalValues = totalValuesInArray.filter(position => position !== undefined); const total = filterTotalValues.reduce((acc, value) => acc + value, 0); setNumberItems(total); } }, [bag, setCar]); const textLoginButton = React.useRef(); function textChange(){ if(textLoginButton.current){ textLoginButton.current.textContent = "Click to enter"; } } function openCarUser(){ setCarUserOpen(!carUserOpen); } function textChangeReverse(){ if(textLoginButton.current){ textLoginButton.current.textContent = "Login"; } } function moveToLocalizacao(){ if(localizationContainer.current){ window.scroll({ top: localizationContainer.current.offsetTop, behavior: "smooth" }) } } function openLoginOrRegister(event){ setCarUserOpen(false); setOpenLoginAndRegisterContainer(true); const textCliqued = event.target.textContent; if(textCliqued === "Cadastre-se Aqui!"){ setLogin(false); setRegister(true); setNameRegister("") setEmailRegister("") setEnderecoRegister("") setComplementoRegister("") setBairroRegister("") setCepRegister("") setTelefoneRegister("") setEmail("") setPassword("") } else{ setRegister(false); setLogin(true); setNameRegister("") setEmailRegister("") setEnderecoRegister("") setComplementoRegister("") setBairroRegister("") setCepRegister("") setTelefoneRegister("") setEmail("") setPassword("") } } return ( <HeaderContainer> <div className="centralizedContainer"> <LogoContainer> <img src={Logo} alt="Logo_Image" title="Food Burger Gourmet" /> </LogoContainer> <MenuOpenUser> <div className="LoginAndSingIn"> <button onMouseOver={textChange} onMouseOut={textChangeReverse} ref={textLoginButton} onClick={openLoginOrRegister} > Login </button> <h5 onClick={openLoginOrRegister}> Cadastre-se Aqui! </h5> { openLoginAndRegisterContainer && ( <LoginAndRegisterContainer /> ) } </div> <CarContainer> <img className="burgerIconCar" src={Burger} alt="My_Burger_Icons" title="My Burger Selected" onClick={openCarUser} /> { car && bag.length >=1 && ( <div className="numberInCar" onClick={openCarUser} > <p>{numberItems}</p> </div> ) } { carUserOpen && bag.length >= 1 && ( <> <div className="detalheContainer"> </div> <Car /> </> ) } </CarContainer> <Menu> <ul> <Link to='/cardapio'> <li>Cardápio</li> </Link> <Link to='restaurante'> <li>Restaurente de Lanche Gourmet</li> </Link> <li onClick={moveToLocalizacao}>Localização</li> <Link to='/contato'> <li>Contato</li> </Link> </ul> </Menu> </MenuOpenUser> </div> </HeaderContainer> ) } export default Header;
// Copyright 2022 - 2023 Wenmeng See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // Author: tickbh // ----- // Created Date: 2023/09/14 09:42:25 use std::{ any::{Any, TypeId}, net::SocketAddr, time::Duration, future::poll_fn, }; use tokio::{ io::{AsyncRead, AsyncWrite}, net::{TcpStream}, }; use webparse::{http::http2::frame::StreamIdentifier, Binary, Request, Response, Serialize, Version, BinaryMut}; use crate::{ ProtError, ProtResult, RecvRequest, RecvStream, ServerH2Connection, TimeoutLayer, OperateTrait, Middleware, }; use super::http1::ServerH1Connection; pub struct Builder { inner: ServerOption, } impl Builder { pub fn new() -> Self { Self { inner: ServerOption::default(), } } pub fn connect_timeout(mut self, connect_timeout: Duration) -> Self { if self.inner.timeout.is_none() { self.inner.timeout = Some(TimeoutLayer::new()); } self.inner.timeout.as_mut().unwrap().connect_timeout = Some(connect_timeout); self } pub fn ka_timeout(mut self, ka_timeout: Duration) -> Self { if self.inner.timeout.is_none() { self.inner.timeout = Some(TimeoutLayer::new()); } self.inner.timeout.as_mut().unwrap().ka_timeout = Some(ka_timeout); self } pub fn read_timeout(mut self, read_timeout: Duration) -> Self { if self.inner.timeout.is_none() { self.inner.timeout = Some(TimeoutLayer::new()); } self.inner.timeout.as_mut().unwrap().read_timeout = Some(read_timeout); self } pub fn write_timeout(mut self, write_timeout: Duration) -> Self { if self.inner.timeout.is_none() { self.inner.timeout = Some(TimeoutLayer::new()); } self.inner.timeout.as_mut().unwrap().write_timeout = Some(write_timeout); self } pub fn timeout(mut self, timeout: Duration) -> Self { if self.inner.timeout.is_none() { self.inner.timeout = Some(TimeoutLayer::new()); } self.inner.timeout.as_mut().unwrap().timeout = Some(timeout); self } pub fn timeout_layer(mut self, timeout: Option<TimeoutLayer>) -> Self { self.inner.timeout = timeout; self } pub fn addr(mut self, addr: SocketAddr) -> Self { self.inner.addr = Some(addr); self } pub fn value(self) -> ServerOption { self.inner } pub fn middle<M: Middleware + 'static>(mut self, middle: M) -> Self { self.inner.middles.push(Box::new(middle)); self } pub fn stream<T>(self, stream: T) -> Server<T> where T: AsyncRead + AsyncWrite + Unpin, { let mut server = Server::new(stream, self.inner.addr); server.set_timeout_layer(self.inner.timeout.clone()); server } } #[derive(Default)] pub struct ServerOption { addr: Option<SocketAddr>, timeout: Option<TimeoutLayer>, middles: Vec<Box<dyn Middleware>>, } pub struct Server<T> where T: AsyncRead + AsyncWrite + Unpin + Sized, { http1: Option<ServerH1Connection<T>>, http2: Option<ServerH2Connection<T>>, middles: Vec<Box<dyn Middleware>>, addr: Option<SocketAddr>, timeout: Option<TimeoutLayer>, req_num: usize, max_req_num: usize, } impl Server<TcpStream> { pub fn builder() -> Builder { Builder::new() } } impl<T> Server<T> where T: AsyncRead + AsyncWrite + Unpin, { pub fn new(io: T, addr: Option<SocketAddr>) -> Self { Self { http1: Some(ServerH1Connection::new(io)), http2: None, middles: vec![], addr, timeout: None, req_num: 0, max_req_num: usize::MAX, } } } impl<T> Server<T> where T: AsyncRead + AsyncWrite + Unpin { pub fn new_by_cache(io: T, addr: Option<SocketAddr>, binary: BinaryMut) -> Self { Self { http1: Some(ServerH1Connection::new_by_cache(io, binary)), http2: None, addr, middles: vec![], timeout: None, req_num: 0, max_req_num: usize::MAX, } } pub fn into_io(self) -> T { if self.http1.is_some() { self.http1.unwrap().into_io() } else { self.http2.unwrap().into_io() } } pub fn set_read_timeout(&mut self, read_timeout: Option<Duration>) { if self.timeout.is_none() { self.timeout = Some(TimeoutLayer::new()); } self.timeout .as_mut() .unwrap() .set_read_timeout(read_timeout); if let Some(http) = &mut self.http1 { http.set_read_timeout(read_timeout); } else if let Some(http) = &mut self.http2 { http.set_read_timeout(read_timeout); } } pub fn set_write_timeout(&mut self, write_timeout: Option<Duration>) { if self.timeout.is_none() { self.timeout = Some(TimeoutLayer::new()); } self.timeout .as_mut() .unwrap() .set_write_timeout(write_timeout); if let Some(http) = &mut self.http1 { http.set_write_timeout(write_timeout); } else if let Some(http) = &mut self.http2 { http.set_write_timeout(write_timeout); } } pub fn set_timeout(&mut self, timeout: Option<Duration>) { if self.timeout.is_none() { self.timeout = Some(TimeoutLayer::new()); } self.timeout.as_mut().unwrap().set_timeout(timeout); if let Some(http) = &mut self.http1 { http.set_timeout(timeout); } else if let Some(http) = &mut self.http2 { http.set_timeout(timeout); } } pub fn set_ka_timeout(&mut self, timeout: Option<Duration>) { if self.timeout.is_none() { self.timeout = Some(TimeoutLayer::new()); } self.timeout.as_mut().unwrap().set_ka_timeout(timeout); if let Some(http) = &mut self.http1 { http.set_ka_timeout(timeout); } else if let Some(http) = &mut self.http2 { http.set_ka_timeout(timeout); } } pub fn set_timeout_layer(&mut self, timeout: Option<TimeoutLayer>) { self.timeout = timeout.clone(); if let Some(http) = &mut self.http1 { http.set_timeout_layer(timeout); } else if let Some(http) = &mut self.http2 { http.set_timeout_layer(timeout); } } pub fn middle<M: Middleware + 'static>(&mut self, middle: M) { self.middles.push(Box::new(middle)); } pub fn get_req_num(&self) -> usize { self.req_num } pub async fn send_response<R>( &mut self, res: Response<R>, stream_id: Option<StreamIdentifier>, ) -> ProtResult<()> where RecvStream: From<R>, R: Serialize, { let _result = if let Some(h1) = &mut self.http1 { h1.send_response(res.into_type::<RecvStream>()).await?; } else if let Some(h2) = &mut self.http2 { if let Some(stream_id) = stream_id { let _recv = RecvStream::only(Binary::new()); let res = res.into_type::<RecvStream>(); h2.send_response(res, stream_id).await?; } }; Ok(()) } pub async fn req_into_type<Req>(mut r: RecvRequest) -> Request<Req> where Req: From<RecvStream>, Req: Serialize + Any, { if TypeId::of::<Req>() == TypeId::of::<RecvStream>() { r.into_type::<Req>() } else { if !r.body().is_end() { let _ = r.body_mut().wait_all().await; } r.into_type::<Req>() } } pub async fn try_wait_req<Req>(r: &mut RecvRequest) -> ProtResult<()> where Req: From<RecvStream>, Req: Serialize, { if !r.body().is_end() { let _ = r.body_mut().wait_all().await; } Ok(()) } pub async fn incoming<F>(&mut self, mut f: F) -> ProtResult<Option<bool>> where F: OperateTrait + Send, { loop { let result = if let Some(h1) = &mut self.http1 { h1.incoming(&mut f, &self.addr, &mut self.middles).await } else if let Some(h2) = &mut self.http2 { h2.incoming(&mut f, &self.addr, &mut self.middles).await } else { Ok(Some(true)) }; match result { Ok(None) | Ok(Some(false)) => { self.req_num = self.req_num.wrapping_add(1); } Err(ProtError::ServerUpgradeHttp2(b, r)) => { if self.http1.is_some() { self.http2 = Some(self.http1.take().unwrap().into_h2(b)); if let Some(r) = r { self.http2 .as_mut() .unwrap() .handle_request(&self.addr, r, &mut f, &mut self.middles) .await?; self.req_num = self.req_num.wrapping_add(1); } } else { return Err(ProtError::ServerUpgradeHttp2(b, r)); } } Err(e) => { for i in 0usize .. self.middles.len() { self.middles[i].process_error(None, &e).await; } return Err(e); } Ok(Some(true)) => return Ok(Some(true)), }; if self.req_num >= self.max_req_num { self.flush().await?; return Ok(Some(true)) } } } pub async fn flush(&mut self) -> ProtResult<()> { if let Some(h1) = &mut self.http1 { let _ = poll_fn(|cx| { h1.poll_write(cx) }).await; } else if let Some(h2) = &mut self.http2 { let _ = poll_fn(|cx| { h2.poll_write(cx) }).await; }; return Ok(()) } pub fn set_max_req(&mut self, num: usize) { self.max_req_num = num; } }
import 'package:flutter/material.dart'; import '../common/mask_layer.dart'; /// 遮罩层 class MaskLayerWidget extends StatelessWidget { const MaskLayerWidget({ super.key, required this.maskLayer, }); final MaskLayer maskLayer; @override Widget build(BuildContext context) { return InkWell( onTap: maskLayer.onTap, child: LayoutBuilder(builder: _builderWidget), ); } Widget _builderWidget(BuildContext context, BoxConstraints constraints) { double width = constraints.maxWidth * maskLayer.percent; double height = constraints.maxHeight; return SizedBox( width: width, height: height, child: maskLayer.widget ?? Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Color(0xFFf7f373), Color(0xFFc5b9ab)], ), ), ), ); } }
--- title: การจัดการภาพ linktitle: การจัดการภาพ second_title: Aspose.Page .NET API description: ค้นพบพลังของ Aspose.Page สำหรับ .NET ผ่านบทช่วยสอนการจัดการรูปภาพของเรา ครอบตัดและปรับขนาดภาพ EPS ได้อย่างง่ายดายเพื่อผลลัพธ์ที่น่าทึ่งและแม่นยำ type: docs weight: 26 url: /th/net/image-manipulation/ --- ## การแนะนำ คุณพร้อมที่จะยกระดับทักษะการจัดการภาพ EPS ใน .NET แล้วหรือยัง? เจาะลึกบทช่วยสอนการจัดการรูปภาพที่ครอบคลุมของเราด้วย Aspose.Page สำหรับ .NET ซึ่งเราจะแนะนำคุณตลอดกระบวนการครอบตัดและปรับขนาดรูปภาพ EPS อย่างราบรื่น ## ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET คุณเบื่อกับการดิ้นรนกับเครื่องมือครอบตัดรูปภาพที่ซับซ้อนหรือไม่? ไม่ต้องมองอีกต่อไป! บทช่วยสอนของเราเกี่ยวกับ "ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET" ให้คำแนะนำทีละขั้นตอนเกี่ยวกับวิธีการสำรวจโลกอันทรงพลังของ Aspose.Page เพื่อครอบตัดรูปภาพ EPS ได้อย่างง่ายดาย ### ปลดปล่อยศักยภาพ Aspose.Page สำหรับ .NET ปลดล็อกโลกแห่งความเป็นไปได้ที่ราบรื่น ช่วยให้คุณสามารถครอบตัดรูปภาพ EPS ได้อย่างแม่นยำ ไม่ว่าคุณจะเป็นมือใหม่หรือนักพัฒนาที่มีประสบการณ์ บทช่วยสอนของเรารองรับทุกระดับทักษะ บอกลากระบวนการที่น่าเบื่อ และพบกับผลลัพธ์อันน่าทึ่ง! ### การปรับขนาดได้อย่างง่ายดาย นำทางกระบวนการปรับขนาดได้อย่างง่ายดายด้วย Aspose.Page เราแนะนำคุณในการบรรลุความแม่นยำในระดับจุด นิ้ว มิลลิเมตร และเปอร์เซ็นต์ บอกลาการบิดเบือนและพบกับภาพ EPS ที่มีขนาดสมบูรณ์แบบซึ่งตรงตามข้อกำหนดของโครงการของคุณ ### เห็นภาพการเปลี่ยนแปลง บทช่วยสอนของเราไม่เพียงแค่สอนเท่านั้น แต่ยังแสดงภาพการเปลี่ยนแปลงอีกด้วย มีส่วนร่วมกับคำอธิบายโดยละเอียด รูปภาพ และตัวอย่างที่ทำให้กระบวนการครอบตัดมีชีวิต ดูผลกระทบของแต่ละขั้นตอนและเพิ่มความมั่นใจในทักษะการจัดการภาพของคุณ ### เพิ่มขั้นตอนการพัฒนาของคุณ Aspose.Page สำหรับ .NET ไม่ได้เป็นเพียงเครื่องมือเท่านั้น มันเป็นตัวเปลี่ยนเกมสำหรับขั้นตอนการพัฒนาของคุณ เรียนรู้วิธีบูรณาการการจัดการภาพอย่างราบรื่น ประหยัดเวลาและความพยายาม ยกระดับโครงการของคุณด้วยภาพ EPS ที่น่าดึงดูดและครอบตัดอย่างแม่นยำ[อ่านเพิ่มเติม](./crop-eps-images/) ## ปรับขนาดภาพ EPS ด้วย Aspose.Page สำหรับ .NET พร้อมที่จะควบคุมขนาดภาพ EPS ของคุณใน .NET แล้วหรือยัง? บทช่วยสอนของเราเกี่ยวกับ "การปรับขนาดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET" ช่วยให้คุณสามารถปรับขนาดรูปภาพได้อย่างแม่นยำ ซึ่งตอบสนองความต้องการเฉพาะของโปรเจ็กต์ของคุณ ### แม่นยำในทุกมิติ Aspose.Page สำหรับ .NET รับประกันความแม่นยำในทุกมิติ ไม่ว่าคุณจะทำงานกับจุด นิ้ว มิลลิเมตร หรือเปอร์เซ็นต์ บทช่วยสอนของเราจะให้ข้อมูลเชิงลึกโดยละเอียดเกี่ยวกับการปรับขนาดที่สมบูรณ์แบบ ไม่มีการคาดเดาอีกต่อไป มีเพียงผลลัพธ์ที่แม่นยำเท่านั้น ### บูรณาการอย่างราบรื่น เรียนรู้วิธีผสานรวม Aspose.Page เข้ากับโปรเจ็กต์ .NET ของคุณได้อย่างราบรื่นเพื่อการปรับขนาดรูปภาพอย่างมีประสิทธิภาพ คำแนะนำทีละขั้นตอนของเราทำให้กระบวนการง่ายขึ้น ทำให้นักพัฒนาทุกระดับสามารถเข้าถึงได้ ยกระดับโปรเจ็กต์ของคุณด้วยรูปภาพที่เข้ากับการออกแบบของคุณได้อย่างลงตัว[อ่านเพิ่มเติม](./resize-eps-images/) สำรวจโลกของ Aspose.Page สำหรับ .NET ด้วยบทช่วยสอนการจัดการรูปภาพของเรา และเปลี่ยนทักษะการจัดการรูปภาพ EPS ของคุณวันนี้! ## บทช่วยสอนการจัดการรูปภาพ ### [ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET](./crop-eps-images/) สำรวจโลกที่ไร้รอยต่อของการจัดการภาพ EPS ใน .NET ด้วย Aspose.Page ครอบตัดและปรับขนาดรูปภาพได้อย่างง่ายดายเพื่อผลลัพธ์ที่น่าทึ่ง ### [ปรับขนาดภาพ EPS ด้วย Aspose.Page สำหรับ .NET](./resize-eps-images/) สำรวจกระบวนการปรับขนาดอิมเมจ EPS ใน .NET ได้อย่างราบรื่นโดยใช้ Aspose.Page ให้ความแม่นยำในระดับจุด นิ้ว มิลลิเมตร และเปอร์เซ็นต์ได้อย่างง่ายดาย
import java.util.Scanner; abstract class shape__{ final double pi=3.14; Scanner sn=new Scanner(System.in); abstract void findArea(); } class Rectangle__ extends shape__{ int l,b; Rectangle__(){ System.out.print("Enter length and breadth : "); l=sn.nextInt(); b=sn.nextInt(); } void findArea(){ System.out.print("\nArea of Rectangle : "+(l*b)); } } class Circle__ extends shape__{ double r; Circle__(){ System.out.print("Enter radius : "); r=sn.nextDouble(); } void findArea(){ System.out.print("\nArea of Circle : "+(pi*r*r)); } } class Square__ extends shape__{ int a; Square__(){ System.out.print("Enter side : "); a=sn.nextInt(); } void findArea(){ System.out.print("\nArea of the Square : "+(a*a)+"\n\n"); } } public class ShapeAbstract { public static void main(String args[]){ System.out.println("Area of Shapes"); Rectangle__ re=new Rectangle__(); Circle__ ci=new Circle__(); Square__ sq=new Square__(); System.out.println("\n_____________RECTANGLE______________"); re.findArea(); System.out.println("\n\n_____________CIRCLE______________"); ci.findArea(); System.out.println("\n\n_____________SQUARE______________"); sq.findArea(); } }
# Retail Example As a result of having to invest in omnichannel capabilities during the pandemic, the retail industry should be better placed to integrate GAI into existing digital platforms. Such integration could be particularly important as companies look for new ways to differentiate and personalise products, while remaining cost-competitive ![Sector deep-dive: Retail and Customer Services](https://raw.githubusercontent.com/rohit-lakhanpal/build-your-own-copilot/main/docs/img/retail-and-customer-services.png) References: [Australia’s Generative AI opportunity Research paper | TechCouncil of Australia](https://techcouncil.com.au/wp-content/uploads/2023/07/230714-Australias-Gen-AI-Opportunity-Final-report-vF4.pdf). | | | | -: | :- | | Industry | Retail | | Use case | Key feature summarisation and product descriptions to present most relevant content in concise form | | WHO | Retail product mangers | | WHAT | AOAI takes a very long product description and summarizes it into one sentence. | | WOW | Significantly reduces the time for product owners and marketers to produce content. | ## Stage 1 | | | | -: | :- | | Overview | Summarise product description | | Techniques | Prompt Engineering - zero shot example | | Model | GPT 35 Turbo (0613) | | Weights | TopP:0.95; Temp:0.7 | **System Prompt** ```text You are an AI assistant that summarises product descriptions. The summary should be limited to one sentence. ``` **User Prompt** ```text For one person Use on up to 5 devices simultaneously Works on PC, Mac, iPhone, iPad, and Android phones and tablets 1 TB (1,000 GB) of secure cloud storage Word, Excel, PowerPoint, and OneNote with offline access and premium features Microsoft Defender advanced security for your personal data and devices OneDrive ransomware protection for your files and photos Outlook ad-free secure email Microsoft Editor advanced spelling, grammar, and writing assistance Clipchamp video editor with premium filters and effects Premium, customizable templates Expanded content library of high-quality photos, icons, fonts, videos, and audio Contact support via chat or email to get help when you need it ``` **Output** ```text Get the ultimate productivity package with Microsoft 365 Personal, including 1TB cloud storage, advanced security features, and premium software for all your devices! ``` ## Stage 2 | | | | -: | :- | | Overview | Summarise product description in the voice of the customer | | Techniques | Prompt Engineering - few shot example | | Model | GPT 35 Turbo (0613) | | Weights | TopP:0.95; Temp:0.7 | **System Prompt** ```text You are an AI assistant that summarises product descriptions. The summary should be limited to one sentence. You can only respond in JSON in the format of {"product description":summarised description} ``` **User Prompt** ```text For one person Use on up to 5 devices simultaneously Works on PC, Mac, iPhone, iPad, and Android phones and tablets 1 TB (1,000 GB) of secure cloud storage Word, Excel, PowerPoint, and OneNote with offline access and premium features Microsoft Defender advanced security for your personal data and devices OneDrive ransomware protection for your files and photos Outlook ad-free secure email Microsoft Editor advanced spelling, grammar, and writing assistance Clipchamp video editor with premium filters and effects Premium, customizable templates Expanded content library of high-quality photos, icons, fonts, videos, and audio Contact support via chat or email to get help when you need it ``` **Output** ```text { "product description": "Microsoft 365 Personal includes 1 TB of secure cloud storage, premium features for Word, Excel, PowerPoint, and OneNote, advanced security for personal data and devices, ad-free secure email, advanced spelling and grammar assistance, and access to a content library of high-quality photos, icons, fonts, videos, and audio." } ```
/** * https://leetcode-cn.com/problems/sort-colors/ * 颜色分类 */ /** * 【冒泡排序】 * ① 从头开始比较每一对相邻元素,如果第1个比第2个大,就交换它们的位置 * 执行完一轮后,最未尾那个元素就是最大的元素 * ② 忽略①中曾经找到的最大元素,重复执行步骤①,直到全部元素有序 */ let sortColors = function sortColors(nums: number[]): void { for (let i = 0; i < nums.length; i++) for (let j = nums.length - 1; j > i; j--) if (nums[j] < nums[j - 1]) [nums[j], nums[j - 1]] = [nums[j - 1], nums[j]] } /** * 【选择排序】 * ① 从序列中找出最大的那个元素,然后与最未尾的元素交换位置 * 执行完一轮后,最未尾的那个元素就是最大的元素 * ② 忽略①中曾经找到的最大元素,重复执行步骤① */ sortColors = function sortColors(nums: number[]): void { for (let i = nums.length - 1; i > 0; i--) { let max = 0 // 最大元素的下标 for (let j = 0; j <= i; j++) max = (nums[max] < nums[j]) ? j : max; [nums[max], nums[i]] = [nums[i], nums[max]] } } /** * 【插入排序】 * ① 在执行过程中,插入排序会将序列分为 2 部分 * 头部是已经排好序的,尾部是待排序的 * ② 从头开始扫描每一个元素 * 每当扫描到一个元素,就将它插入到头部合适的位置,使得头部数据依然保持有序 */ sortColors = function sortColors(nums: number[]): void { for (let i = 0; i < nums.length; i++) { let cur = i; while (cur > 0 && nums[cur] > nums[cur - 1]) { [nums[cur], nums[cur - 1]] = [nums[cur - 1], nums[cur]] cur-- } } } /** * 一次遍历 */ sortColors = function sortColors(nums: number[]): void { let left = 0, right = nums.length - 1 // left 指向第一个非 0 的数 while (nums[left] == 0) left++; // right 指向从后往前第一个非 2 的数 while (nums[right] == 2) right--; let i = left while (i <= right && left <= right) { if (nums[i] == 0) { [nums[left], nums[i]] = [nums[i], nums[left]] left++ i++ } else if (nums[i] == 2) { [nums[right], nums[i]] = [nums[i], nums[right]] right-- } else i++ } }
import React, { Component } from "react"; import { Switch, Route, Redirect } from "react-router-dom"; import { connect } from "react-redux"; import { HomePage } from "../pages/homepage"; import { ShopPage } from "../pages/shop"; import { SignInAndSignUpPage } from "../pages/SignIn_and_SignUp"; import { Header } from "../components/Header"; import { auth, createUserProfileDocument } from "../firebase/firebase.utils"; import { setCurrentUser } from "../redux/user/user.actions"; import "./App.scss"; class App extends Component { // state = { // currentUser: null // }; unsubscribeFromAuth = null; componentDidMount() { const { setCurrentUser } = this.props; this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => { if (userAuth) { const userRef = await createUserProfileDocument(userAuth); userRef.onSnapshot(snapshot => { setCurrentUser({ id: snapshot.id, ...snapshot.data() }); }); } setCurrentUser(userAuth); }); } componentWillUnmount() { this.unsubscribeFromAuth(); } render() { return ( <div className="App"> <Header /> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/shop" component={ShopPage} /> <Route exact path="/signin" render={() => this.props.currentUser ? ( <Redirect to="/" /> ) : ( <SignInAndSignUpPage /> ) } /> </Switch> </div> ); } } const mapStateToProps = ({ user }) => ({ currentUser: user.currentUser }); const mapDispatchToProps = dispatch => ({ setCurrentUser: user => dispatch(setCurrentUser(user)) }); export default connect( mapStateToProps, mapDispatchToProps )(App);
/* eslint-disable key-spacing */ import { AggregateRoot } from '@nestjs/cqrs'; import { LiteralObject, Utils } from '@aurorajs.dev/core'; import { IamRoleId, IamRoleName, IamRoleIsMaster, IamRolePermissionIds, IamRoleAccountIds, IamRoleCreatedAt, IamRoleUpdatedAt, IamRoleDeletedAt, } from './value-objects'; import { IamCreatedRoleEvent } from '../application/events/iam-created-role.event'; import { IamUpdatedRoleEvent } from '../application/events/iam-updated-role.event'; import { IamDeletedRoleEvent } from '../application/events/iam-deleted-role.event'; import { IamPermission } from '@app/iam/permission'; import { IamAccount } from '@app/iam/account'; export class IamRole extends AggregateRoot { id: IamRoleId; name: IamRoleName; isMaster: IamRoleIsMaster; permissionIds: IamRolePermissionIds; accountIds: IamRoleAccountIds; createdAt: IamRoleCreatedAt; updatedAt: IamRoleUpdatedAt; deletedAt: IamRoleDeletedAt; // eager relationship permissions: IamPermission[]; accounts: IamAccount[]; constructor( id: IamRoleId, name: IamRoleName, isMaster: IamRoleIsMaster, permissionIds: IamRolePermissionIds, accountIds: IamRoleAccountIds, createdAt: IamRoleCreatedAt, updatedAt: IamRoleUpdatedAt, deletedAt: IamRoleDeletedAt, permissions?: IamPermission[], accounts?: IamAccount[], ) { super(); this.id = id; this.name = name; this.isMaster = isMaster; this.permissionIds = permissionIds; this.accountIds = accountIds; this.createdAt = createdAt; this.updatedAt = updatedAt; this.deletedAt = deletedAt; // eager relationship this.permissions = permissions; this.accounts = accounts; } static register ( id: IamRoleId, name: IamRoleName, isMaster: IamRoleIsMaster, permissionIds: IamRolePermissionIds, accountIds: IamRoleAccountIds, createdAt: IamRoleCreatedAt, updatedAt: IamRoleUpdatedAt, deletedAt: IamRoleDeletedAt, permissions?: IamPermission[], accounts?: IamAccount[], ): IamRole { return new IamRole( id, name, isMaster, permissionIds, accountIds, createdAt, updatedAt, deletedAt, permissions, accounts, ); } created(role: IamRole): void { this.apply( new IamCreatedRoleEvent( role.id.value, role.name.value, role.isMaster.value, role.permissionIds?.value, role.accountIds?.value, role.createdAt?.value, role.updatedAt?.value, role.deletedAt?.value, ), ); } updated(role: IamRole): void { this.apply( new IamUpdatedRoleEvent( role.id?.value, role.name?.value, role.isMaster?.value, role.permissionIds?.value, role.accountIds?.value, role.createdAt?.value, role.updatedAt?.value, role.deletedAt?.value, ), ); } deleted(role: IamRole): void { this.apply( new IamDeletedRoleEvent( role.id.value, role.name.value, role.isMaster.value, role.permissionIds?.value, role.accountIds?.value, role.createdAt?.value, role.updatedAt?.value, role.deletedAt?.value, ), ); } toDTO(): LiteralObject { return { id: this.id.value, name: this.name.value, isMaster: this.isMaster.value, permissionIds: this.permissionIds?.value, accountIds: this.accountIds?.value, createdAt: this.createdAt?.value, updatedAt: this.updatedAt?.value, deletedAt: this.deletedAt?.value, // eager relationship permissions: this.permissions?.map(item => item.toDTO()), accounts: this.accounts?.map(item => item.toDTO()), }; } // function called to get data for repository side effect methods toRepository(): LiteralObject { return { id: this.id.value, name: this.name.value, isMaster: this.isMaster.value, permissionIds: this.permissionIds?.value, accountIds: this.accountIds?.value, createdAt: this.createdAt?.value, updatedAt: this.updatedAt?.value, deletedAt: this.deletedAt?.value, // eager relationship permissions: this.permissions?.map(item => item.toDTO()), accounts: this.accounts?.map(item => item.toDTO()), }; } }
// // Copyright 2020 Electronic Arts Inc. // // TiberianDawn.DLL and RedAlert.dll and corresponding source code is free // software: you can redistribute it and/or modify it under the terms of // the GNU General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed // in the hope that it will be useful, but with permitted additional restrictions // under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT // distributed with this program. You should have received a copy of the // GNU General Public License along with permitted additional restrictions // with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection /* $Header: /CounterStrike/BAR.H 1 3/03/97 10:24a Joe_bostic $ */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : Command & Conquer * * * * File Name : BAR.H * * * * Programmer : Joe L. Bostic * * * * Start Date : 08/16/96 * * * * Last Update : August 16, 1996 [JLB] * * * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #ifndef BAR_H #define BAR_H /* ** The "bool" integral type was defined by the C++ committee in ** November of '94. Until the compiler supports this, use the following ** definition. */ #ifndef __BORLANDC__ #ifndef TRUE_FALSE_DEFINED #define TRUE_FALSE_DEFINED enum {false=0,true=1}; typedef int bool; #endif #endif #include "fixed.h" /* ** This is a manager for a progress (or other) bargraph. Such a graph consists of a fill ** and a background region. The fill percentage of the bargraph is controlled by an ** update value. The bargraph can be optionally outlined. */ class ProgressBarClass { public: ProgressBarClass(int x, int y, int width, int height, int forecolor, int backcolor, int bordercolor=0); bool Update(fixed value); void Redraw(void) const; private: void Outline(void) const; bool Is_Horizontal(void) const; bool Is_Outlined(void) const {return(BorderColor != 0);} /* ** This is the upper left coordinates of the bargraph. */ int X,Y; /* ** This is the dimensions of the bargraph. */ int Width, Height; /* ** These are the colors to use when drawing the progress bar. */ int BarColor; int BackColor; int BorderColor; /* ** This is the current value of the bargraph. */ fixed CurrentValue; /* ** This is the current value as of the last time the bargraph was rendered. */ fixed LastDisplayCurrent; /* ** If the bargraph has been drawn at least once, then this flag will ** be true. */ unsigned IsDrawn:1; }; #endif
import { v4 as uuidv4 } from 'uuid'; import { comparing, hashing } from '../utils/bcrypto'; import { IUser, IUserUpdate } from '../types/user.type'; import { User } from '../entities/User'; export class UserService { async findAll(): Promise<User[]> { return User.find(); } async delete(id: string): Promise<User | null> { const deletedUser = await User.findOne({ where: { id } }); if (deletedUser) { await User.delete(id); return deletedUser; } return null; } async findByEmail(email: string): Promise<User | null> { return User.findOne({ where: { email } }); } public async createUser({ username, password, email }: IUser) { const existingUser = await this.findByEmail(email); if (existingUser) { return { status: 400, data: null, error: null, message: 'User with this email already exists' }; } const passwordHash = await hashing(password); const token = await hashing(uuidv4()); const encodedToken = Buffer.from(token).toString('base64'); const newUser = User.create({ username, password: passwordHash, email, confirmationToken: token }); await newUser.save(); return { status: 200, data: { email, confirmationToken: encodedToken }, error: null, message: 'User successfully registered' }; } public async loginUser({ password, email }: IUser) { const existingUser = await this.findByEmail(email); if (!existingUser) { return { status: 400, data: null, error: null, message: 'User not exist' }; } const passwordMatched = await comparing(password, existingUser.password); if (!passwordMatched) { return { status: 400, data: null, message: 'Invalid password or email' }; } return { status: 200, data: null, error: null, message: 'User successfully login', id: existingUser.id }; } public userLogout() { try { return { status: 200, data: null, error: null, message: 'User successfully logged out' }; } catch (error) { return { status: 500, data: null, error: 'Server error', message: `We got this error ${error}` }; } } public async changePassword(email: string, { oldPassword, newPassword }: IUserUpdate) { const user = await this.findByEmail(email); if (!user || user === null) { return { status: 404, data: null, error: null, message: 'User not found' }; } const passwordMatched = await comparing(oldPassword, user.password); if (!passwordMatched) { return { status: 400, data: null, error: null, message: 'Invalid password' }; } const passwordHash = await hashing(newPassword); const updatedUser = await User.update({ id: user.id }, { password: passwordHash }); return { status: 200, data: updatedUser, error: null, message: 'Password changed successfully' }; } public async requestResetPassword(email: string) { const user = await this.findByEmail(email); if (!user || user === null) { return { status: 404, data: null, error: null, message: 'User not found' }; } const resetToken = await hashing(uuidv4()); const encodedToken = Buffer.from(resetToken).toString('base64'); user.resetPasswordToken = resetToken; await user.save(); return { status: 200, data: { email: user.email, resetPasswordToken: encodedToken }, error: null, message: 'Password reset token sent successfully' }; } public async resetPassword(resetPasswordToken: string, newPassword: string) { const decodedToken = Buffer.from(resetPasswordToken, 'base64').toString('ascii'); const user = await User.findOne({ where: { resetPasswordToken: decodedToken } }); if (!user) { return { status: 404, data: null, error: null, message: 'User not found' }; } const passwordHash = await hashing(newPassword); user.password = passwordHash; user.resetPasswordToken = ''; await user.save(); return { status: 200, data: null, error: null, message: 'Password change successfully' }; } public async confirmEmail(confirmationToken: string) { try { const decodedToken1 = Buffer.from(confirmationToken, 'base64').toString('ascii'); const user = await User.findOne({ where: { confirmationToken: decodedToken1 } }); if (!user) { return { status: 404, data: null, error: 'User not found', message: 'User not found' }; } user.isEmailConfirmed = true; user.confirmationToken = ''; await user.save(); return { status: 200, data: user, error: null, message: 'Email successfully confirmed' }; } catch (error) { return { status: 400, data: null, error: 'Invalid confirmation token', message: 'Invalid confirmation token' }; } } public async checkAuth() { return { status: 200, data: { isAuthenticated: true }, error: null, message: 'Authentication succes' }; } }
package cn.lzj66.service; import cn.lzj66.dao.ClassesDao; import cn.lzj66.dao.StudentDao; import cn.lzj66.dao.SubjectDao; import cn.lzj66.dao.TaskDao; import cn.lzj66.dao.TaskItemDao; import cn.lzj66.dao.TeacherClassesDao; import cn.lzj66.dao.TeacherDao; import cn.lzj66.entity.Classes; import cn.lzj66.entity.Student; import cn.lzj66.entity.Task; import cn.lzj66.entity.TaskItem; import cn.lzj66.entity.Teacher; import cn.lzj66.request.ListQuestion; import cn.lzj66.request.Subject; import cn.lzj66.response.Question; import cn.lzj66.dao.*; import cn.lzj66.entity.*; import cn.lzj66.request.CreateTask; import cn.lzj66.util.CalculateExp; import cn.lzj66.util.Create; import cn.lzj66.util.InviteCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class TeacherService { @Autowired private ClassesDao classesDao; @Autowired private TeacherClassesDao teacherClassesDao; @Autowired private TaskDao taskDao; @Autowired private TaskItemDao taskItemDao; @Autowired private TeacherDao teacherDao; @Autowired private SubjectDao subjectDao; @Autowired private StudentDao studentDao; /** * 根据用户名获取账号密码 * @param username String * @return Class */ public Teacher getTeacherByUserName(String username){ return teacherDao.getTeacherByName(username); } /** * 根据教师id获取班级列表 * @param teacherId int * @return List */ public List<Classes> getClassList(int teacherId){ return classesDao.getClassByTeacherAndId(teacherId); } /** * 根据班级id获取全部同学 * @param classId int * @return List */ public List<Student> getAllStudentByClassId(int classId){ return studentDao.getSameStudent(classId); } /** * 增加一个老师账号 * @param teacher Class * @return */ public int addTeacher(Teacher teacher){ return teacherDao.addTeacher(teacher); } /** * 增加一个Subject * @param subject * @return */ public int addSubject(Subject subject) { return subjectDao.addSubject(subject); } /** * 添加一个班级 * @param teacherId int 教师id * @param name string 班级名字 * @param desc string 班级描述 * @return */ @Transactional public boolean addClass(int teacherId,String name,String desc){ String uuid = InviteCode.build();//生成一个邀请码 Classes classes = new Classes(); classes.setName(name); classes.setRemark(desc); classes.setUuid(uuid); classesDao.addClass(classes); int classId = classes.getId(); System.out.println(classes.getId()); int res = teacherClassesDao.add(teacherId,classId); if(res >= 1){ return true; }else{ return false; } } @Transactional public boolean addTask(int teacherId , CreateTask question, ListQuestion listQuestion){ Task task = new Task(); task.setClassId(question.getClassId()); task.setTeacherId(teacherId); task.setTitle(question.getTitle()); task.setCount(question.getCount()); task.setDescription(question.getDescription().trim()); task.setEndTime(question.getEndTime()); int row = taskDao.addTask(task); int taskId = task.getId(); List<TaskItem> items = new ArrayList<>(); TaskItem taskItem; for (int i = 0; i < listQuestion.getQuestion().size(); i++) { taskItem = new TaskItem(); taskItem.setQuestion(listQuestion.getQuestion().get(i)); taskItem.setAnswer(listQuestion.getAnswer().get(i)); taskItem.setTaskId(taskId); items.add(taskItem); } int res = taskItemDao.addBatchItem(items); if(res >= 1){ return true; }else{ return false; } } public List<Task> getTaskList(int teacherId){ return taskDao.getListTaskByTeacherId(teacherId); } /** * 创建题目 * @param difficult 难度 * @param type 题目类型 * @param count 数量 * @return List */ public List<Question> createQuestion(int difficult, int type, int count){ List<Question> list = new ArrayList<>(); switch (type){ case 1: CalculateExp calculateExp = new CalculateExp(); Map<String,List<String>> map = calculateExp.build(count, Create.getMaxNumberByDifficult(difficult),Create.getDifficultBySelf(difficult)); List<String> ques = map.get("question"); List<String> answer = map.get("answer"); Question question ; for (int i = 0; i < ques.size(); i++) { question = new Question(); question.setId(i + 1); question.setQuestion(ques.get(i)); question.setAnswer(answer.get(i)); list.add(question); } break; case 2: list = subjectDao.getSubjectByDifficult(difficult,count); break; default: break; } return list; } }
import { lz, lzc } from 'lazy-init' import type { LazyOptions } from '../src/options' const satisfiesOptions = (a: object, b: object, options: LazyOptions) => { const { cache = false, freeze = false } = options expect(Object.isFrozen(a)).toBe(freeze) expect(Object.isFrozen(b)).toBe(freeze) if (cache) { expect(a).toBe(b) } else { expect(a).not.toBe(b) } } describe('correct "lazyOptions" are applied by "lz()" method', () => { test('`{ cache: false, freeze: false }` [default]', () => { const expectedOptions = { cache: false, freeze: false } satisfiesOptions( lz({ foo: 'bar' }, undefined), lz({ foo: 'bar' }, undefined), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, false), lz({ foo: 'bar' }, false), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, {}), lz({ foo: 'bar' }, {}), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: false }), lz({ foo: 'bar' }, { cache: false }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { freeze: false }), lz({ foo: 'bar' }, { freeze: false }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: false, freeze: false }), lz({ foo: 'bar' }, { cache: false, freeze: false }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: undefined, freeze: undefined }), lz({ foo: 'bar' }, { cache: undefined, freeze: undefined }), expectedOptions ) }) test('`{ cache: true, freeze: false }`', () => { const expectedOptions = { cache: true, freeze: false } satisfiesOptions( lz({ foo: 'bar' }, { cache: true, freeze: false }), lz({ foo: 'bar' }, { cache: true, freeze: false }), expectedOptions ) }) test('`{ cache: false, freeze: true }`', () => { const expectedOptions = { cache: false, freeze: true } satisfiesOptions( lz({ foo: 'bar' }, true), lz({ foo: 'bar' }, true), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { freeze: true }), lz({ foo: 'bar' }, { freeze: true }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: false, freeze: true }), lz({ foo: 'bar' }, { cache: false, freeze: true }), expectedOptions ) }) test('`{ cache: true, freeze: true }`', () => { const expectedOptions = { cache: true, freeze: true } satisfiesOptions( lz({ foo: 'bar' }, { cache: true }), lz({ foo: 'bar' }, { cache: true }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: true, freeze: undefined }), lz({ foo: 'bar' }, { cache: true, freeze: undefined }), expectedOptions ) satisfiesOptions( lz({ foo: 'bar' }, { cache: true, freeze: true }), lz({ foo: 'bar' }, { cache: true, freeze: true }), expectedOptions ) }) }) describe('correct "lazyOptions" are applied by "lzc()" method', () => { test('`{ cache: false, freeze: false }`', () => { const expectedOptions = { cache: false, freeze: false } satisfiesOptions( lzc({ foo: 'bar' }, { cache: false }), lzc({ foo: 'bar' }, { cache: false }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: false, freeze: false }), lzc({ foo: 'bar' }, { cache: false, freeze: false }), expectedOptions ) }) test('`{ cache: true, freeze: false }`', () => { const expectedOptions = { cache: true, freeze: false } satisfiesOptions( lzc({ foo: 'bar' }, false), lzc({ foo: 'bar' }, false), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { freeze: false }), lzc({ foo: 'bar' }, { freeze: false }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: undefined, freeze: false }), lzc({ foo: 'bar' }, { cache: undefined, freeze: false }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: true, freeze: false }), lzc({ foo: 'bar' }, { cache: true, freeze: false }), expectedOptions ) }) test('`{ cache: false, freeze: true }`', () => { const expectedOptions = { cache: false, freeze: true } satisfiesOptions( lzc({ foo: 'bar' }, { cache: false, freeze: true }), lzc({ foo: 'bar' }, { cache: false, freeze: true }), expectedOptions ) }) test('`{ cache: true, freeze: true } [default]`', () => { const expectedOptions = { cache: true, freeze: true } satisfiesOptions( lzc({ foo: 'bar' }, undefined), lzc({ foo: 'bar' }, undefined), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, true), lzc({ foo: 'bar' }, true), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, {}), lzc({ foo: 'bar' }, {}), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: true }), lzc({ foo: 'bar' }, { cache: true }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { freeze: true }), lzc({ foo: 'bar' }, { freeze: true }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: undefined, freeze: undefined }), lzc({ foo: 'bar' }, { cache: undefined, freeze: undefined }), expectedOptions ) satisfiesOptions( lzc({ foo: 'bar' }, { cache: true, freeze: true }), lzc({ foo: 'bar' }, { cache: true, freeze: true }), expectedOptions ) }) })
const routes = [ { path: '/', component: () => import('layouts/MainLayout.vue'), children: [ { path: '', component: () => import('pages/IndexPage.vue'), name: 'index', meta: { requiresAuth: true } }, { path: '/item', component: () => import('pages/ItemsPage.vue'), name: 'items', meta: { requiresAuth: true } }, { path: '/login', component: () => import('pages/LoginPage.vue'), name: 'login', meta: { guest: true } }, { path: '/settings', component: () => import('pages/SettingsPage.vue'), name: 'settings', meta: { requiresAuth: true } }, { path: '/item/:id', component: () => import('pages/ItemDetailsPage.vue'), name: 'item-details', meta: { requiresAuth: true } }, { path: '/item/:id/edit', component: () => import('pages/EditItemPage.vue'), name: 'edit-item', meta: { requiresAuth: true } }, { path: '/item/create', component: () => import('pages/CreateItemPage.vue'), name: 'create-item', meta: { requiresAuth: true } }, { path: '/order/:id', component: () => import('pages/OrderDetailsPage.vue'), name: 'order-details', meta: { requiresAuth: true } }, { path: '/round/:id', component: () => import('pages/RoundDetailsPage.vue'), name: 'round-details' }, { path: '/round/:id/payment-methods', component: () => import('pages/RoundPaymentMethodsPage.vue'), name: 'round-payments' }, { path: '/order', component: () => import('pages/OrdersPage.vue'), name: 'orders', meta: { requiresAuth: true } }, { path: '/round', component: () => import('pages/RoundsPage.vue'), name: 'rounds', meta: { requiresAuth: true } }, { path: '/payments', component: () => import('pages/PaymentsPage.vue'), name: 'payments', meta: { requiresAuth: true } }, { path: '/payment/create', component: () => import('pages/CreatePaymentPage.vue'), name: 'create-payment', meta: { requiresAuth: true } }, { path: '/payemnt/:id/edit', component: () => import('pages/EditPaymentPage.vue'), name: 'edit-payment', meta: { requiresAuth: true } }, { path: '/change-password', component: () => import('pages/ChangePasswordPage.vue'), name: 'change-password', meta: { requiresAuth: true } }, { path: '/telegram-bot', component: () => import('pages/TelegramBotSettingPage.vue'), name: 'telegram-bot', meta: { requiresAuth: true } }, { path: '/users', component: () => import('pages/UsersPage.vue'), name: 'users', meta: { requiresAuth: true } }, ] }, // Always leave this as last one, // but you can also remove it { path: '/:catchAll(.*)*', component: () => import('pages/ErrorNotFound.vue') } ] export default routes
<div align="center"> <img width="400px" src="https://github.com/minimal-lang/.github/assets/82233337/802b8cc5-03ba-42f3-bfff-a6808830e434"> # 𝙼𝚒𝚗𝚒𝚖𝚊𝚕 𝙻𝚊𝚗𝚐𝚞𝚊𝚐𝚎 𝙰 𝚗𝚎𝚠 𝚠𝚊𝚢 𝚝𝚘 𝚝𝚑𝚒𝚗𝚔 𝚊𝚋𝚘𝚞𝚝 𝚙𝚛𝚘𝚐𝚛𝚊𝚖𝚖𝚒𝚗𝚐. </div> > #### 𝚀𝚞𝚒𝚌𝚔 𝙰𝚍𝚟𝚒𝚌𝚎 > The language is under heavy development, and you can help us develop it!<br/> > Join our [Discord server](https://discord.gg/F3Uh9W4g), and apply to be a developer (there is a channel explaining how). ### 𝙼𝚎𝚖𝚋𝚎𝚛𝚜 <div align='center'> **Creators:** [@pandasoli](https://github.com/pandasoli) and [@JuniorBecari10](https://github.com/juniorbecari10) </div> <br/> ## 𝙰𝚋𝚘𝚞𝚝 **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** is a compiled, general-purpose programming language with high-level syntax, but low-level control and speed.<br/> The compiler writes the minimum amount of Assembly instructions possible, so that the language reaches the peak of its speed. The language is also very customizable, you can create your own statements or expression nodes, by doing this the code will be more readable and easier to develop and debug. **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** can be changed though plugins that are able to mimic any programming language syntax. <br/> They make possible even the creation of a transpiler from any language to **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**, only with a plugin (for example you can mimic the entire Go or Rust syntax through them). <br/> ## 𝚃𝚑𝚎 𝙲𝚘𝚖𝚙𝚒𝚕𝚎𝚛 The **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** compiler is very fast and its error messages are very helpful.<br/> With **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**, solving compiling errors is easy!<br/> Tom will be your best friend in this journey. ### 𝙼𝚎𝚎𝚝 𝚃𝚘𝚖 Tom will be your best friend while programming in **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**.<br/> He will always help you developing your programs. ``` /\_/\ ( o.o ) Hello! > ^ < ``` He will always be present while creating your **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** project, inside the language's intuitive setup.<br/> Also he will help you solving the compiling errors, giving hints of how to solve them. ## 𝚂𝚢𝚗𝚝𝚊𝚡 Like said before, **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** has a high-level and easy to understand syntax. <br> The keywords are short, but easily readable. Example of a Hello World program: ```rust fn main { println("Hello, World!") } ``` For more information about the syntax or anything related to the language, check out our [Docs](https://github.com/minimal-lang/docs)!<br/> _(they aren't boring long lines of text)._
import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:lets_go_with_me/core/util/network_Info.dart'; import 'package:lets_go_with_me/core/util/shared_preference_util.dart'; import 'package:lets_go_with_me/data/repositories/auth_repo.dart'; import '../../core/util/user_preferences.dart'; part 'auth_state.dart'; class AuthCubit extends Cubit<AuthState> { AuthCubit({required this.authRepo, required this.networkInfo}) : super(AuthInitial()); final AuthRepo authRepo; final NetworkInfo networkInfo; Future<void> requestLoginOtp(String mobNo) async { if (mobNo.length != 10) { emit(AuthError(message: "Kindly enter 10 digit valid mobile number.")); return; } final internetAvailable = await networkInfo.isConnected; if (!internetAvailable) { emit(AuthError(message: "No active internet connection.")); return; } emit(RequestOtpInProgress()); final failureOrOtpRequestResponseModel = await authRepo.requestOtp(mobNo); emit(failureOrOtpRequestResponseModel.fold((failure) { return RequestOtpFailure(); }, (otpRequestResponseModel) { print("lgfjg OTP ${otpRequestResponseModel.otp.toString()}"); SharedPreferenceUtil.instance.setBooleanPreferencesValue(SharedPreferenceUtil.instance.isNewUser, otpRequestResponseModel.isNewUser); SharedPreferenceUtil.instance.setStringPreferenceValue(SharedPreferenceUtil.instance.loginOtp, otpRequestResponseModel.otp.toString()); if (otpRequestResponseModel.userid != null) { SharedPreferenceUtil.instance.setStringPreferenceValue(SharedPreferenceUtil.instance.userId, otpRequestResponseModel.userid!); } return RequestOtpSuccess(); })); } Future<void> verifyLoginOtp(String otp) async { emit(VerifyOtpInProgress()); final verifyOtpSuccess = await authRepo.verifyOtp(otp); if (verifyOtpSuccess) { emit(VerifyOtpSuccess()); } else { emit(VerifyOtpFailure()); } } }
<script setup lang="ts"> import { computed } from 'vue' interface Gradient { '0%'?: string '100%'?: string from?: string to?: string direction?: 'right'|'left' } interface Props { width?: number|string // 进度条总宽度 percent?: number // 当前进度百分比 strokeColor?: string|Gradient // 进度条的色彩,传入 string 时为纯色,传入 object 时为渐变 strokeWidth?: number // 进度条线的宽度,单位px showInfo?: boolean // 是否显示进度数值或状态图标 format?: Function // 内容的模板函数 function | slot type?: 'line'|'circle' // 进度条类型 } const props = withDefaults(defineProps<Props>(), { width: '100%', percent: 0, strokeColor: '#1677FF', strokeWidth: 8, showInfo: true, format: (percent: number) => percent + '%', type: 'line' }) const totalWidth = computed(() => { // 进度条总宽度 if (typeof props.width === 'number') { return props.width + 'px' } else { return props.width } }) const perimeter = computed(() => { // 圆条周长 return (100 - props.strokeWidth) * Math.PI }) const path = computed(() => { // 圆条轨道路径指令 const long = (100 - props.strokeWidth) return `M 50,50 m 0,-${(long / 2)} a ${(long / 2)},${(long / 2)} 0 1 1 0,${long} a ${(long / 2)},${(long / 2)} 0 1 1 0,-${long}` }) const lineColor = computed(() => { if (typeof props.strokeColor === 'string') { return props.strokeColor } else { return `linear-gradient(to ${props.strokeColor.direction || 'right'}, ${props.strokeColor['0%'] || props.strokeColor.from}, ${props.strokeColor['100%'] || props.strokeColor.to})` } }) const showPercent = computed(() => { return props.format(props.percent > 100 ? 100 : props.percent) }) </script> <template> <div v-if="type==='line'" class="m-progress-line" :style="`width: ${totalWidth}; height: ${strokeWidth < 24 ? 24 : strokeWidth}px;`"> <div class="m-progress-inner"> <div :class="['u-progress-bg', {'u-success-bg': percent >= 100}]" :style="`background: ${lineColor}; width: ${percent >= 100 ? 100 : percent}%; height: ${strokeWidth}px;`"></div> </div> <template v-if="showInfo"> <Transition mode="out-in"> <span v-if="percent >= 100" class="m-success"> <svg focusable="false" class="u-icon" data-icon="check-circle" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"></path></svg> </span> <p class="u-progress-text" v-else> <slot name="format" :percent="percent">{{ showPercent }}</slot> </p> </Transition> </template> </div> <div v-else class="m-progress-circle" :style="`width: ${totalWidth}; height: ${totalWidth};`"> <svg class="u-progress-circle" viewBox="0 0 100 100"> <path :d="path" stroke-linecap="round" class="u-progress-circle-trail" :stroke-width="strokeWidth" :style="`stroke-dasharray: ${perimeter}px, ${perimeter}px;`" fill-opacity="0"></path> <path :d="path" stroke-linecap="round" class="u-progress-circle-path" :class="{success: percent >= 100}" :stroke-width="strokeWidth" :stroke="lineColor" :style="`stroke-dasharray: ${(percent / 100) * perimeter}px, ${perimeter}px;`" :opacity="percent === 0 ? 0 : 1" fill-opacity="0"></path> </svg> <template v-if="showInfo"> <Transition mode="out-in"> <svg v-if="percent >= 100" class="u-icon" focusable="false" data-icon="check" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path></svg> <p class="u-progress-text" v-else> <slot name="format" :percent="percent">{{ showPercent }}</slot> </p> </Transition> </template> </div> </template> <style lang="less" scoped> .v-enter-active, .v-leave-active { transition: opacity 0.2s; } .v-enter-from, .v-leave-to { opacity: 0; } @success: #52C41A; .m-progress-line { display: flex; align-items: center; .m-progress-inner { width: 100%; background: #f5f5f5; border-radius: 100px; .u-progress-bg { position: relative; background-color: #1677FF; border-radius: 100px; transition: all .3s cubic-bezier(0.78, 0.14, 0.15, 0.86); &::after { content: ""; background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(255, 255, 255, .5) 100%); animation: progressRipple 2s cubic-bezier(.4, 0, .2, 1) infinite; } @keyframes progressRipple { 0% { position: absolute; inset: 0; right: 100%; opacity: 1; } 66% { position: absolute; inset: 0; opacity: 0; } 100% { position: absolute; inset: 0; opacity: 0; } } } .u-success-bg { background: @success !important; } } .m-success { width: 40px; text-align: center; display: inline-flex; align-items: center; padding-left: 8px; flex-shrink: 0; // 默认 1.即空间不足时,项目将缩小 .u-icon { display: inline-block; width: 16px; height: 16px; fill: @success; } } .u-progress-text { /* 如果所有项目的flex-shrink属性都为1,当空间不足时,都将等比例缩小 如果一个项目的flex-shrink属性为0,其他项目都为1,则空间不足时,前者不缩小。 */ flex-shrink: 0; // 默认 1.即空间不足时,项目将缩小 width: 40px; font-size: 14px; padding-left: 8px; color: rgba(0, 0, 0, .88); } } .m-progress-circle { display: inline-block; position: relative; .u-progress-circle { .u-progress-circle-trail { stroke: #f5f5f5; stroke-dashoffset: 0; transition: stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s ease 0s, stroke-width .06s ease .3s, opacity .3s ease 0s; } .u-progress-circle-path { stroke-dashoffset: 0; transition: stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s ease 0s, stroke-width .06s ease .3s, opacity .3s ease 0s; } .success { stroke: @success !important; } } .u-icon { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: inline-block; width: 30px; height: 30px; fill: @success; } .u-progress-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; font-size: 27px; line-height: 1; text-align: center; color: rgba(0, 0, 0, .85); } } </style>
import React, { useState } from "react"; import axios from "axios"; import { Link, useNavigate } from "react-router-dom"; export default function AddStaff() { let navigate = useNavigate(); const [staff, setStaff] = useState({ first_name: "", last_name: "", phone_number: "", email: "", role: "", description: "", }); const { first_name, last_name, phone_number, email, role, description } = staff; const onInputChange = (e) => { setStaff({ ...staff, [e.target.name]: e.target.value }); }; const onSubmit = async (e) => { e.preventDefault(); await axios.post("http://localhost:8080/staff", staff); //To POST info into the data base by using axios navigate("/allstaff"); //To redirect to home page }; return ( <div className="container"> <div className="row"> <div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow"> <h2 className="text-center m-4">Edit Staff</h2> <form onSubmit={(e) => onSubmit(e)}> <div className="mb-3"> <label htmlFor="Name" className="form-label"> Name </label> <input type={"text"} className="form-control" placeholder="Enter name" name="first_name" value={first_name} onChange={(e) => onInputChange(e)} /> </div> <div className="mb-3"> <label htmlFor="Surname" className="form-label"> Surname </label> <input type={"text"} className="form-control" placeholder="Enter surname" name="last_name" value={last_name} onChange={(e) => onInputChange(e)} /> </div> <div className="mb-3"> <label htmlFor="Phone_number" className="form-label"> Phone Number </label> <input type={"text"} className="form-control" placeholder="Enter phone number" name="phone_number" value={phone_number} onChange={(e) => onInputChange(e)} /> </div> <div className="mb-3"> <label htmlFor="Email" className="form-label"> Email </label> <input type={"email"} className="form-control" placeholder="Enter email address" name="email" value={email} onChange={(e) => onInputChange(e)} /> </div> <div className="mb-3"> <label htmlFor="Role" className="form-label"> Role </label> <input type={"text"} className="form-control" placeholder="Enter role" name="role" value={role} onChange={(e) => onInputChange(e)} /> </div> <div className="mb-3"> <label htmlFor="description" className="form-label"> Description </label> <input type={"text"} className="form-control" placeholder="Enter Description" name="description" value={description} onChange={(e) => onInputChange(e)} /> </div> <button type="submit" className="btn btn-outline-primary"> Submit </button> <Link className="btn btn-outline-danger mx-2" to="/allstaff"> Cancel </Link> </form> </div> </div> </div> ); }
import React, { useEffect, useState } from 'react'; import { fetchUser, fetchTrips } from "../api.js"; import { Link, useNavigate } from "react-router-dom"; import Navbar from "../components/Navbar/Navbar.jsx"; import Footer from "../components/Footer/Footer.jsx"; import TrajetProfil from '../components/Trajets/TrajetProfil.jsx'; import './style/Profil.css'; function Profil() { const [auth, setAuth] = useState(false); const [email, setEmail] = useState(''); //Tableau des trajets de l'utilisateur const [trips, setTrips] = useState([]); useEffect(() => { fetchUser() .then(res => { if(res.data.Status === "Success") { setAuth(true); setEmail(res.data.email); // navigate('/'); //Afficher les trajets de l'utilisateur connecté fetchTrips() .then(res => { setTrips(res.data); console.log(res.data); }) .then(err => console.log(err)); } else { setAuth(false); setMessage(res.data.Error); } }) .then(err => console.log(err)); }, []); return ( <div id="profile-page"> <Navbar /> <section id='section-profil'> <div className="container-profil"> <div className='grid-container'> <div class="container" id="info-personnelles"> <h3>Infos personnelles</h3> <div className='container-content'> <div class='infos-utilisateur'> <p>Océane H.</p> <p>Session : CDA31 23-01</p> <button>Modifier la photo de profil</button> </div> <div className='img-utilisateur'> <img src="" alt="" /> </div> </div> </div> <div class="container" id="biographie"> <h3>Biographie</h3> <div className='container-content'> <div> <p>Bonjour, moi c’est Laura. Je recherche une ou plusieurs personnes pour faire du covoiturage depuis Blagnac. </p> <button>Modifier ma bio</button> </div> </div> </div> <div class="container" id="trajets-crees"> <h3>Mes trajets</h3> <div className='list-trajets'> { trips.length > 0 ? <ul> {trips.map(trip => ( <TrajetProfil key={trip.id} adresse_depart={trip.adresse_depart} adresse_arrivee={trip.adresse_arrivee} date={trip.date}/> ))} </ul> : <p>Vous n'avez aucun trajet</p> } </div> </div> <div class="container" id="badges-gagnes"> <h3>Mes badges</h3> </div> {/* <h3>Bonjour {name}</h3> <p>Votre mail : {email}</p> { trips.length > 0 ? <ul> {trips.map(trip => ( <li key={trip.id}> <p>Adresse de départ : {trip.adresse_depart}</p> <p>Adresse d'arrivée : {trip.adresse_arrivee}</p> <p>Date : {trip.date}</p> <p>Nombre de places : {trip.number_place}</p> </li> ))} </ul> : <p>Vous n'avez aucun trajet</p> } */} </div> {/* <Link to="/login" onClick={handleLogOut}>Déconnexion</Link> */} </div> </section> <Footer /> </div> ) } export default Profil
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2024, Benoit BLANCHON // MIT License #include <ArduinoJson.h> #include <catch.hpp> #include <sstream> #define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression); #define SHOULD_FAIL(expression) \ REQUIRE(DeserializationError::TooDeep == expression); TEST_CASE("JsonDeserializer nesting") { JsonDocument doc; SECTION("Input = const char*") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeMsgPack(doc, "\xA1H", nesting)); // "H" SHOULD_FAIL(deserializeMsgPack(doc, "\x90", nesting)); // [] SHOULD_FAIL(deserializeMsgPack(doc, "\x80", nesting)); // {} } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeMsgPack(doc, "\x90", nesting)); // {} SHOULD_WORK(deserializeMsgPack(doc, "\x80", nesting)); // [] SHOULD_FAIL(deserializeMsgPack(doc, "\x81\xA1H\x80", nesting)); // {H:{}} SHOULD_FAIL(deserializeMsgPack(doc, "\x91\x90", nesting)); // [[]] } } SECTION("char* and size_t") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeMsgPack(doc, "\xA1H", 2, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, "\x90", 1, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, "\x80", 1, nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeMsgPack(doc, "\x90", 1, nesting)); SHOULD_WORK(deserializeMsgPack(doc, "\x80", 1, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, "\x81\xA1H\x80", 4, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, "\x91\x90", 2, nesting)); } } SECTION("Input = std::string") { using std::string; SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeMsgPack(doc, string("\xA1H"), nesting)); SHOULD_FAIL(deserializeMsgPack(doc, string("\x90"), nesting)); SHOULD_FAIL(deserializeMsgPack(doc, string("\x80"), nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeMsgPack(doc, string("\x90"), nesting)); SHOULD_WORK(deserializeMsgPack(doc, string("\x80"), nesting)); SHOULD_FAIL(deserializeMsgPack(doc, string("\x81\xA1H\x80"), nesting)); SHOULD_FAIL(deserializeMsgPack(doc, string("\x91\x90"), nesting)); } } SECTION("Input = std::istream") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); std::istringstream good("\xA1H"); // "H" std::istringstream bad("\x90"); // [] SHOULD_WORK(deserializeMsgPack(doc, good, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); std::istringstream good("\x90"); // [] std::istringstream bad("\x91\x90"); // [[]] SHOULD_WORK(deserializeMsgPack(doc, good, nesting)); SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting)); } } }
# KaziNasi KaziNasi is a web application designed to connect individuals seeking casual labor with available workers in their local area. The platform aims to simplify the process of finding and hiring workers for short-term tasks such as cleaning, gardening, moving, and more. ## Table of Contents - [Introduction](#introduction) - [Features](#features) - [Technologies Used](#technologies-used) - [Installation](#installation) - [Usage](#usage) - [Deployment](#deployment) - [Contributing](#contributing) - [License](#license) ## Introduction Finding reliable and available help for short-term tasks can be challenging. KaziNasi bridges this gap by providing a platform where individuals can easily find workers for their specific needs. Whether you're a homeowner looking for someone to help with yard work or a business owner in need of extra hands for a one-time project, KaziNasi can help you find the right person for the job. ## Features - **User Authentication**: Users can create accounts, log in, and manage their profiles. - **Worker Profiles**: Workers can create detailed profiles showcasing their skills, experience, availability, and rates. - **Client Profiles**: Clients can create profiles and post job listings detailing the tasks they need help with. - **Job Matching**: KaziNasi uses a matching algorithm to connect workers with relevant job listings based on their skills and availability. - **Messaging System**: Users can communicate with each other through a built-in messaging system to discuss job details, negotiate terms, and more. - **Rating and Review System**: Clients can rate workers based on their performance, and workers can rate clients based on their experience, helping to build trust within the community. - **Geolocation**: The platform utilizes geolocation to show users nearby workers and job listings, making it easier to find local opportunities. - **Notifications**: Users receive notifications for new messages, job matches, and other relevant updates. ## Technologies Used - **Frontend**: The frontend of KaziNasi is built using Flutter, a cross-platform framework for building native interfaces for iOS, Android, and the web. - **Backend**: The backend is powered by Node.js, a JavaScript runtime built on Chrome's V8 JavaScript engine. - **Database**: MySQL is used as the database to store user profiles, job listings, messages, and reviews. - **Web Server**: Nginx is used as the web server to serve the Flutter web app and handle incoming requests. - **Authentication**: Firebase Authentication is used to manage user authentication and authorization, ensuring that only authenticated users can access the platform. ## Installation To run KaziNasi locally, follow these steps: 1. Clone the repository: ```sh git clone https://github.com/kelvinthuo999/KaziNasi ``` 2. Navigate to the project directory: ```sh cd KaziNasi ``` 3. Install dependencies: ```sh flutter pub get ``` 4. Set up the Node.js backend: Follow the instructions in the `backend/README.md` file to set up and run the Node.js backend. 5. Run the app: ```sh flutter run -d chrome ``` ## Usage Once the app is running, you can use it to: - Create a user account as a worker or client. - Fill out your profile with relevant information. - Browse job listings or create a new job listing if you're a client. - Apply for jobs if you're a worker. - Communicate with other users through the messaging system. - Rate and review other users based on your experience. ## Deployment To deploy KaziNasi to a live server, follow these steps: 1. Set up a server: You'll need a server running Nginx, Node.js, and MySQL to deploy the backend of KaziNasi. 2. Deploy the frontend: Use a web hosting service (e.g., Firebase Hosting, Netlify) to deploy the Flutter web app frontend. 3. Configure the backend: Update the frontend configuration (e.g., API endpoints) to point to your deployed backend. 4. Access the app: Once deployed, the KaziNasi web app will be accessible via any browser. ## Contributing Contributions to KaziNasi are welcome! If you'd like to contribute to the project, please fork the repository and submit a pull request with your changes.
import { StyleSheet, View } from "react-native"; import Text from "../utils/Text.jsx"; import React from "react"; import theme from "../../theme.js"; import ReviewActions from "./ReviewActions.jsx"; const styles = StyleSheet.create({ circle: { alignItems: "center", justifyContent: "center", borderRadius: 50 / 2, width: 50, height: 50, borderColor: theme.colors.primary, borderWidth: 2, }, }); const ReviewItem = ({ review, currentUser }) => { return ( <View style={{ flexDirection: "column", padding: "5%" }}> <View style={{ flexDirection: "row" }}> <View style={styles.circle}> <Text fontWeight={"bold"} fontSize={"subheading"} color={"primary"}> {review.rating} </Text> </View> <View style={{ marginLeft: "5%", flexShrink: 1 }}> <View style={{ paddingBottom: 10 }}> <Text testID={"reviewAuthor"} fontWeight={"bold"} fontSize={"subheading"} > {currentUser ? review.repository.fullName : review.user.username} </Text> <Text testID={"reviewDate"} fontSize={"body"} color={"textSecondary"} > {review.createdAt} </Text> </View> <View style={{ flexShrink: 1 }}> <Text testID={"reviewText"}>{review.text}</Text> </View> </View> </View> {currentUser ? <ReviewActions review={review} /> : null} </View> ); }; export default ReviewItem;
const mangasData = require("../../infrastructure/mangas/data"); import { IMangaRepository } from "../../domain/repository/MangaRepository"; import { Manga } from "@/domain/entity/manga/model"; export class Mangas { constructor(readonly mangaRepository: IMangaRepository) {} public async getAllMangas(): Promise<any> { try { return await this.mangaRepository.getAllMangas(); } catch (error) { return "Erro ao buscar os mangas: " + error; } } public async getManga(idManga: number): Promise<any> { try { return await this.mangaRepository.getManga(idManga); } catch (error) { return "Erro ao buscar o manga: " + error; } } public async createManga(manga: Manga): Promise<any> { try { return await this.mangaRepository.createManga(manga); } catch (error) { return "Erro ao criar o manga: " + error; } } public async updateManga(idManga: number, manga: Manga): Promise<any> { try { return await this.mangaRepository.updateManga(idManga, manga); } catch (error) { return "Erro ao atualizar o manga: " + error; } } public async deleteManga(idManga: number): Promise<any> { try { return await this.mangaRepository.deleteManga(idManga); } catch (error) { return "Erro ao deletar o manga: " + error; } } }
package com.study.security_bosung.web.controller.api; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.ContentDisposition; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.study.security_bosung.service.notice.NoticeService; import com.study.security_bosung.web.dto.CMRespDto; import com.study.security_bosung.web.dto.notice.AddNoticeReqDto; import com.study.security_bosung.web.dto.notice.GetNoticeListResponseDto; import com.study.security_bosung.web.dto.notice.GetNoticeResponseDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/api/v1/notice") @Slf4j @RequiredArgsConstructor public class NoticeRestController { // 파일의 경로를 변수처럼 사용할 수 있음 @Value("${file.path}") private String filePath; private final NoticeService noticeService; @GetMapping("/list/{page}") public ResponseEntity<?> getNoticeList(@PathVariable int page, @RequestParam String searchFlag, @RequestParam String searchValue) { List<GetNoticeListResponseDto> listDto = null; try { listDto = noticeService.getNoticeList(page, searchFlag, searchValue); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.internalServerError().body(new CMRespDto<>(-1, "datavase error", listDto)); } return ResponseEntity.ok(new CMRespDto<>(1, "lookup successful", listDto)); } @PostMapping("") public ResponseEntity<?> addNotice(AddNoticeReqDto addNoticeReqDto) { log.info(">>>>>>{}", addNoticeReqDto); log.info(">>>>>> fileName: {}", addNoticeReqDto.getFile().get(0).getOriginalFilename()); int noticeCode = 0; try { noticeCode = noticeService.addNotice(addNoticeReqDto); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.internalServerError().body(new CMRespDto<>(-1, "Failed to write", noticeCode)); } return ResponseEntity.ok(new CMRespDto<>(1, "completing creation", noticeCode)); } @GetMapping("/{noticeCode}") public ResponseEntity<?> getNotice(@PathVariable int noticeCode) { GetNoticeResponseDto getNoticeResponseDto = null; try { getNoticeResponseDto = noticeService.getNotice(null, noticeCode); if(getNoticeResponseDto == null) { return ResponseEntity.badRequest().body(new CMRespDto<>(-1, "request failes", null)); } } catch (Exception e) { e.printStackTrace(); return ResponseEntity.internalServerError().body(new CMRespDto<>(-1, "database failes", null)); } return ResponseEntity.ok().body(new CMRespDto<>(1, "lookup successful", getNoticeResponseDto)); } @GetMapping("/{flag}/{noticeCode}") public ResponseEntity<?> geNotice(@PathVariable String flag, @PathVariable int noticeCode) { GetNoticeResponseDto getNoticeResponseDto = null; if (flag.equals("pre") || flag.equals("next")) { try { getNoticeResponseDto = noticeService.getNotice(flag, noticeCode); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.internalServerError().body(new CMRespDto<>(-1, "database failes", null)); } }else { return ResponseEntity.badRequest().body(new CMRespDto<>(-1, "request failes", null)); } return ResponseEntity.ok().body(new CMRespDto<>(1, "lookup successful", getNoticeResponseDto)); } @GetMapping("/file/download/{fileName}") public ResponseEntity<?> downloadFile(@PathVariable String fileName) throws IOException { Path path = Paths.get(filePath + "notice/" + fileName); String contentType = Files.probeContentType(path); // file의 MIME타입 log.info("contentType: {}", contentType); HttpHeaders headers = new HttpHeaders(); headers.setContentDisposition(ContentDisposition.builder("attachment") // 한글 파일명 다운로드 할 수 있게 설정 .filename(fileName, StandardCharsets.UTF_8) .build()); headers.add(HttpHeaders.CONTENT_TYPE, contentType); // header Resource resource = new InputStreamResource(Files.newInputStream(path)); // body return ResponseEntity.ok().headers(headers).body(resource); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.fasten.analyzer.restapiplugin.mvn.api; import eu.fasten.analyzer.restapiplugin.mvn.RestApplication; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class CallableApiTest { private CallableApiService service; private CallableApi api; private final int offset = 0; private final int limit = Integer.parseInt(RestApplication.DEFAULT_PAGE_SIZE); @BeforeEach void setUp() { service = Mockito.mock(CallableApiService.class); api = new CallableApi(service); } @Test public void getPackageCallablesTest() { var packageName = "pkg name"; var version = "pkg version"; var response = new ResponseEntity<>("package binary callables", HttpStatus.OK); Mockito.when(service.getPackageCallables(packageName, version, offset, limit, null, null)).thenReturn(response); var result = api.getPackageCallables(packageName, version, offset, limit, null, null); assertEquals(response, result); Mockito.verify(service).getPackageCallables(packageName, version, offset, limit, null, null); } @Test public void getCallableMetadataTest() { var packageName = "pkg name"; var version = "pkg version"; var callable = "callable"; var response = new ResponseEntity<>("callable metadata", HttpStatus.OK); Mockito.when(service.getCallableMetadata(packageName, version, callable, null, null)).thenReturn(response); var result = api.getCallableMetadata(packageName, version, callable, null, null); assertEquals(response, result); Mockito.verify(service).getCallableMetadata(packageName, version, callable, null, null); } @Test public void getCallablesTest() { var ids = List.of(1L, 2L, 3L); var response = new ResponseEntity<>("callables metadata map", HttpStatus.OK); Mockito.when(service.getCallables(ids)).thenReturn(response); var result = api.getCallables(ids); assertEquals(response, result); Mockito.verify(service).getCallables(ids); } }
/* * AMRIT – Accessible Medical Records via Integrated Technology * Integrated EHR (Electronic Health Records) Solution * * Copyright (C) "Piramal Swasthya Management and Research Institute" * * This file is part of AMRIT. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see https://www.gnu.org/licenses/. */ import { Component, OnInit, DoCheck } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { BeneficiaryDetailsService } from '../../services/beneficiary-details.service'; import 'rxjs/Rx'; import { HttpServiceService } from 'app/app-modules/core/services/http-service.service'; import { SetLanguageComponent } from 'app/app-modules/core/components/set-language.component'; @Component({ selector: 'app-beneficiary-details', templateUrl: './beneficiary-details.component.html', styleUrls: ['./beneficiary-details.component.css'] }) export class BeneficiaryDetailsComponent implements OnInit, DoCheck { beneficiary: any; today: any; beneficiaryDetailsSubscription: any; current_language_set: any; constructor( private router: Router, private route: ActivatedRoute, public httpServiceService: HttpServiceService, private beneficiaryDetailsService: BeneficiaryDetailsService ) { } ngOnInit() { this.assignSelectedLanguage(); this.today = new Date(); this.route.params.subscribe(param => { this.beneficiaryDetailsService.getBeneficiaryDetails(param['beneficiaryRegID'], localStorage.getItem('benFlowID')); this.beneficiaryDetailsSubscription = this.beneficiaryDetailsService.beneficiaryDetails$ .subscribe(res => { if (res != null) { this.beneficiary = res; if (res.serviceDate) { this.today = res.serviceDate; } } }); this.beneficiaryDetailsService.getBeneficiaryImage(param['beneficiaryRegID']) .subscribe(data => { if (data && data.benImage) { this.beneficiary.benImage = data.benImage; } }); }); } ngDoCheck() { this.assignSelectedLanguage(); } assignSelectedLanguage() { const getLanguageJson = new SetLanguageComponent(this.httpServiceService); getLanguageJson.setLanguage(); this.current_language_set = getLanguageJson.currentLanguageObject; } ngOnDestroy() { if (this.beneficiaryDetailsSubscription) this.beneficiaryDetailsSubscription.unsubscribe(); } }
import * as React from 'react'; import { Slider } from '@miblanchard/react-native-slider'; import { Button, StyleSheet, Text, View } from 'react-native'; import { ExcludeSystemGestureAreaView } from '../../src'; import { NavigationContainer, useNavigation } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="home" component={Home} /> <Stack.Screen name="demo" component={DemoComponent} /> </Stack.Navigator> </NavigationContainer> ); } const Home = () => { const { navigate } = useNavigation(); return ( <View style={styles.container}> <Button title="Go To Slider" onPress={() => { navigate('demo', {}); }} /> </View> ); }; const DemoComponent = () => { const [value, setValue] = React.useState(20); return ( <View style={styles.container}> <View style={styles.sliderContainer}> <ExcludeSystemGestureAreaView> <Slider containerStyle={{ width: '100%' }} value={value} maximumTrackTintColor="red" minimumTrackTintColor="blue" thumbTintColor="orange" minimumValue={0} step={0.5} maximumValue={100} onValueChange={(value) => setValue(value as number)} /> </ExcludeSystemGestureAreaView> </View> <Text>Value: {value}</Text> </View> ); }; const styles = StyleSheet.create({ sliderContainer: { height: 50, width: '100%', marginLeft: 10, marginRight: 10, alignItems: 'stretch', justifyContent: 'center', // backgroundColor: 'green', }, container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, box: { width: 60, height: 60, marginVertical: 20, }, });
/* * This code is released under Creative Commons Attribution 4.0 International * (CC BY 4.0) license, http://creativecommons.org/licenses/by/4.0/legalcode . * That means: * * You are free to: * * Share — copy and redistribute the material in any medium or format * Adapt — remix, transform, and build upon the material * for any purpose, even commercially. * * The licensor cannot revoke these freedoms as long as you follow the * license terms. * * Under the following terms: * * Attribution — You must give appropriate credit, provide a link to the * license, and indicate if changes were made. You may do so in any * reasonable manner, but not in any way that suggests the licensor endorses * you or your use. * * No additional restrictions — You may not apply legal terms or technological * measures that legally restrict others from doing anything the license * permits. * * * 2019 Aeonium Software Systems, Robert Rohm. */ package java8.teil06.streams.terminal; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.function.BinaryOperator; import java.util.function.IntBinaryOperator; import java.util.stream.IntStream; /** * Beispiel zu Reduce-Operationen: Endergebnis des reduce-Vorgangs ist immer ein * Optional, parametrisiert mit dem Ergebnistyp. Die Reduzierung erfolgt immer * mit einem BinaryOperator * * @author Robert Rohm&lt;r.rohm@aeonium-systems.de&gt; */ public class Terminal04_reduce { public static void main(String[] args) { IntStream intStream = IntStream.of(1, 6, 4, 56, 68, 95, 266, 757, 668, 8865, 5); OptionalInt intMax = intStream.reduce(new IntBinaryOperator() { /** * Reduzierung zum Maximum: * * @param left Erster bzw. vorheriger Wert, * @param right nächster Wert * @return Maximum der beiden Werte */ @Override public int applyAsInt(int left, int right) { return Math.max(left, right); } }); System.out.println("intMax: " + intMax.getAsInt()); // Reduce mit komplexen Datenobjekten List<Person> personen = Person.createData(); Optional<Person> reduced = personen.stream().reduce(new BinaryOperator<Person>() { /** * * @param t Erstes Element - oder Return-Wert des vorherigen Durchlaufs * @param u Nächstes Element * @return Zwischenergebnis */ @Override public Person apply(Person t, Person u) { System.out.println("t: " + t); System.out.println("u: " + u); System.out.println("------------------"); return t; } }); System.out.println("result: " + reduced.get()); } }
from transformers import AutoTokenizer, AutoModelForCausalLM,BitsAndBytesConfig,StoppingCriteriaList import transformers import torch from typing import Dict,List,Tuple from byzerllm.utils import (generate_instruction_from_history, compute_max_new_tokens,tokenize_stopping_sequences,StopSequencesCriteria) from typing import Dict, Any,List,Generator from pyjava.storage import streaming_tar as STar from pyjava import RayContext from pyjava.api.mlsql import DataServer from byzerllm import BlockRow import os import time def stream_chat(self,tokenizer,ins:str, his:List[Dict[str,str]]=[], max_length:int=4090, top_p:float=0.95, temperature:float=0.1,**kwargs): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") timeout_s = float(kwargs.get("timeout_s",60*5)) skip_check_min_length = int(kwargs.get("stopping_sequences_skip_check_min_length",0)) role_mapping = { "user":"User", "assistant":"Assistant", } fin_ins = generate_instruction_from_history(ins,his,role_mapping=role_mapping) tokens = tokenizer(fin_ins, return_token_type_ids=False,return_tensors="pt").to(device) stopping_criteria = None if "stopping_sequences" in kwargs: stopping_sequences = [torch.tensor(word).to(device) for word in tokenize_stopping_sequences(tokenizer,kwargs["stopping_sequences"].split(","))] input_length = tokens["input_ids"].shape[1] stopping_criteria=StoppingCriteriaList([StopSequencesCriteria( tokenizer=tokenizer, stops=stopping_sequences, input_start=input_length, skip_check_min_length=skip_check_min_length )]) max_new_tokens = compute_max_new_tokens(tokens,max_length) start_time = time.monotonic() response = self.generate( input_ids=tokens["input_ids"], max_new_tokens= max_new_tokens, repetition_penalty=1.05, temperature=temperature, attention_mask=tokens.attention_mask, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id, bos_token_id=tokenizer.bos_token_id, early_stopping=True, max_time=timeout_s, stopping_criteria=stopping_criteria, ) time_taken = time.monotonic() - start_time new_tokens = response[0][tokens["input_ids"].shape[1]:] print(f"generate took {time_taken} s to complete. tokens/s:{len(new_tokens)/time_taken}",flush=True) answer = tokenizer.decode(new_tokens, skip_special_tokens=True) return [(answer,"")] def init_model(model_dir,infer_params:Dict[str,str]={},sys_conf:Dict[str,str]={}): longContextMode = infer_params.get("longContextMode","true") == "true" if longContextMode: old_init = transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.__init__ def ntk_scaled_init(self, dim, max_position_embeddings=4096, base=10000, device=None): #The method is just these three lines max_position_embeddings = 16384 a = 8 #Alpha value base = base * a ** (dim / (dim-2)) #Base change formula old_init(self, dim, max_position_embeddings, base, device) transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.__init__ = ntk_scaled_init pretrained_model_dir = os.path.join(model_dir,"pretrained_model") adaptor_model_dir = model_dir is_adaptor_model = os.path.exists(pretrained_model_dir) if not is_adaptor_model: pretrained_model_dir = model_dir tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir,trust_remote_code=True) tokenizer.padding_side="right" tokenizer.pad_token_id=0 tokenizer.bos_token_id = 1 print(f"longContextMode:{longContextMode}", flush=True) quatization = infer_params.get("quatization", "false") if quatization in ["4", "8", "true"]: print(f"enable [{quatization}] quatization.", flush=True) load_in_8bit = quatization == "8" # default using int4 quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=False, bnb_4bit_compute_dtype=torch.bfloat16, ) if load_in_8bit: llm_int8_threshold = infer_params.get("llm_int8_threshold", 6.0) quantization_config = BitsAndBytesConfig( load_in_8bit=True, llm_int8_threshold=llm_int8_threshold, llm_int8_skip_modules=None, llm_int8_enable_fp32_cpu_offload=False, llm_int8_has_fp16_weight=False, ) model = AutoModelForCausalLM.from_pretrained( pretrained_model_dir, trust_remote_code=True, device_map="auto", quantization_config=quantization_config, ) else: model = AutoModelForCausalLM.from_pretrained(pretrained_model_dir,trust_remote_code=True, device_map='auto', torch_dtype=torch.bfloat16 ) if is_adaptor_model: from peft import PeftModel model = PeftModel.from_pretrained(model, adaptor_model_dir) model.eval() if quatization: model = torch.compile(model) model = model.to_bettertransformer() import types model.stream_chat = types.MethodType(stream_chat, model) return (model,tokenizer) def sft_train(data_refs:List[DataServer], train_params:Dict[str,str], conf: Dict[str, str])->Generator[BlockRow,Any,Any]: from ..utils.sft import sft_train as common_sft_train return common_sft_train(data_refs,train_params,conf) def sfft_train(data_refs:List[DataServer], train_params:Dict[str,str], conf: Dict[str, str])->Generator[BlockRow,Any,Any]: from ..utils.fulltune.pretrain import sfft_train as common_sfft_train return common_sfft_train(data_refs,train_params,conf)
import { Injectable, OnDestroy } from '@angular/core'; import { webSocket, WebSocketSubject } from 'rxjs/webSocket'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { WsEchoService } from './echo-ws.service'; import { Logger } from 'src/app/core/logger'; /* Example service for websocket backend connection. Works in pair with either: - python echo backend server. See .md file in digitalpanda-study/web-socket-and-worker for setup at "ws://localhost:9998/echo" - digitalpanda-backend text-based bidirectoninal WebSocket controller at `${environment.wsApiEndpoint}/ui/websocket/echo` */ @Injectable({ providedIn: 'root' }) export class EchoNativeWebSocketService implements OnDestroy, WsEchoService{ private echoEndpoint: string = environment.wsApiEndpoint + "/ws/echo" //"ws://localhost:9998/echo" private socket$: WebSocketSubject<string>; public connect(): void { if (!this.socket$ || this.socket$.closed) { Logger.debug("[EchoSocketService].connect() : new WebSocketSubject connection") this.socket$ = webSocket({ url: this.echoEndpoint , deserializer : e => String(e.data) , serializer : e => e , openObserver : { next: () => Logger.debug("[EchoSocketService]: server connection opened")} , closeObserver : { next: () => Logger.debug("[EchoSocketService]: server connection closed")} }); } } sendMessage(message: string) { this.connect(); this.socket$.next(message); } getInputStream(): Observable<string> { this.connect(); return this.socket$.asObservable(); } ngOnDestroy(): void { this.close(); } close() { this.socket$.complete(); } }
#[starknet::interface] trait IHelloWorld<IContractState> { fn read_hello_world(self: @IContractState) -> felt252; fn write_hello_world(ref self: IContractState, new_message: felt252); } #[starknet::contract] mod contract { #[storage] struct Storage { hello_world: felt252, } #[constructor] fn constructor(ref self: ContractState) { self.hello_world.write('Hello Encode!'); } #[external(v0)] impl HelloWorldInterface of super::IHelloWorld<ContractState> { fn read_hello_world(self: @ContractState) -> felt252 { self.hello_world.read() } fn write_hello_world(ref self: ContractState, new_message: felt252) { self.hello_world.write(new_message); } } }
<?php /* 1. Write a script to create XML file named “Teacher.xml”. <Department> <Computer Science> <Teacher Name>…</Teacher Name> <Qualification>….</Qualification> <Subject Taught>…</Subject Taught> <Experience>…</Experience> </Computer Science> </Department> Store the details of 5 teachers who are having qualification as NET. */ // format one use simplexml_load_string() // xml string /* $xmlstr="<?xml version='1.0' ?><Department></Department>"; // called as root $xml= simplexml_load_string($xmlstr); */ class teach{ public $tname,$sub,$exp; public function __construct($t,$s,$e){ $this->tname=$t; $this->sub=$s; $this->exp=$e; } public function create_xml(SimpleXMLElement $xml){ $cs_obj=$xml->addChild("Computer Science"); //parent $tname_obj=$cs_obj->addChild("Teacher Name","$this->tname"); // child $qual=$cs_obj->addChild("Qualification","UGC-NET"); $sub_obj=$cs_obj->addChild("Subject Taught","$this->sub"); $exp_obj=$cs_obj->addChild("Experience","$this->exp"); } } // using SimpleXMLElement class : // $xml=new SimpleXMLElement("<Department></Department>"); // root // $cs=$xml->addChild("Computer Science"); //parent // $tname=$cs->addChild("Teacher Name","prajwal"); // child // $qual=$cs->addChild("Qualification","UGC-NET"); // child // $sub=$cs->addChild("Subject Taught","PHP_LAB"); // child // $sub=$cs->addChild("Subject Taught","PYTHON_LAB"); // child // $sub=$cs->addChild("Subject Taught","CPP_LAB"); // child // $exp=$cs->addChild("Experience","1year"); // child // $xml->asXML("Teacher.xml"); $obj[0]=new teach("teach1","php",1); $obj[1]=new teach("teach2","cpp",2); $obj[2]=new teach("teach3","python",3); $obj[3]=new teach("teach4","EVS",4); $obj[5]=new teach("teach5","english",5); $xml=new SimpleXMLElement("<Department></Department>"); // root foreach($obj as $t){ $t->create_xml($xml); } $xml->asXML("Teacher.xml"); echo "<h1>XML Doc created Successful.</h1>"."<br>"; /* // Adding child named "institution" // and valued "geeksforgeeks" $xml->addChild("institution", "geeksforgeeks"); // Adding attribute named "type" and value // "educational" in institution element. $xml->institution->addAttribute("type", "educational"); */ ?>
/** * 상태 : (offsetX, offsetY, size) = 좌표 (offsetX, offsetY)에서 시작하여 가로 길이와 세로 길이가 size인 정사각형을 압축했을 때 남아 있는 0과 1의 개수 * 종료 조건 : 상태가 나타내는 범위의 크기와 관계없이 범위 안 원소들이 모두 0이거나 1이면 하나의 수자로 압축 * - 0의 개수가 zero, 1의 개수가 one 이라면 * {0 : 1, 1 : 0} -> 모든 원소가 0 * {0 : 0, 1 : 1} -> 모든 원소가 1 * 점화식 : (offsetX, offsetY, size) = (offsetX, offsetY, size/2) + (offsetX + size/2, offsetY, size/2) * + (offsetX, offsetY + size/2, size/2) + (offsetX + size/2, offsetY + size/2, size/2) */ class Solution { public int[] solution(int[][] arr) { Count count = count(0, 0, arr.length, arr); return new int[]{count.zero, count.one}; } private Count count(int offsetX, int offsetY, int size, int[][] arr) { int h = size / 2; for (int x = offsetX; x < offsetX + size; x++) { //모든 원소가 같은 값을 같는지 순회(검사) for (int y = offsetY; y < offsetY + size; y++) { if (arr[y][x] != arr[offsetY][offsetX]) { return count(offsetX, offsetY, h, arr) //모든 결과 합해서 반환 .add(count(offsetX + h, offsetY, h, arr)) .add(count(offsetX, offsetY + h, h, arr)) .add(count(offsetX + h, offsetY + h, h, arr)); } } } //다른 값을 가진 원소가 있다면 종료 조건에 해당하지 않고 점화식에 따라 반환값 구하기 if (arr[offsetY][offsetX] == 1) { //해당 원소가 1인지 0인지에 따라 알맞은 개수를 갖는 Count 객체 반환 return new Count(0, 1); } return new Count(1, 0); } private static class Count { public final int zero; public final int one; public Count(int zero, int one) { this.zero = zero; this.one = one; } public Count add(Count other) { //원소가 섞여있다면 재귀 메서드를 사용하여 점화식에 따라 부분 문제를 해결해야 함 // 4개의 작은 정사각형 결과 합을 구해야 함 return new Count(zero + other.zero, one + other.one); } } }
import { useState } from "react"; import Bookings from "./Bookings/Bookings"; import Restaurant from "../../assets/images/restaurant.jpg"; import SeasoningDish from "../../assets/images/seasoning-dish.jpg"; import WarningIcon from "../../assets/icons/warning.png"; import AsteriskIcon from "../../assets/icons/asterisk.png"; import "./BookingForm.css"; export const getInitialDate = () => { const initialDate = new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "2-digit", year: "numeric", }); const formattedDate = initialDate.split("/").reverse().join("-"); return formattedDate; }; const BookingForm = ({ availableTimes, dispatch, submitForm }) => { const [date, setDate] = useState({ value: getInitialDate(), isValid: true, }); const [time, setTime] = useState("17:00"); const [guests, setGuests] = useState({ value: "1", isValid: true, }); const [occasion, setOccasion] = useState("Birthday"); const isFormValid = date.isValid && guests.isValid; const validateDateInput = (selectedDate) => { if (!selectedDate) { setDate({ value: "", isValid: false }); return false; } return true; }; const handleDateChange = (e) => { const selectedDate = e.target.value; const isValidDate = validateDateInput(selectedDate); if (isValidDate) { setDate({ value: selectedDate, isValid: true, }); dispatch({ type: "date_change", payload: selectedDate }); } }; const handleTimeChange = (e) => { setTime(e.target.value); }; const validateGuestsInput = (enteredGuests) => { if (!enteredGuests) { setGuests({ value: "", isValid: false }); return false; } if (+enteredGuests < 1 || +enteredGuests > 10) { setGuests({ value: enteredGuests, isValid: false }); return false; } return true; }; const handleGuestsChange = (e) => { const enteredGuests = e.target.value; const isValidGuests = validateGuestsInput(enteredGuests); if (isValidGuests) setGuests({ value: enteredGuests, isValid: true }); }; const handleOccasionChange = (e) => { setOccasion(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); if (!isFormValid) return; const formData = { date: date.value, time: time, guests: guests.value, occasion: occasion, }; submitForm(formData); }; return ( <section className="booking-form"> <header> <h1>Book a table</h1> <p>Find a table for any occasion</p> <section className="restaurant-images"> <img src={Restaurant} alt="restaurant ambience" /> <img src={SeasoningDish} alt="adrian seasoning a dish" /> </section> </header> <main> <div className="required-fields"> <em> <img src={AsteriskIcon} alt="asterisk icon" id="asterisk" />indicates required fields. </em> </div> <form onSubmit={handleSubmit}> <div className="form-field"> <label htmlFor="res-date"> Choose date <img src={AsteriskIcon} alt="asterisk icon" className="asterisk-icon" /> </label> <input type="date" id="res-date" name="res-date" value={date.value} onChange={handleDateChange} required /> {!date.isValid && ( <div className="warning"> <img src={WarningIcon} alt="warning icon" /> <p className="error">Please select a date.</p> </div> )} </div> <div className="form-field"> <label htmlFor="res-time"> Choose time <img src={AsteriskIcon} alt="asterisk icon" className="asterisk-icon" /> </label> <select id="res-time" name="res-time" value={time} onChange={handleTimeChange} required > <Bookings availableSlots={availableTimes} /> </select> </div> <div className="form-field"> <label htmlFor="guests"> Number of guests <img src={AsteriskIcon} alt="asterisk icon" className="asterisk-icon" /> </label> <input type="number" id="guests" name="guests" placeholder="1" min="1" max="10" value={guests.value} onChange={handleGuestsChange} required /> {!guests.isValid && ( <div className="warning"> <img src={WarningIcon} alt="warning icon" /> <p className="error">Please enter a number between 1 and 10.</p> </div> )} </div> <div className="form-field"> <label htmlFor="occasion"> Occasion <img src={AsteriskIcon} alt="asterisk icon" className="asterisk-icon" /> </label> <select id="occasion" name="occasion" value={occasion} onChange={handleOccasionChange} required > <option>Birthday</option> <option>Anniversary</option> </select> </div> <input id="submit-btn" disabled={!isFormValid} type="submit" value="Make Your Reservation" aria-label="On Click" aria-labelledby="Make Your Reservation" /> </form> </main> </section> ); }; export default BookingForm;
import React, { useEffect, useState } from "react"; // import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux"; import Footer from "./Foot"; import "../index.css"; import { getTodos, handleCompleted, removeToDo } from "./TodoSlice"; function ToDoList() { const dispatch = useDispatch(); useEffect(() => { console.log("dispatched"); const newTodos = getTodos(); dispatch(newTodos); }, [dispatch]); const { data, error, loading } = useSelector((state) => state); console.log(data); const [filter, setfilter] = useState < string > ("all"); const handleFilter = (selectedFilter) => { setfilter(selectedFilter); }; const filteredTodos = data.filter((todo) => { if (filter === "active") { return !todo.completed; } else if (filter === "completed") { return todo.completed; } else { return true; } }); console.log(data); const handle = (todo) => { dispatch(handleCompleted(todo)); }; return ( <> <ul className="todo-list"> {filteredTodos && filteredTodos.map((todo) => todo.completed ? ( <li key={todo.id} className="completed"> <div className="view"> <input onChange={() => handle(todo)} className="toggle" checked={todo.completed} type="checkbox" /> <label>{todo.title}</label> <button onClick={() => dispatch(removeToDo(todo))} className="destroy" ></button> </div> </li> ) : ( <li key={todo.id}> <div className="view"> <input className="toggle" type="checkbox" checked={todo.completed} onChange={() => handle(todo)} /> <label>{todo.title}</label> <button onClick={() => dispatch(removeToDo(todo))} className="destroy" ></button> </div> </li> ) )} </ul> <Footer handleFilter={handleFilter} /> </> ); } export default ToDoList;
import { TimelineOutlined } from "@mui/icons-material"; import { Box, Button, TextField, Typography, useMediaQuery, useTheme } from "@mui/material"; import { DataGrid } from "@mui/x-data-grid"; import axios from "axios"; import { Formik } from "formik"; import { useEffect, useState } from "react"; import { NotificationContainer, NotificationManager } from 'react-notifications'; import Popup from 'reactjs-popup'; import * as yup from "yup"; import Header from "../../components/Header"; import { tokens } from "../../theme"; const Transactions = () => { const isNonMobile = useMediaQuery("(min-width:600px)"); const theme = useTheme(); const colors = tokens(theme.palette.mode); const [tx, setTx] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { axios.get("https://hardy-mind-production.up.railway.app/transaction") .then((res) => { if (res.data.success) { setTx(res.data.data); } }) .catch((err) => { NotificationManager.error('Error', err.message, 3000); }) }, []) const columns = [ { field: "id", headerName: "Tx ID", }, { field: "email", headerName: "Email", flex: 1, cellClassName: "name-column--cell", }, { field: "type", headerName: "Waste Type", headerAlign: "left", align: "left", flex: 1, renderCell: (params) => { return ( <> {params.value.map((v) => { return <Box width="50%" m="0 auto" p="5px" display="flex" justifyContent="center" backgroundColor={ v.name === "waste1" ? colors.redAccent[600] : v.name === "waste2" ? colors.blueAccent[700] : colors.greenAccent[700] } borderRadius="4px" key={v.name} > <Typography color={colors.grey[100]} sx={{ ml: "5px" }}> {v.weight} Ons </Typography> </Box> })} </> ); }, }, { field: "cost", headerName: "Cost", flex: 1, renderCell: (params) => ( <Typography color={colors.greenAccent[500]}> IDR {params.row.cost} </Typography> ), }, { field: "date", headerName: "Date", flex: 1, }, ]; const contentStyle = { height: "70vh", width: "70%", backgroundColor: "#00008bab", backdropFilter: "blur(6px)", borderRadius: "2rem", display: "flex", alignItems: "center", justifyContent: "center", }; const handleFormSubmit = async(values) => { try { const transaction = await axios.post("https://hardy-mind-production.up.railway.app/transaction", values); const response = transaction.data; if (response.success) { NotificationManager.success('Success', 'Success add transaction', 3000); } else { NotificationManager.warning('Error', 'Someting Wrong', 3000); } } catch (error) { console.log(error); NotificationManager.error('Error', 'API Error', 3000); } }; return ( <Box m="20px"> <Box display="flex" justifyContent="space-between" alignItems="center"> <Header title="TRANSACTIONS" subtitle="List of Transactions" /> <Box> <Popup modal contentStyle={contentStyle} trigger={<Button sx={{ backgroundColor: colors.blueAccent[700], color: colors.grey[100], fontSize: "14px", fontWeight: "bold", padding: "10px 20px", }} > <TimelineOutlined sx={{ mr: "10px" }} /> Add Transaction </Button>} position="center center"> <Formik onSubmit={handleFormSubmit} initialValues={initialValues} validationSchema={checkoutSchema} > {({ values, errors, touched, handleBlur, handleChange, handleSubmit, }) => ( <form onSubmit={handleSubmit} style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center" }}> <Box display="flex" justifyContent="center" flexDirection="column" gap="20px" width="20rem" sx={{ "& > div": { gridColumn: isNonMobile ? undefined : "span 4" }, }} > <TextField variant="filled" type="text" label="Email" onBlur={handleBlur} onChange={handleChange} value={values.email} name="email" error={!!touched.email && !!errors.email} helperText={touched.email && errors.email} sx={{ gridColumn: "span 4" }} /> <TextField variant="filled" type="number" label="Weight Waste 1 (Ons)" onBlur={handleBlur} onChange={handleChange} value={values.waste1} name="waste1" error={!!touched.waste1 && !!errors.waste1} helperText={touched.waste1 && errors.waste1} sx={{ gridColumn: "span 4" }} /> <TextField variant="filled" type="number" label="Weight Waste 2 (Ons)" onBlur={handleBlur} onChange={handleChange} value={values.waste2} name="waste2" error={!!touched.waste2 && !!errors.waste2} helperText={touched.waste2 && errors.waste2} sx={{ gridColumn: "span 4" }} /> <TextField variant="filled" type="number" label="Weight Waste 3 (Ons)" onBlur={handleBlur} onChange={handleChange} value={values.waste3} name="waste3" error={!!touched.waste3 && !!errors.waste3} helperText={touched.waste3 && errors.waste3} sx={{ gridColumn: "span 4" }} /> <TextField variant="filled" type="number" label="Cost Total" onBlur={handleBlur} onChange={handleChange} value={values.cost} name="cost" error={!!touched.cost && !!errors.cost} helperText={touched.cost && errors.cost} sx={{ gridColumn: "span 4" }} /> </Box> <Box display="flex" justifyContent="end" mt="20px"> <Button type="submit" color="secondary" variant="contained"> Submit </Button> </Box> </form> )} </Formik> </Popup> </Box> </Box> <Box m="40px 0 0 0" height="75vh" sx={{ "& .MuiDataGrid-root": { border: "none", }, "& .MuiDataGrid-cell": { borderBottom: "none", }, "& .name-column--cell": { color: colors.greenAccent[300], }, "& .MuiDataGrid-columnHeaders": { backgroundColor: colors.blueAccent[700], borderBottom: "none", }, "& .MuiDataGrid-virtualScroller": { backgroundColor: colors.primary[400], }, "& .MuiDataGrid-footerContainer": { borderTop: "none", backgroundColor: colors.blueAccent[700], }, "& .MuiCheckbox-root": { color: `${colors.greenAccent[200]} !important`, }, }} > <DataGrid checkboxSelection rows={tx} columns={columns} /> </Box> <NotificationContainer/> </Box> ); }; const checkoutSchema = yup.object().shape({ email: yup.string().email("invalid email").required("required"), }); const initialValues = { email: "", waste1: 0, waste2: 0, waste3: 0, cost: 0, }; export default Transactions;
""" Test module for file_to_dict.py Module contains test cases for the functions in file_to_dict.py using pytest. """ from file_to_dict import file_to_dict def test_file_to_dict(): """ Test if the text file is reads into dictionary. Examples: - Read a file into a dictionary ('dict.txt'). - Read a file into a dictionary ('dict1.txt'). """ # Test Case 1: Test to read 'dict.txt' file into dictionary. result_1 = file_to_dict('dict.txt') expected_result_1 = {'name': ' Vismaya', 'Location': ' Coimbatore'} assert result_1 == expected_result_1, "Tested Successfully!" # Test Case 2: Test to read 'dict1.txt' file into dictionary. result_2 = file_to_dict('dict1.txt') expected_result_2 = {'from': ' Pollachi', 'To': ' Coimbatore'} assert result_2 == expected_result_2, "Tested Successfully!"
/* This file is part of Helio Workstation. Helio is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Helio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Helio. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "PianoTrackNode.h" #include "PianoSequence.h" #include "ProjectNode.h" #include "TreeNodeSerializer.h" #include "Icons.h" #include "Pattern.h" #include "MainLayout.h" #include "Instrument.h" #include "OrchestraPit.h" #include "Delta.h" #include "PianoTrackDiffLogic.h" PianoTrackNode::PianoTrackNode(const String &name) : MidiTrackNode(name, Serialization::Core::pianoTrack) { this->sequence = new PianoSequence(*this, *this); this->pattern = new Pattern(*this, *this); // this will be set by transport //this->layer->setInstrumentId(this->workspace.getDefaultInstrument()->getInstrumentID()); this->vcsDiffLogic = new VCS::PianoTrackDiffLogic(*this); using namespace Serialization::VCS; this->deltas.add(new VCS::Delta({}, MidiTrackDeltas::trackPath)); this->deltas.add(new VCS::Delta({}, MidiTrackDeltas::trackMute)); this->deltas.add(new VCS::Delta({}, MidiTrackDeltas::trackColour)); this->deltas.add(new VCS::Delta({}, MidiTrackDeltas::trackInstrument)); this->deltas.add(new VCS::Delta({}, PianoSequenceDeltas::notesAdded)); this->deltas.add(new VCS::Delta({}, PatternDeltas::clipsAdded)); } Image PianoTrackNode::getIcon() const noexcept { return Icons::findByName(Icons::pianoTrack, HEADLINE_ICON_SIZE); } int PianoTrackNode::getNumDeltas() const { return this->deltas.size(); } //===----------------------------------------------------------------------===// // VCS stuff //===----------------------------------------------------------------------===// VCS::Delta *PianoTrackNode::getDelta(int index) const { using namespace Serialization::VCS; if (this->deltas[index]->hasType(PianoSequenceDeltas::notesAdded)) { const int numEvents = this->getSequence()->size(); if (numEvents == 0) { this->deltas[index]->setDescription(VCS::DeltaDescription("empty sequence")); } else { this->deltas[index]->setDescription(VCS::DeltaDescription("{x} notes", numEvents)); } } else if (this->deltas[index]->hasType(PatternDeltas::clipsAdded)) { const int numClips = this->getPattern()->size(); if (numClips == 0) { this->deltas[index]->setDescription(VCS::DeltaDescription("empty pattern")); } else { this->deltas[index]->setDescription(VCS::DeltaDescription("{x} clips", numClips)); } } return this->deltas[index]; } ValueTree PianoTrackNode::getDeltaData(int deltaIndex) const { using namespace Serialization::VCS; if (this->deltas[deltaIndex]->hasType(MidiTrackDeltas::trackPath)) { return this->serializePathDelta(); } if (this->deltas[deltaIndex]->hasType(MidiTrackDeltas::trackMute)) { return this->serializeMuteDelta(); } else if (this->deltas[deltaIndex]->hasType(MidiTrackDeltas::trackColour)) { return this->serializeColourDelta(); } else if (this->deltas[deltaIndex]->hasType(MidiTrackDeltas::trackInstrument)) { return this->serializeInstrumentDelta(); } else if (this->deltas[deltaIndex]->hasType(PianoSequenceDeltas::notesAdded)) { return this->serializeEventsDelta(); } else if (this->deltas[deltaIndex]->hasType(PatternDeltas::clipsAdded)) { return this->serializeClipsDelta(); } jassertfalse; return {}; } VCS::DiffLogic *PianoTrackNode::getDiffLogic() const { return this->vcsDiffLogic; } void PianoTrackNode::resetStateTo(const VCS::TrackedItem &newState) { using namespace Serialization::VCS; for (int i = 0; i < newState.getNumDeltas(); ++i) { const VCS::Delta *newDelta = newState.getDelta(i); const auto newDeltaData(newState.getDeltaData(i)); if (newDelta->hasType(MidiTrackDeltas::trackPath)) { this->resetPathDelta(newDeltaData); } else if (newDelta->hasType(MidiTrackDeltas::trackMute)) { this->resetMuteDelta(newDeltaData); } else if (newDelta->hasType(MidiTrackDeltas::trackColour)) { this->resetColourDelta(newDeltaData); } else if (newDelta->hasType(MidiTrackDeltas::trackInstrument)) { this->resetInstrumentDelta(newDeltaData); } // the current layer state is supposed to have // a single note delta of type PianoSequenceDeltas::notesAdded else if (newDelta->hasType(PianoSequenceDeltas::notesAdded)) { this->resetEventsDelta(newDeltaData); } // same rule applies to clips state: else if (newDelta->hasType(PatternDeltas::clipsAdded)) { this->resetClipsDelta(newDeltaData); } } } //===----------------------------------------------------------------------===// // Serializable //===----------------------------------------------------------------------===// ValueTree PianoTrackNode::serialize() const { ValueTree tree(Serialization::Core::treeNode); this->serializeVCSUuid(tree); tree.setProperty(Serialization::Core::treeNodeType, this->type, nullptr); tree.setProperty(Serialization::Core::treeNodeName, this->name, nullptr); this->serializeTrackProperties(tree); tree.appendChild(this->sequence->serialize(), nullptr); tree.appendChild(this->pattern->serialize(), nullptr); TreeNodeSerializer::serializeChildren(*this, tree); return tree; } void PianoTrackNode::deserialize(const ValueTree &tree) { this->reset(); this->deserializeVCSUuid(tree); this->deserializeTrackProperties(tree); forEachValueTreeChildWithType(tree, e, Serialization::Midi::track) { this->sequence->deserialize(e); } forEachValueTreeChildWithType(tree, e, Serialization::Midi::pattern) { this->pattern->deserialize(e); } // Proceed with basic properties and children TreeNode::deserialize(tree); } //===----------------------------------------------------------------------===// // Deltas //===----------------------------------------------------------------------===// ValueTree PianoTrackNode::serializePathDelta() const { using namespace Serialization::VCS; ValueTree tree(MidiTrackDeltas::trackPath); tree.setProperty(delta, this->getTrackName(), nullptr); return tree; } ValueTree PianoTrackNode::serializeMuteDelta() const { using namespace Serialization::VCS; ValueTree tree(MidiTrackDeltas::trackMute); tree.setProperty(delta, this->getTrackMuteStateAsString(), nullptr); return tree; } ValueTree PianoTrackNode::serializeColourDelta() const { using namespace Serialization::VCS; ValueTree tree(MidiTrackDeltas::trackColour); tree.setProperty(delta, this->getTrackColour().toString(), nullptr); return tree; } ValueTree PianoTrackNode::serializeInstrumentDelta() const { using namespace Serialization::VCS; ValueTree tree(MidiTrackDeltas::trackInstrument); tree.setProperty(delta, this->getTrackInstrumentId(), nullptr); return tree; } ValueTree PianoTrackNode::serializeEventsDelta() const { ValueTree tree(Serialization::VCS::PianoSequenceDeltas::notesAdded); for (int i = 0; i < this->getSequence()->size(); ++i) { const MidiEvent *event = this->getSequence()->getUnchecked(i); tree.appendChild(event->serialize(), nullptr); } return tree; } void PianoTrackNode::resetPathDelta(const ValueTree &state) { jassert(state.hasType(Serialization::VCS::MidiTrackDeltas::trackPath)); const String &path(state.getProperty(Serialization::VCS::delta)); this->setXPath(path, false); } void PianoTrackNode::resetMuteDelta(const ValueTree &state) { jassert(state.hasType(Serialization::VCS::MidiTrackDeltas::trackMute)); const String &muteState(state.getProperty(Serialization::VCS::delta)); const bool willMute = MidiTrack::isTrackMuted(muteState); if (willMute != this->isTrackMuted()) { this->setTrackMuted(willMute, false); } } void PianoTrackNode::resetColourDelta(const ValueTree &state) { jassert(state.hasType(Serialization::VCS::MidiTrackDeltas::trackColour)); const String &colourString(state.getProperty(Serialization::VCS::delta)); const Colour &colour(Colour::fromString(colourString)); if (colour != this->getTrackColour()) { this->setTrackColour(colour, false); } } void PianoTrackNode::resetInstrumentDelta(const ValueTree &state) { jassert(state.hasType(Serialization::VCS::MidiTrackDeltas::trackInstrument)); const String &instrumentId(state.getProperty(Serialization::VCS::delta)); this->setTrackInstrumentId(instrumentId, false); } void PianoTrackNode::resetEventsDelta(const ValueTree &state) { jassert(state.hasType(Serialization::VCS::PianoSequenceDeltas::notesAdded)); this->getSequence()->reset(); forEachValueTreeChildWithType(state, e, Serialization::Midi::note) { this->getSequence()->checkoutEvent<Note>(e); } this->getSequence()->updateBeatRange(false); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATIONINTERFACE_H #define BITCOIN_VALIDATIONINTERFACE_H #include <boost/signals2/signal.hpp> #include <boost/shared_ptr.hpp> #include <memory> class CBlock; class CBlockIndex; struct CBlockLocator; class CBlockIndex; class CConnman; class CReserveScript; class CTransaction; class CValidationInterface; class CValidationState; class uint256; // These functions dispatch to one or all registered wallets /** Register a wallet to receive updates from core */ void RegisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister a wallet from core */ void UnregisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister all wallets from core */ void UnregisterAllValidationInterfaces(); class CValidationInterface { protected: virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {} virtual void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) {} virtual void SetBestChain(const CBlockLocator &locator) {} virtual void UpdatedTransaction(const uint256 &hash) {} virtual void Inventory(const uint256 &hash) {} virtual void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) {} virtual void BlockChecked(const CBlock&, const CValidationState&) {} virtual void GetScriptForMining(boost::shared_ptr<CReserveScript>&) {}; virtual void ResetRequestCount(const uint256 &hash) {}; virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& block) {}; friend void ::RegisterValidationInterface(CValidationInterface*); friend void ::UnregisterValidationInterface(CValidationInterface*); friend void ::UnregisterAllValidationInterfaces(); }; struct CMainSignals { /** Notifies listeners of updated block chain tip */ boost::signals2::signal<void (const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip; /** A posInBlock value for SyncTransaction calls for tranactions not * included in connected blocks such as transactions removed from mempool, * accepted to mempool or appearing in disconnected blocks.*/ static const int SYNC_TRANSACTION_NOT_IN_BLOCK = -1; /** Notifies listeners of updated transaction data (transaction, and * optionally the block it is found in). Called with block data when * transaction is included in a connected block, and without block data when * transaction was accepted to mempool, removed from mempool (only when * removal was due to conflict from connected block), or appeared in a * disconnected block.*/ boost::signals2::signal<void (const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<void (const uint256 &)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void (const CBlockLocator &)> SetBestChain; /** Notifies listeners about an inventory item being seen on the network. */ boost::signals2::signal<void (const uint256 &)> Inventory; /** Tells listeners to broadcast their data. */ boost::signals2::signal<void (int64_t nBestBlockTime, CConnman* connman)> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; /** Notifies listeners that a key for mining is required (coinbase) */ boost::signals2::signal<void (boost::shared_ptr<CReserveScript>&)> ScriptForMining; /** Notifies listeners that a block has been successfully mined */ boost::signals2::signal<void (const uint256 &)> BlockFound; /** * Notifies listeners that a block which builds directly on our current tip * has been received and connected to the headers tree, though not validated yet */ boost::signals2::signal<void (const CBlockIndex *, const std::shared_ptr<const CBlock>&)> NewPoWValidBlock; }; CMainSignals& GetMainSignals(); #endif // BITCOIN_VALIDATIONINTERFACE_H
import "./App.css"; import { useState } from "react"; import { Routes, Route, useNavigate } from "react-router-dom"; import { getUser } from "../../utilities/users-service"; import Auth from "../AuthPage/AuthPage"; import NewOrder from "../NewOrderPage/NewOrderPage"; import OrderHistory from "../OrderHistoryPage/OrderHistoryPage"; import NavBar from "../../Components/NavBar/NavBar"; import Footer from "../../Components/Footer/Footer"; import Menu from "../MenuPage/MenuPage"; import Home from "../HomePage/HomePage"; import Rewards from "../RewardsPage/RewardsPage"; import About from "../AboutPage/AboutPage"; import Careers from "../CareersPage/CareersPage"; export default function App() { const [user, setUser] = useState(getUser()); const navigate = useNavigate(); function scrollToTop() { window.scrollTo(0, 0); } const handleLogin = () => { let path = `/login`; navigate(path) } return ( <main className="App"> <NavBar user={user} setUser={setUser} /> <Routes> {/* route components in here */} <Route path="/orders/new" element={<NewOrder scrollToTop={scrollToTop}/>} /> {/* <Route path="/orders" element={<OrderHistory />} /> */} <Route path="/menu" element={<Menu scrollToTop={scrollToTop}/>} /> <Route path="/" element={<Home user={user} handleLogin={handleLogin} scrollToTop={scrollToTop}/>} /> <Route path="/rewards" element={<Rewards handleLogin={handleLogin} scrollToTop={scrollToTop}/>} /> <Route path="/about" element={<About user={user} scrollToTop={scrollToTop}/>} /> <Route path="/careers" element={<Careers scrollToTop={scrollToTop}/>} /> <Route path="/login" element={<Auth setUser={setUser} scrollToTop={scrollToTop}/>} /> </Routes> <Footer/> </main> ); }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "SurvivalGame/Components/Inventory/Data/InventoryTypes.h" #include "SGInventoryComponent.generated.h" DECLARE_DELEGATE(FOnInventoryChangedSignature); UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class SURVIVALGAME_API USGInventoryComponent : public UActorComponent { GENERATED_BODY() public: USGInventoryComponent(); void Initialize(); FOnInventoryChangedSignature OnInventoryChanged; void SetCapacity(int32 NewColumns, int32 NewRows); void SetItems(TArray<UInventoryItem*> NewItems); bool TryAddItem(UInventoryItem* ItemToAdd); bool IsRoomAvailable(UInventoryItem* Item, int32 TopLeftIndex); UInventoryItem* GetItemAtIndex(int32 Index); FInventoryTile IndexToTile(int32 Index) const; int32 TileToIndex(FInventoryTile* Tile); void AddItem(UInventoryItem* ItemToAdd, int32 TopLeftIndex); void RemoveItem(UInventoryItem* ItemToRemove); TMap<UInventoryItem*, FInventoryTile> GetItemsAsMap() const; FORCEINLINE int32 GetColumns() const { return Columns; } FORCEINLINE int32 GetRows() const { return Rows; } FORCEINLINE TArray<UInventoryItem*> GetItems() const { return Items; } protected: virtual void BeginPlay() override; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Inventory | Parameters", DisplayName="Кол-во слотов в ширину") int32 Columns; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Inventory | Parameters", DisplayName="Кол-во слотов в длину") int32 Rows; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Inventory") TArray<UInventoryItem*> Items; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Inventory") TSubclassOf<AItem> ItemBaseClass; private: bool bIsDirty = false; };
from art import logo import random cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def choose_random_card(): card = random.choice(cards) return card def start_game(): player = [] computer = [] total_player_score = 0 total_computer_score = 0 print(logo) # Initial player.append(choose_random_card()) def draw_card(total_player_score, total_computer_score): player.append(choose_random_card()) computer.append(choose_random_card()) total_player_score = sum(player) total_computer_score = sum(computer) return total_player_score, total_computer_score def draw_card_for_computer( total_computer_score): computer.append(choose_random_card()) total_computer_score = sum(computer) return total_computer_score def check_score_for_player(): if total_player_score >= 21: return True return False def check_score_for_computer(): if total_computer_score >= 21: return True return False def check_result(total_player_score, total_computer_score): if total_computer_score==total_player_score: print('Draw!') elif total_player_score==21: print("Win with a Blackjack 😎") elif total_computer_score==21: print(" Lose with a Blackjack 😤") elif total_player_score>21: print("You went over. You lose 😤") elif total_computer_score>21: print("Opponent went over. You win 😁") elif total_computer_score>total_player_score: print("You lose 😤") elif total_player_score>total_computer_score: print("You win 😃") total_player_score, total_computer_score = draw_card( total_player_score, total_computer_score) print(f"Your cards: {player}, current score: {total_player_score}") print(f"Computer's first card: {total_computer_score}") if total_player_score>=21 or total_computer_score>=21: print() else: continue_draw_card = input( "Type 'y' to get another card, type 'n' to pass: ") while not check_score_for_computer() and not check_score_for_player() : if total_player_score>=21 or total_computer_score>=21: break if continue_draw_card=='y': total_player_score, total_computer_score = draw_card( total_player_score, total_computer_score) else: total_computer_score = draw_card_for_computer( total_computer_score) if total_player_score>=21 or total_computer_score>=21: break print(f"Your cards: {player}, current score: {total_player_score}") print(f"Computer's first card: {computer[0]}") continue_draw_card = input( "Type 'y' to get another card, type 'n' to pass: ") print(f"Your final hand: {player}, final score: {total_player_score}") print(f"Computer's final hand: {computer}, final score: {total_computer_score}") check_result(total_player_score, total_computer_score) if input("Do you want to play a game of Blackjack? Type 'y' or 'n':") == 'y': start_game() if input("Do you want to play a game of Blackjack? Type 'y' or 'n':") == 'y': start_game()
import 'package:fireauth/data/custom_widget_page.dart'; import 'package:fireauth/data/firebase_helper.dart'; import 'package:fireauth/screen/login_page.dart'; import 'package:flutter/material.dart'; class SingUpPage extends StatefulWidget { const SingUpPage({Key? key}) : super(key: key); @override State<SingUpPage> createState() => _SingUpPageState(); } class _SingUpPageState extends State<SingUpPage> { bool isObscure = true; bool Obscure=true; final _formkey = GlobalKey<FormState>(); TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController passwordController2 = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Padding( padding: const EdgeInsets.only(bottom: 50), child: Container( child: Form( key: _formkey, child: Column( children: [ Expanded( flex: 3, child: Container(child: Image.asset("images/logo.png"))), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Container( child: Column( children: [ Expanded( flex: 1, child: Container( child: TextFormField( validator: (value) { if (value!.isEmpty) { return "email coun't be empty"; } if (value.length < 3) { return "Invalid email"; } if (!value.contains("@")) { return "Invalid user email"; } }, textInputAction: TextInputAction.next, controller: emailController, decoration: InputDecoration( hintText: "Enter your email", labelText: "Enter your email", prefixIcon: Icon(Icons.email), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5))), ))), Expanded( flex: 1, child: Container( child: TextFormField( validator: (value) { if (value!.isEmpty) { return "password coun't be empty"; } if (value.length < 6) { return "Password must be more than 6 digits"; } }, onEditingComplete: () { if (_formkey.currentState!.validate()) { print("successful"); } else { print("unsuccessful"); } }, controller: passwordController, obscureText: isObscure, textInputAction: TextInputAction.next, decoration: InputDecoration( hintText: "Enter your password", labelText: "Enter your password", suffixIcon: IconButton( onPressed: () { setState(() { isObscure = !isObscure; }); }, icon: Icon(Icons.visibility)), prefixIcon: Icon(Icons.password_outlined), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5))), ))), Expanded( flex: 1, child: Container( child: TextFormField( validator: (value) { if (value!.isEmpty) { return "password coun't be empty"; } if (value.length < 6) { return "Password must be more than 6 digits"; } if(value!=passwordController.text){ return "password dose not match"; } }, onEditingComplete: () { if (_formkey.currentState!.validate()) { print("successful"); } else { print("unsuccessful"); } }, controller: passwordController2, obscureText: Obscure, textInputAction: TextInputAction.next, decoration: InputDecoration( hintText: "Confirm password", labelText: "Confirm password", suffixIcon: IconButton( onPressed: () { setState(() { Obscure = !Obscure; }); }, icon: Icon(Icons.visibility)), prefixIcon: Icon(Icons.password_outlined), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5))), ))), ], )), )), Expanded( flex: 2, child: Container( child: Column( children: [ Expanded( flex: 2, child: GestureDetector( onTap: () { if (_formkey.currentState!.validate()) { print("succesful"); } else {} var e = emailController.text; var p = passwordController.text==passwordController2.text? passwordController.text:null; print(".....................................$p"); // var p2=passwordController2.text; var obj = FirebaseHelper().singup(e, p, context); }, child: Container( height: 200, width: 500, decoration: BoxDecoration(image: DecorationImage(image: AssetImage("images/button.png"))), child: Center(child: Text("Sing Up",style: mystyleroboto(17, Colors.white,FontWeight.w700),)), ))), Expanded( flex: 1, child: Center( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 70), child: Padding( padding: const EdgeInsets.symmetric(vertical: 1), child: Row( children: [ Expanded( child: Container( height: double.infinity, width: double.infinity, decoration:BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30), ), child:Padding( padding: const EdgeInsets.all(12.0), child: Container(height: double.infinity,width: double.infinity, child: Image.asset("images/facebook.png"), ), ) ) ), SizedBox( width: 10, ), Expanded( child:Container( height: double.infinity, width: double.infinity, decoration:BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30), ), child:Padding( padding: const EdgeInsets.all(12.0), child: Container(height: double.infinity,width: double.infinity, child: Image.asset("images/google.webp"), ), ) ) ), SizedBox( width: 10, ), Expanded( child: GestureDetector( onTap: () {}, child: Container( height: double.infinity, width: double.infinity, decoration:BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30), ), child:Padding( padding: const EdgeInsets.all(12.0), child: Container(height: double.infinity,width: double.infinity, child: Image.asset("images/phone.png"), ), ) )),) ], ), ), ), )), ], ), )), ], ), ), ), ), ); } }
# forms.py from django import forms from django.core.exceptions import ValidationError class CourseFilterForm(forms.Form): search = forms.CharField(label='Search', required=False) # Add more filter fields as needed class Estilos(forms.TextInput): CSS = {'all': ('red_estilos.css')} class EstilosInput(): attrs={'class': 'formInput'} class RegistrarForm(forms.Form): user = forms.CharField(label='Usuario', required=True) nombre = forms.CharField(label='Nombre', required=True) apellido = forms.CharField(label='Apellido:', required=True) email = forms.EmailField(label='Correo Electrónico', required=True) password = forms.CharField(label='Contraseña:', widget=forms.PasswordInput, required=True) passwordConfirm = forms.CharField(label='Confirmar Contraseña:', widget=forms.PasswordInput, required=True) def clean_user(self): if self.cleaned_data['user'] == "carlos": raise ValidationError("El usuario ya existe") return self.cleaned_data['user'] def clean(self): if self.cleaned_data['password'] != self.cleaned_data['passwordConfirm']: print("clave incorrecta") raise ValidationError("La contraseña no coincide") return self.cleaned_data #agregado 22 octubre, actualmente este registra el usuario y lo envìa a la tabla default del db (auth_user) class UserRegistrationForm(forms.Form): name = forms.CharField(label='Nombre', min_length=2) lastname = forms.CharField(label='Apellido', min_length=2) email = forms.EmailField(label='Correo Electrónico') password = forms.CharField(label='Contraseña', widget=forms.PasswordInput, min_length=6) password2 = forms.CharField(label='Confirmar Contraseña', widget=forms.PasswordInput, min_length=6) class ContactoForm(forms.Form): nombre = forms.CharField(label='Nombre', required=True) email = forms.EmailField(label='Correo Electrónico', required=True) telefono = forms.CharField(label='Telèfono:', required=True) mensaje = forms.CharField(label='Mensaje:', widget=forms.TextInput(attrs={'class': 'mensaje_form'}), required=True)
import { useContext, useEffect } from "react"; import style from "./Drawer.module.scss"; import { Context } from "../../Context"; import { nanoid } from "nanoid"; import { Editor } from "react-draft-wysiwyg"; import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css"; import { convertToHTML } from "draft-convert"; import { useState } from "react"; import { clearEditorContent } from "draftjs-utils"; import { ContentState, EditorState } from "draft-js"; import htmlToDraft from "html-to-draftjs"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faMinus, faPlus } from "@fortawesome/free-solid-svg-icons"; const Drawer = () => { const context = useContext(Context); const [activeItem, setActiveItem] = useState({}); const [initial, setInitial] = useState(true); useEffect(() => { const item = context.items.find((item) => item.id === context.itemID); setActiveItem({ ...item }); if (context.drawer && item) { const contentBlocks = htmlToDraft(item.html); const contentState = ContentState.createFromBlockArray( contentBlocks.contentBlocks ); const initialEditorState = EditorState.createWithContent(contentState); context.setEditorState(initialEditorState); } // eslint-disable-next-line }, [context.itemID]); useEffect(() => { if (!context.drawer && !initial) { const element = context.items.find((item) => item.id === activeItem.id); const items = [...context.items]; items.splice(items.indexOf(element), 1, activeItem); context.setItems(items); //context.setConvertedContent('') } setInitial(false); // eslint-disable-next-line }, [context.drawer]); const deleteOption = (id) => { const filteredOptions = activeItem.options.filter( (option) => option.id !== id ); setActiveItem({ ...activeItem, options: filteredOptions }); }; const addOption = () => { const newOptions = [ ...activeItem.options, { id: nanoid(), name: "Option", value: "" }, ]; setActiveItem({ ...activeItem, options: newOptions }); }; const closeDrawer = () => { let html = convertToHTML(context.editorState.getCurrentContent()); //context.setConvertedContent(html); const newLabel = context.editorState .getCurrentContent() .getPlainText("\u0001"); setActiveItem({ ...activeItem, label: newLabel, html: html }); context.setDrawer(false); context.setItemID(""); context.setEditorState(clearEditorContent(context.editorState)); }; return ( <div className={`${style.drawerWrapper} ${context.drawer && style.edit}`}> <div className={`${style.drawer} ${context.drawer && style.edit}`}> <div className={style.actions}> <button onClick={closeDrawer}>X</button> </div> <h2>{activeItem && activeItem.type}</h2> <h3>Set Label</h3> <Editor editorState={context.editorState} onEditorStateChange={context.setEditorState} editorClassName={style.editor} wrapperClassName={style.wrapper} toolbarClassName={style.toolbar} /> <div className={style.checkboxContainer}> <input type="checkbox" id="isRequired" checked={activeItem.required || false} onChange={(e) => setActiveItem({ ...activeItem, required: e.target.checked })} className={style.checkbox} /> <label htmlFor="isRequired">Required?</label> </div> {context.drawer && activeItem.type === "Dropdown" && ( <div className={style.options}> <button onClick={addOption} className={style.addOptButton}> <FontAwesomeIcon icon={faPlus} style={{ color: "#defecd" }} /> </button> <label>Add Option</label> <table > <thead> <tr> <th>Options</th> <th>Value</th> <th>Remove</th> </tr> </thead> {activeItem.options.map((option) => { return ( <tbody key={nanoid()}> <tr> <td> <input type="text" defaultValue={option.name} onChange={(e) => (option.name = e.target.value)} /> </td> <td> <input type="text" defaultValue={option.value} onChange={(e) => (option.value = e.target.value)} /> </td> <td> <button onClick={() => deleteOption(option.id)} className={style.delOptButton} > <FontAwesomeIcon icon={faMinus} style={{ color: "whitesmoke" }} /> </button> </td> </tr> </tbody> ); })} </table> </div> )} </div> </div> ); }; export default Drawer;
import React, { useEffect } from "react"; import "./AddedQuestions.css"; import { useNavigate } from "react-router-dom"; import { useCollection } from "../../hooks/useCollection"; import { useAuthContext } from "../../hooks/useAuthContext"; import { useStyles } from "../../hooks/useStyles"; import { useFirestore } from "../../hooks/useFirestore"; import { AnimatePresence, motion } from "framer-motion"; import arrow from "../../assets/leftArrowOrange.svg"; import trash from "../../assets/trash.svg"; import ItemList from "../../components/ItemList"; const pageVariants = { hidden: { opacity: 0, y: 50, }, visible: { opacity: 1, y: 0, transition: { delay: 0.1 }, }, exit: { opacity: 0, transition: { duration: 0.1 }, }, }; export default function AddedQuestions() { const { pickCardColor } = useStyles(); const navigate = useNavigate(); const { user } = useAuthContext(); const { documents, isPending, error } = useCollection( `users/${user.uid}/added` ); const { deleteDocument } = useFirestore(`users/${user.uid}/added`); /* const [correctedDocs, setCorrectedDocs] = useState([]); */ useEffect(() => { if (documents !== undefined) { //TODO: fix this /* const newTags = documents?.map((d) => d.tags.map((t) => translateTag(t))); console.log(newTags); setCorrectedDocs(documents); correctedDocs?.forEach((d, i) => (d.tags = newTags[i])); console.log("corrected docs: ", correctedDocs); */ } }, [documents]); /* const translateTag = (tag) => { const capitalizedString = tag.replace(/(?:^|\s|[-"'([{])+\S/g, (c) => c.toUpperCase() ); const stringWithSpaces = capitalizedString .replace(/([A-Z])/g, " $1") .trim(); return stringWithSpaces; }; */ return ( <motion.div variants={pageVariants} initial="hidden" animate="visible" exit="exit" className="container added-questions" > <h2 className="text-center"> <img src={arrow} alt="arrow" className="go-back" onClick={() => navigate(-1)} /> Added questions </h2> <ItemList documents={documents} isPending={isPending} error={error} noDocsMessage={"No added questions"} > <AnimatePresence mode={"popLayout"}> {documents?.map((q) => ( <motion.div layout animate={{ opacity: 1 }} exit={{ y: -100, opacity: 0 }} transition={{ duration: 0.4, type: "spring" }} className="card" key={q.id} style={{ backgroundColor: pickCardColor(q.tags), }} > <p>{q.question}</p> <p className="subheadline">Category:</p> <ul className="tags"> {q.tags !== undefined && q.tags.map((p) => <li key={p}>{p}</li>)} </ul> <div className="icon-wrapper"> <div> <img src={trash} alt="check icon" onClick={() => deleteDocument(q.id)} /> </div> </div> </motion.div> ))} </AnimatePresence> </ItemList> </motion.div> ); }
import java.util.Random; import java.util.List; import java.util.ArrayList; import java.util.stream.Collectors; //all stats here are as of the end of the 2023 season /** * This class simulates a 162-game baseball season for two different teams modeled after two different hitters.<br> These hitters have either the same or very similar OPS, but vastly different OBP and SLG from each other.<br> The purpose of this is to get a general idea of whether getting on base consistently or hitting for more power but less consistently is more important for scoring runs and winning.<br> Rafael Devers (active) and Eddie Collins (HOF) both have an .853 career OPS, but Eddie Collins's OBP is .424 while Rafael Devers's is .343, which makes them a perfect pair.<br> */ public class ObpSlgSim { //the ratio of productive outs to total outs, currently the MLB league average in 2023 //Sacrifice flies are counted among these, so in this simulation they count against batting average and slugging percentage. public static final double productiveOutRatio = 4456.0/16633; //the ratio of double plays to double play opportunities, the MLB league average in 2023 public static final double doublePlayRatio = 3466.0/34097; //the ratio of infield singles to outfield singles, the MLB league average in 2023 public static final double infieldHitRatio = 4480.0/26031; private static final boolean LOG_PAS = false; private static final boolean LOG_INNINGS = false; private static final boolean LOG_GAMES = false; private static class Player { private Random r; private int pa, k, oip, bbHbp, singles, doubles, triples, homers; public List<Integer> outcomes; private int[] thresholds; /** * @param paIn The number of plate appearances * @param kIn the number of strikeouts * @param oipIn The number of outs in play: PA - BB - HBP - SO - H * @param bbHbpIn The number of walks + hit-by-pitches * @param singlesIn The number of singles * @param doublesIn The number of doubles * @param triplesIn The number of triples * @param homersIn The number of home runs */ public Player(int paIn, int kIn, int oipIn, int bbHbpIn, int singlesIn, int doublesIn, int triplesIn, int homersIn) { pa = paIn; k = kIn; oip = oipIn; bbHbp = bbHbpIn; singles = singlesIn; doubles = doublesIn; triples = triplesIn; homers = homersIn; thresholds = new int[7]; thresholds[0] = k; thresholds[1] = thresholds[0] + oip; thresholds[2] = thresholds[1] + bbHbp; thresholds[3] = thresholds[2] + singles; thresholds[4] = thresholds[3] + doubles; thresholds[5] = thresholds[4] + triples; thresholds[6] = thresholds[5] + homers; r = new Random(); outcomes = new ArrayList<Integer>(); } /** * Copy constructor. * @param other The player to copy */ public Player(Player other) { pa = other.pa; k = other.k; oip = other.oip; bbHbp = other.bbHbp; singles = other.singles; doubles = other.doubles; triples = other.triples; homers = other.homers; thresholds = other.thresholds; r = new Random(); outcomes = new ArrayList<Integer>(); } /** Gets the result of a new plate appearance for this player based on pseudorandom number generation. * @return The number corresponding to the result of a new plate appearance. * 0: strikeout * 1: out in play * 2: walk or hit-by-pitch * 3: single * 4: double * 5: triple * 6: home run */ public int getPA() { int outcome = r.nextInt(pa); for(int i = 0; i < thresholds.length; i++) { if(outcome < thresholds[i]) { outcomes.add(i); return i; } } //this should never happen - if it does, ERROR! return -1; } /** * @return The unrounded on-base percentage of this player */ private double getRawOBP() { List<Integer> timesOnBase = outcomes.stream().filter(oc -> oc > 1).collect(Collectors.toList()); return (double)timesOnBase.size()/outcomes.size(); } /** * @return The unrounded slugging percentage of this player */ private double getRawSLG() { int tb = 0, ab = 0; for(int oc : outcomes) { if(oc != 2) ab++; if(oc > 2) tb += oc-2; } return (double)tb/ab; } /** * @return The on-base percentage of this player, rounded to the nearest thousandth */ public double getOBP() { return (double)Math.round(1000 * getRawOBP())/1000; } /** * @return the slugging percentage of this player, rounded to the nearest thousandth */ public double getSLG() { return (double)Math.round(1000 * getRawSLG())/1000; } /** * @return the on-base plus slugging percentage of this player, rounded to the nearest thousandth */ public double getOPS() { return (double)Math.round(1000 * (getRawOBP() + getRawSLG()))/1000; } } private static class Team { public Player[] lineup; public int runs; public final String name; public int wins, losses; /** * Creates a team with the given array of players and name. * @param players The players in their lineup order. * @param nameIn The name of the team. */ public Team(Player[] players, String nameIn) { name = nameIn; runs = 0; lineup = players; } /** * @return The number of total team plate appearances */ public int getPAs() { int pas = 0; for(Player p : lineup) { pas += p.outcomes.size(); } return pas; } /** * @return The number of total team at-bats */ public int getABs() { int abs = 0; for(Player p : lineup) { List<Integer> occs = p.outcomes.stream().filter(oc -> 2 != oc).collect(Collectors.toList()); abs += occs.size(); } return abs; } /** * Gets the number of times a particular occurence occurred for a team (e.g. single, double, triple, home run) * @return The number of times the given occurrence occurred for this team */ private int getNumOccurrences(int outcome) { int count = 0; for(Player p : lineup) { List<Integer> occs = p.outcomes.stream().filter(oc -> outcome == oc).collect(Collectors.toList()); count += occs.size(); } return count; } /** * @return The number of collective strikeouts by this team */ public int getStrikeouts() { return getNumOccurrences(0); } /** * @return The number of collective outs in play by this team */ public int getOutsInPlay() { return getNumOccurrences(1); } /** * @return The number of collective walks plus hit-by-pitches by this team */ public int getBbHbp() { return getNumOccurrences(2); } /** * @return The number of collective singles by this team */ public int getSingles() { return getNumOccurrences(3); } /** * @return The number of collective doubles by this team */ public int getDoubles() { return getNumOccurrences(4); } /** * @return The number of collective triples by this team */ public int getTriples() { return getNumOccurrences(5); } /** * @return The number of collective home runs by this team */ public int getHomers() { return getNumOccurrences(6); } /** * @return The number of collective times this team has reached base safely */ public int getTimesOnBase() { int count = 0; for(Player p : lineup) { List<Integer> occs = p.outcomes.stream().filter(oc -> oc > 1).collect(Collectors.toList()); count += occs.size(); } return count; } /** * @return The number of collective hits by this team */ public int getHits() { int count = 0; for(Player p : lineup) { List<Integer> occs = p.outcomes.stream().filter(oc -> oc > 2).collect(Collectors.toList()); count += occs.size(); } return count; } /** * @return The number of collective total bases by this team */ public int getTotalBases() { int tb = 0; for(Player p : lineup) { List<Integer> hits = p.outcomes.stream().filter(oc -> oc > 2).collect(Collectors.toList()); tb += hits.stream().reduce(0, (acc, val) -> acc + val - 2); } return tb; } /** * @return The collective batting average of this team */ public double getBA() { return (double)Math.round(1000 * (double)getHits()/getABs())/1000; } /** * @return The collective on-base percentage of this team */ public double getOBP() { return (double)Math.round(1000 * (double)getTimesOnBase()/getPAs())/1000; } /** * @return The collective slugging percentage of this team */ public double getSLG() { return (double)Math.round(1000 * (double)getTotalBases()/getABs())/1000; } /** * @return A String representing the win-loss record of this team */ public String getWL() { return wins + "-" + losses; } /** * @return The winning percentage of this team (wins / (wins + losses)), rounded to the nearest thousandth */ public double getWPCT() { double rawWpct = (double)wins/(wins+losses); return (double) Math.round(rawWpct * 1000)/1000; } } //To represent the result of a simulated inning private static class InningResult { int runsScored, nextBatter; public InningResult(int runsScoredIn, int nextBatterIn) { runsScored = runsScoredIn; nextBatter = nextBatterIn; } } /** * Simulates an inning. * @param firstBatter The batter leading off this inning. * @param team The batting team. * @param canWalkOff Tells if there is a chance this inning could end without three outs being recorded. True iff the home team is batting in the 9th inning or later. * @param downBy How many runs the batting team is trailing by. Only relevant if canWalkOff is true. * @return An InningResult showing the number of runs scored in the inning and the batter leading off next inning. */ private static InningResult simInning(int firstBatter, Player[] team, boolean canWalkOff, int downBy) { Random r = new Random(); int outs = 0; int runs = 0; int curBatter = firstBatter % team.length; boolean[] baserunners = new boolean[]{false, false, false}; while(outs < 3) { if(LOG_PAS) { if(baserunners[0]) { if(baserunners[1]) { if(baserunners[2]) { System.out.print("Bases loaded, "); } else { System.out.print("Runners at first and second, "); } } else { if(baserunners[2]) { System.out.print("Runners at first and third, "); } else { System.out.print("Runner at first, "); } } } else { if(baserunners[1]) { if(baserunners[2]) { System.out.print("Runners at second and third, "); } else { System.out.print("Runner at second, "); } } else { if(baserunners[2]) { System.out.print("Runner at third, "); } else { System.out.print("Bases empty, "); } } } System.out.println(outs + " out"); System.out.print("Batter #" + (curBatter+1) + ": "); } int outcome = team[curBatter].getPA(); switch(outcome) { case 0: //strikeout outs++; if(LOG_PAS) { System.out.print("Strikeout."); } break; case 1: //out in play if(outs < 2) { double prodOutRoll = r.nextDouble(); if(baserunners[0]) { if(prodOutRoll < doublePlayRatio) { if(LOG_PAS) { System.out.print("Grounds into double play."); } //GIDP outs++; if(outs < 2) { if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } baserunners[2] = baserunners[1]; baserunners[1] = false; baserunners[0] = false; } } else if(prodOutRoll < doublePlayRatio + productiveOutRatio) { if(LOG_PAS) { System.out.print("Productive out."); } //productive out; every runner moves up a base if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } baserunners[2] = baserunners[1]; baserunners[1] = baserunners[0]; if(LOG_PAS) { if(baserunners[2]) { System.out.print(" Runner advances from second to third."); } if(baserunners[1]) { System.out.print(" Runner advances from first to second."); } } baserunners[0] = false; } } else { if(prodOutRoll < productiveOutRatio) { if(LOG_PAS) { System.out.print("Productive out."); } //productive out; every runner moves up a base if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } baserunners[2] = baserunners[1]; baserunners[1] = baserunners[0]; baserunners[0] = false; } } } else { if(LOG_PAS) { System.out.print("Out in play."); } } outs++; if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } break; case 2: //walk or hit by pitch if(LOG_PAS) { System.out.print("Walk or hit-by-pitch."); } if(baserunners[0]) { if(baserunners[1]) { if(baserunners[2]) { runs++; if(LOG_PAS) { System.out.print(" Runner scores from third."); } } else { baserunners[2] = true; } if(LOG_PAS) { System.out.print(" Runner advances from second to third."); } } else { baserunners[1] = true; } if(LOG_PAS) { System.out.print(" Runner advances from first to second."); } } else { baserunners[0] = true; } if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } break; case 3: //single if(LOG_PAS) { System.out.print("Single."); } if(baserunners[2]) { runs++; if(LOG_PAS) { System.out.print(" Runner scores from third."); } if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } } baserunners[2] = baserunners[1]; baserunners[1] = baserunners[0]; baserunners[0] = true; double infieldHitRoll = r.nextDouble(); if(infieldHitRoll >= infieldHitRatio) { //outfield single: score the runner originally on second if there is one if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from second."); } runs++; baserunners[2] = false; if(canWalkOff && downBy < runs) { return new InningResult(runs, (curBatter + 1) % team.length + 1); } } if(baserunners[1] && LOG_PAS) { System.out.print(" Runner advances from first to second."); } } else if(LOG_PAS) { System.out.print(" Infield single."); if(baserunners[2]) { System.out.print(" Runner advances from second to third."); } if(baserunners[1]) { System.out.print(" Runner advances from first to second."); } } break; case 4: //double if(LOG_PAS) { System.out.print("Double."); } if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } if(baserunners[1]) { if(LOG_PAS) { System.out.print(" Runner scores from second."); } runs++; } baserunners[2] = baserunners[0]; if(LOG_PAS && baserunners[2]) { System.out.print(" Runner advances from first to third."); } baserunners[1] = true; baserunners[0] = false; if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } break; case 5: //triple if(LOG_PAS) { System.out.print("Triple."); } if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } if(baserunners[1]) { if(LOG_PAS) { System.out.print(" Runner scores from second."); } runs++; } if(baserunners[0]) { if(LOG_PAS) { System.out.print(" Runner scores from first."); } runs++; } baserunners[2] = true; baserunners[1] = false; baserunners[0] = false; if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } break; case 6: //home run if(LOG_PAS) { System.out.print("Home run."); } if(baserunners[2]) { if(LOG_PAS) { System.out.print(" Runner scores from third."); } runs++; } if(baserunners[1]) { if(LOG_PAS) { System.out.print(" Runner scores from second."); } runs++; } if(baserunners[0]) { if(LOG_PAS) { System.out.print(" Runner scores from first."); } runs++; } runs++; baserunners[2] = false; baserunners[1] = false; baserunners[0] = false; if(canWalkOff && downBy < runs) { if(LOG_PAS) { System.out.println(" Walk-off RBI!"); } return new InningResult(runs, (curBatter + 1) % team.length + 1); } break; default: //should never happen if(LOG_PAS) { System.out.println("ERROR: Unknown PA outcome " + outcome); } throw new RuntimeException("ERROR: Unknown PA outcome " + outcome); } curBatter = (curBatter + 1) % team.length; if(LOG_PAS) { System.out.println(" Next up: " + (curBatter + 1)); } } if(LOG_INNINGS || LOG_PAS) { System.out.println("End of the inning. " + runs + " run(s) scored."); } return new InningResult(runs, curBatter); } /** * Simulates a game between two teams. * @param awayTeam The away team (batting first). * @param homeTeam The home team (batting second). * @return An array containing the number of runs scored by the away team, the number of runs scored by the home team, and the number of innings played (if not 9). */ static int[] playGame(Team awayTeam, Team homeTeam) { Player[] away = awayTeam.lineup, home = homeTeam.lineup; int awayTeamRuns = 0, homeTeamRuns = 0; int awayTeamBatter = 0, homeTeamBatter = 0; int inning = 1; for(; inning < 9; inning++) { if(LOG_INNINGS) { System.out.println("Score: " + awayTeamRuns + " - " + homeTeamRuns); System.out.println("Top " + inning + ":"); } InningResult top = simInning(awayTeamBatter, away, false, homeTeamRuns - awayTeamRuns); awayTeamRuns += top.runsScored; awayTeamBatter = top.nextBatter; if(LOG_INNINGS) { System.out.println("Score: " + awayTeamRuns + " - " + homeTeamRuns); System.out.println("Bottom " + inning + ":"); } InningResult bottom = simInning(homeTeamBatter, home, false, awayTeamRuns - homeTeamRuns); homeTeamRuns += bottom.runsScored; homeTeamBatter = bottom.nextBatter; } do { if(LOG_INNINGS) { System.out.println("Score: " + awayTeamRuns + " - " + homeTeamRuns); System.out.println("Top " + inning + ":"); } InningResult top = simInning(awayTeamBatter, away, false, homeTeamRuns - awayTeamRuns); awayTeamRuns += top.runsScored; awayTeamBatter = top.nextBatter; if(awayTeamRuns >= homeTeamRuns) { if(LOG_INNINGS) { System.out.println("Score: " + awayTeamRuns + " - " + homeTeamRuns); System.out.println("Bottom " + inning + ":"); } InningResult bottom = simInning(homeTeamBatter, home, true, awayTeamRuns - homeTeamRuns); homeTeamRuns += bottom.runsScored; homeTeamBatter = bottom.nextBatter; } inning++; } while(awayTeamRuns == homeTeamRuns); if(LOG_INNINGS || LOG_GAMES) { System.out.println("Final score: " + awayTeam.name + " " + awayTeamRuns + " - " + homeTeamRuns + " " + homeTeam.name + ((inning > 10)?(" in " + (inning-1) + " innings"):(""))); } awayTeam.runs += awayTeamRuns; homeTeam.runs += homeTeamRuns; if(awayTeamRuns > homeTeamRuns) { awayTeam.wins++; homeTeam.losses++; } else { awayTeam.losses++; homeTeam.wins++; } if(inning > 10) { return new int[]{awayTeamRuns, homeTeamRuns, inning-1}; } return new int[]{awayTeamRuns, homeTeamRuns}; } public static void main(String[] args) { //Eddie Collins, Rafael Devers Player p1 = new Player(12087, 467, 6729, 1576, 2643, 438, 187, 47), p2 = new Player(3614, 747, 1626, 322, 519, 221, 7, 172); Player[] t1 = new Player[9], t2 = new Player[9]; for(int i = 0; i < 9; i++) { t1[i] = new Player(p1); t2[i] = new Player(p2); } Team highObp = new Team(t1, "High OBP"), highSlg = new Team(t2, "High SLG"); //playGame(highObp, highSlg); //alternate which team is at home every 3 games over the 162 game season int gameNumber = 1; for(int i = 0; i < 54; i++) { for(int j = 0; j < 3; j++) { if(LOG_GAMES) { System.out.print("Game #" + gameNumber + ": "); } if(0 == i%2) { int[] score = playGame(highObp, highSlg); } else { int[] score = playGame(highSlg, highObp); } gameNumber++; } } if(LOG_GAMES) { int seasonLength = gameNumber-1; System.out.println("The " + seasonLength + "-game season has concluded."); } System.out.println("Records:"); System.out.println("Team High OBP: " + highObp.getWL() + " (" + highObp.getWPCT() + ")"); System.out.println("Team High SLG: " + highSlg.getWL() + " (" + highSlg.getWPCT() + ")"); System.out.println(); System.out.println("Batting stats:"); double highObpOBP = highObp.getOBP(), highObpSLG = highObp.getSLG(), highSlgOBP = highSlg.getOBP(), highSlgSLG = highSlg.getSLG(); System.out.println("Team High OBP: " + highObp.getBA() + "/" + highObpOBP + "/" + highObpSLG + " (" + (highObpOBP + highObpSLG) + " OPS), " + highObp.runs + " runs scored"); System.out.println("Team High SLG: " + highSlg.getBA() + "/" + highSlgOBP + "/" + highSlgSLG + " (" + (highSlgOBP + highSlgSLG) + " OPS), " + highSlg.runs + " runs scored"); } }
import { useRouter } from 'next/router' import { useConfig } from 'nextra-theme-docs' import Logo from "src/components/assets/logo"; import LogoFull from 'src/components/assets/logoFull'; // eslint-disable-next-line import/no-anonymous-default-export export default { logo: <span>Kreatifika Kitab ChatGPT</span>, // project: { // link: 'https://github.com/shuding/nextra' // }, useNextSeoProps() { return { titleTemplate: "%s – Kreatifika", }; }, toc: { float: true, title: "Pada Halaman Ini", backToTop: true }, search: { placeholder: "Cari Prompt...", }, editLink: { text: "", }, feedback: { content: "Ada Pertanyaan? E-mail kami →", labels: "feedback", useLink() { const config = useConfig(); return `mailto:test@example.com?subject=${encodeURIComponent( `Saya memiliki pertanyaan pada ${config.title}` )}`; }, }, sidebar: { titleComponent({ title, type }) { if (type === 'separator') { return <span className="cursor-default">{title}</span> } return <>{title}</> }, defaultMenuCollapseLevel: 1, toggleButton: true }, logo: () => { const title = "Kitab ChatGPT Perintah Super Canggih!"; return ( <> <Logo height={12} /> <span className="mx-2 font-extrabold hidden md:inline select-none" style={{ marginLeft: "4px" }} title={`Kreatifika: ${title}`} > Kitab ChatGPT </span> </> ); }, head: () => { // eslint-disable-next-line react-hooks/rules-of-hooks const { route } = useRouter(); // eslint-disable-next-line react-hooks/rules-of-hooks const { frontMatter, title } = useConfig(); const titleSuffix = "Kitab ChatGPT Perintah Super Canggih!"; const description = "Kumpulan Perintah ChatGPT yang akan memaksimalkan cara kerja ChatGPT. Dapatkan ekslusif prompt library yang akan selalu update setiap minggunya."; const imageUrl = new URL("https://i.ibb.co/pKxmNnh/Frame-1-1.png"); if (!/\/index\.+/.test(route)) { imageUrl.searchParams.set("title", title || titleSuffix); } const ogTitle = title ? `${title} – Kreatifika` : `Kreatifika: ${titleSuffix}`; const ogDescription = frontMatter.description || description; const ogImage = frontMatter.image || imageUrl.toString(); return ( <> {/* Favicons, meta */} <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png" /> <link rel="icon" type="image/svg+xml" href="/favicon/favicon.svg" /> <link rel="manifest" href="/favicon/site.webmanifest" /> <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#000000" /> <meta name="msapplication-TileColor" content="#ffffff" /> <meta name="apple-mobile-web-app-title" content="SWR" /> <meta name="description" content={ogDescription} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@vercel" /> <meta name="twitter:image" content={ogImage} /> <meta property="og:title" content={ogTitle} /> <meta property="og:description" content={ogDescription} /> <meta property="og:image" content={ogImage} /> </> ); }, footer: { text: () => { return ( <a href={`https://kreatifika.com`} target="_blank" rel="noopener" className="inline-flex items-center no-underline text-current font-semibold" > <span className="mr-2">Powered By</span> <span> <LogoFull /> </span> </a> ); }, }, gitTimestamp({ timestamp }) { // eslint-disable-next-line react-hooks/rules-of-hooks const { locale } = useRouter(); const lastUpdatedOn = "Terakhir diperbaharui"; return ( <> {lastUpdatedOn}{" "} <time dateTime={timestamp.toISOString()}> {timestamp.toLocaleDateString(locale, { day: "numeric", month: "long", year: "numeric", })} </time> </> ); }, // ... other theme options }
import { useGitHubAutomatedRepos, ProjectIcons, StackIcons } from 'github-automated-repos'; import { useTheme } from '../ui/theme-provider'; function GitHub() { const data = useGitHubAutomatedRepos("nerigleston", "deploy"); const { theme } = useTheme(); const isDarkTheme = theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches); return ( <div className={`container mx-auto mt-10 ${isDarkTheme ? 'dark' : 'light'}`}> {data.map((item) => ( <div key={item.id} className={`bg-gray-300 dark:bg-gray-800 p-6 shadow-lg rounded-lg mb-6 ${isDarkTheme ? 'text-white' : 'text-gray-700'}`}> <div className="flex flex-wrap mb-4"> {item.topics.map((icon) => ( <ProjectIcons key={icon} className="project_Icon mr-2 mb-2" iconItem={icon} /> ))} </div> <a href={item.html_url} className={`text-xl font-bold ${isDarkTheme ? 'text-blue-400' : 'text-blue-500'} hover:underline`}> <h1 className="text-lg sm:text-xl md:text-2xl lg:text-3xl xl:text-4xl">{item.name}</h1> </a> <p className={`${isDarkTheme ? 'text-gray-300' : 'text-gray-700'} mt-2 text-sm sm:text-base`}>{item.description}</p> {item.homepage && ( <a href={item.homepage} className={`text-blue-500 ${isDarkTheme ? 'dark:hover:underline' : 'hover:underline'}`}> <h3 className="mt-2">Homepage</h3> </a> )} <div className="flex flex-wrap mt-4"> {item.topics.map((icon) => ( <div key={icon} className="mr-4 mb-2"> <StackIcons key={`icon-${icon}`} className="stack_Icon" itemTopics={icon} /> </div> ))} </div> </div> ))} </div> ); } export default GitHub;
> Все сочетания описаны для VS Code на Windows > ↓ / ↑ / ← / → — стрелки вниз, вниз и т.д. > ЛКМ / ПКМ / СКМ — левая, правая, средняя кнопки мышки соответственно. 1. **Shift + Tab** — сместить табуляцию на один шаг влево. Если вы пишете на Python, то табуляция или четыре пробела — ваш неизменный спутник. Но мало кто знает, что достаточно поставить курсор в любое место строки, нажать Shift + Tab и вуаля, вся строка смещается влево на «один таб». ![Shift + Tab](https://habrastorage.org/getpro/habr/upload_files/ff7/159/b4e/ff7159b4e42e3e0077ae4dce96a46180.gif "Shift + Tab") 2. **Ctrl + /** — закомментировать или раскомментировать строку. VS Code сам разберется, какой язык программирования вы используете, и в начале строки установит или удалит необходимый символ для комментария. Место, где находится курсор на строке неважно. ![Ctrl + /](https://habrastorage.org/getpro/habr/upload_files/378/2b8/b19/3782b8b19839beb9b839c52c02324047.gif "Ctrl + /") 3. **Shift + Del** — удалить строку целиком. Теперь не нужно выделять мышкой всю строку и потом нажимать Backspace. Не нужно выделять всю строку. Правда! ![Shift + Del](https://habrastorage.org/getpro/habr/upload_files/79b/348/98c/79b34898c8baf5e0495e5ec88970c5e5.gif "Shift + Del") 4. **Alt + ↑ / ↓** — перемещение строки с курсором вверх или вниз. Просто попробуйте и ощутите, насколько это удобно. Знаете шутку «стоит всего один раз зимой надеть подштанники, и ты уже не можешь остановиться»? Так вот стоит только один раз переместить так строку, и вы уже не сможете по-другому! ![Alt + ↑ / ↓](https://habrastorage.org/getpro/habr/upload_files/4de/bd6/b4e/4debd6b4ec2c01524edbdc4cf83744c0.gif "Alt + ↑ / ↓") 5. **Shift + Alt + ↓ / ↑** — дублирование строки с курсором вниз. В зависимости от ↓ или ↑ курсор останется на текущей или новой строке. Теперь можно обойтись без Ctrl + C, хотя нет, нельзя =) ![Alt + ↑ / ↓](https://habrastorage.org/getpro/habr/upload_files/d37/6df/40f/d376df40f2b7d799267c2fd32a75c10e.gif "Alt + ↑ / ↓") 6. **F2** — переименовать переменную. Прошу заметить, что переименовываются все переменные с таким названием только внутри блока, не внутри всего открытого файла. Часто нужно переименовать переменную, которая уже используется в нескольких местах функции, и тут либо вручную расставлять курсор в нужное место, либо поставить курсор на переменную и нажать F2. ![F2](https://habrastorage.org/getpro/habr/upload_files/a49/9b1/737/a499b1737bbbbbb870857077e151dec9.gif "F2") 7. **F12** или **Alt + ЛКМ** на переменной — перейти к переменной или родительскому классу. Часто рассказывают про PyCharm, будто только он умеет проваливаться в родительские классы, чтобы посмотреть, какие его атрибуты мы можем переопределять, наследуясь от него; но так умеет и VS Code. ![F12 или Alt + ЛКМ](https://habrastorage.org/getpro/habr/upload_files/c44/625/9d5/c446259d57475d8b3ad832045007e7a8.gif "F12 или Alt + ЛКМ") 8. **Ctrl + D** — выделяет слово, на котором находится курсор. Следующее нажатие на D (удерживая Ctrl) выделить следующее по порядку вниз идентичное значение. Вот пишете вы функцию, и вам нужно выделить ближайшие значения ‘name’. Легко! Выделить все вхождения слова можно вот так — Ctrl + F2. Радует то, что курсор оказывается в конце каждого выделенного значения и сразу можно редактировать! ![Ctrl + D](https://habrastorage.org/getpro/habr/upload_files/75a/074/56d/75a07456def328e86361306438c0af05.gif "Ctrl + D") 9. **Ctrl + L** — выделяет всю строку. Целиком. Теперь копипастить еще проще, не правда ли? =) ![Ctrl + L](https://habrastorage.org/getpro/habr/upload_files/4df/3e3/99f/4df3e399fbb96aa3f47a9218268f5c8c.gif "Ctrl + L") 10. **Ctrl + Alt + →** — разделить рабочую область и переместить актуальную вкладку вправо. **Ctrl + Alt + ←** возвращает вкладку назад. Вы не поверите, насколько удобно видеть, например, [_models.py_](http://models.py/) и [_views.py_](http://views.py/) рядом. ![Ctrl + Alt + →](https://habrastorage.org/getpro/habr/upload_files/231/545/4a7/2315454a7de74313a687a5b8da47a746.gif "Ctrl + Alt + →") А теперь неочевидные, но потрясающие возможности. Меню → Файл → Настройки → Сочетания клавиш (Ctrl + K + Ctrl + S), в строке поиска вводим необходимый параметр и кликаем по результату мышкой, после нажимаем нужные клавиши для установки пользовательской настройки и наслаждаемся. Команды, которые точно стоит попробовать: `editor.action.jumpToBracket` — переход к парной скобке, у меня установлено на Ctrl + Q. Сначала переход к ближайшей скобке, а следующее нажатие перемещает вас к парной скобке и так далее. Часто нам нужно оказаться либо в начале скобок, либо в конце. А кликать мышкой или стрелками не всегда удобно. Теперь достаточно одного нажатия и вы у нужной скобки. ![Ctrl + Alt + →](https://habrastorage.org/getpro/habr/upload_files/dda/839/8c2/dda8398c28730ecdc15dbd98c06128f2.gif "Ctrl + Alt + →") Ctrl + Alt + → `editor.action.selectToBracket` — выделить все внутри ближайших скобок и сами скобки, у меня это Ctrl + Shift + Q. Сколько кликов мышкой, сколько ошибок, выделяя внутри скобок мышкой или Shift + стрелки. А теперь можно просто одним нажатием выделить все точно и быстро. ![editor.action.selectToBracket](https://habrastorage.org/getpro/habr/upload_files/cd3/ebc/05a/cd3ebc05a81487127c47e0ac7de0fcbe.gif "editor.action.selectToBracket") editor.action.selectToBracket Буду благодарен за любые интересные и полезные хоткеи, пишите в комментариях, что понравилось из моих, и что вы используете сами?
<!DOCTYPE html> <html lang="zh-CN> <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,min-width:1.0,max-width:1.0,user-scalable:0 "> <title>Document</title> <style> div { /* 弹性布局 不需要浮动也能一排 这里是父盒子,可以添加属性控制子盒子item的排序规则*/ display: flex; width: 100%; height: 100%; background-color: bisque; /* 主轴设置,row横x column竖排y reverse反转 column再次反转*/ flex-direction: row; /* 主轴子元素排序,flew-start头end尾巴 center居中 space-around平分空间,space-between先两边贴再平分空间。 */ justify-content: space-between; /* 多个盒子,会自己压缩空间,所以要自动换行 */ flex-wrap: wrap; /* 交叉y轴设置方向 同理主轴 如果是多行只能使用align-content,此属性有平分*/ align-items: center; } div span { width: 100px; height: 200px; background-color: pink; margin: 10px; /* flex: 1; 现在可以按比例分,既可以撑开盒子,又不需要清楚浮动,还是横排。不给宽度。就是占几份的意思 */ /* 可以控制单独y轴子项的排序 同样是单独的*/ align-self: auto; /* 排序,越大越前 需要单独设置样式,div span:nth-child(3): ;*/ order: -1; } </style> </head> <body> <div> <span>1</span> <span>2</span> <span>3</span> <span>4</span> <!-- 多个盒子,会自己压缩空间,所以要自动换行 --> <span>5</span> </div> </body> </html>
package es.uca.iw.views.Reclamaciones; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.Route; import com.vaadin.flow.theme.lumo.LumoUtility.Background; import com.vaadin.flow.theme.lumo.LumoUtility.BorderRadius; import com.vaadin.flow.theme.lumo.LumoUtility.Display; import com.vaadin.flow.theme.lumo.LumoUtility.FlexDirection; import com.vaadin.flow.theme.lumo.LumoUtility.FontSize; import com.vaadin.flow.theme.lumo.LumoUtility.Gap; import com.vaadin.flow.theme.lumo.LumoUtility.Margin; import com.vaadin.flow.theme.lumo.LumoUtility.Margin.Horizontal; import com.vaadin.flow.theme.lumo.LumoUtility.Margin.Vertical; import com.vaadin.flow.theme.lumo.LumoUtility.Padding; import com.vaadin.flow.component.textfield.TextArea; import com.vaadin.flow.component.Text; import es.uca.iw.services.ComplaintService; import es.uca.iw.model.Complaint; import es.uca.iw.views.MainUserLayout; import jakarta.annotation.security.RolesAllowed; import java.util.List; @Route(value = "user/Reclamaciones", layout = MainUserLayout.class) @RolesAllowed({"ADMIN", "USER"}) public class ReclamacionesView extends VerticalLayout { private Grid<Complaint> grid; private ComplaintService complaintService; private Dialog dialog; public ReclamacionesView(ComplaintService complaintService) { this.complaintService = complaintService; addClassNames(Padding.MEDIUM, Display.FLEX, FlexDirection.COLUMN, Gap.LARGE, Horizontal.AUTO, Vertical.AUTO); H2 header = new H2("MIS RECLAMACIONES"); header.addClassNames(Horizontal.AUTO, FontSize.XXLARGE, Background.CONTRAST_5, BorderRadius.MEDIUM, Padding.MEDIUM, Margin.SMALL); header.getStyle().set("color", "blue"); add(header); grid = new Grid<>(Complaint.class); grid.setColumns("id", "description", "creationDate", "status", "comments"); grid.getColumnByKey("id").setHeader("ID"); grid.getColumnByKey("description").setHeader("Descripción"); grid.getColumnByKey("creationDate").setHeader("Fecha de Creación"); grid.getColumnByKey("status").setHeader("Estado"); grid.getColumnByKey("comments").setHeader("Comentarios"); grid.addComponentColumn(complaint -> { Button accionesButton = new Button("Acciones"); accionesButton.addClickListener(e -> mostrarAcciones(complaint)); return accionesButton; }).setHeader("Acciones"); Button añadirReclamacionButton = new Button("Añadir Reclamación"); añadirReclamacionButton.addClickListener(e -> mostrarFormularioAñadirReclamacion()); add(añadirReclamacionButton); add(grid); actualizarTablaReclamacionesUsuarioAutenticado(); } private void mostrarAcciones(Complaint complaint) { dialog = new Dialog(); dialog.setCloseOnOutsideClick(false); FormLayout formLayout = new FormLayout(); Button opcion1Button = new Button("Eliminar Reclamación"); opcion1Button.addClickListener(e -> mostrarConfirmacionEliminarReclamacion(complaint)); Button opcion2Button = new Button("Añadir Comentarios"); opcion2Button.addClickListener(e -> mostrarFormularioAñadirComentarios(complaint)); Button verComentariosButton = new Button("Ver Comentarios"); verComentariosButton.addClickListener(e -> mostrarComentarios(complaint)); formLayout.add(opcion1Button, opcion2Button, verComentariosButton); dialog.add(formLayout); dialog.open(); } private void mostrarConfirmacionEliminarReclamacion(Complaint complaint) { Dialog confirmDialog = new Dialog(); confirmDialog.setCloseOnOutsideClick(false); VerticalLayout confirmLayout = new VerticalLayout(); Span confirmMessage = new Span("¿Estás seguro de que deseas eliminar esta reclamación?"); Button confirmButton = new Button("Confirmar"); confirmButton.addClickListener(e -> { eliminarReclamacion(complaint); confirmDialog.close(); }); Button cancelButton = new Button("Cancelar"); cancelButton.addClickListener(e -> confirmDialog.close()); confirmLayout.add(confirmMessage); confirmLayout.setHorizontalComponentAlignment(FlexComponent.Alignment.CENTER, confirmMessage); HorizontalLayout buttonLayout = new HorizontalLayout(confirmButton, cancelButton); buttonLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); confirmLayout.add(buttonLayout); confirmDialog.add(confirmLayout); confirmDialog.open(); } private void eliminarReclamacion(Complaint complaint) { complaintService.eliminarReclamacion(complaint.getId()); actualizarTablaReclamacionesUsuarioAutenticado(); dialog.close(); } private void mostrarFormularioAñadirComentarios(Complaint complaint) { Dialog comentariosDialog = new Dialog(); comentariosDialog.setCloseOnOutsideClick(false); FormLayout comentariosFormLayout = new FormLayout(); Span comentariosLabel = new Span("Comentarios"); TextArea comentariosField = new TextArea(); comentariosField.setWidthFull(); Button confirmarComentariosButton = new Button("Confirmar"); confirmarComentariosButton.addClickListener(e -> { addComentariosAReclamacion(complaint, comentariosField.getValue()); actualizarTablaReclamacionesUsuarioAutenticado(); comentariosDialog.close(); }); comentariosFormLayout.add(comentariosLabel, comentariosField, confirmarComentariosButton); comentariosDialog.add(comentariosFormLayout); comentariosDialog.open(); } private void addComentariosAReclamacion(Complaint complaint, String comentarios) { complaintService.addComentariosAReclamacion(complaint, comentarios); } private void mostrarFormularioAñadirReclamacion() { Dialog dialog = new Dialog(); dialog.setCloseOnOutsideClick(false); FormLayout formLayout = new FormLayout(); Span descripcionLabel = new Span("Descripción *"); TextArea descripcionField = new TextArea(); descripcionField.setWidthFull(); Span comentariosLabel = new Span("Comentarios"); TextArea comentariosField = new TextArea(); comentariosField.setWidthFull(); Button confirmarButton = new Button("Confirmar"); confirmarButton.addClickListener(e -> { String descripcion = descripcionField.getValue(); if (validarDescripcion(descripcion)) { formLayout.removeAll(); Complaint nuevaReclamacion = new Complaint(); nuevaReclamacion.setDescription(descripcion); List<String> nuevosComentarios = List.of(comentariosField.getValue()); nuevaReclamacion.setComments(nuevosComentarios); complaintService.addComplaint(nuevaReclamacion); actualizarTablaReclamacionesUsuarioAutenticado(); dialog.close(); } else { formLayout.removeAll(); Text errorText = new Text("Descripción inválida, por favor ingrese una descripción."); formLayout.add(errorText); } }); formLayout.add(descripcionLabel, descripcionField, comentariosLabel, comentariosField, confirmarButton); dialog.add(formLayout); dialog.open(); } private boolean validarDescripcion(String descripcion) { return descripcion != null && !descripcion.trim().isEmpty(); } private void mostrarComentarios(Complaint complaint) { Dialog comentariosDialog = new Dialog(); comentariosDialog.setCloseOnOutsideClick(true); String comentarios = String.join("\n", complaint.getComments()); TextArea comentariosTextArea = new TextArea(); comentariosTextArea.setValue(comentarios); comentariosTextArea.setReadOnly(true); comentariosTextArea.getStyle().set("width", "800px"); comentariosDialog.add(comentariosTextArea); comentariosDialog.open(); } private void actualizarTablaReclamacionesUsuarioAutenticado() { List<Complaint> reclamaciones = complaintService.getComplaintsByAuthenticatedUser(); grid.setItems(reclamaciones); } }
class MessageBox { constructor(typeMessage) { this.typeMessage = typeMessage this.durationId = null; } calcProgressBar() { let width = 100 this.durationId = setInterval(() => { this.progressBar.style.width = `${width}%`; if (width < 0) { this.close() } width--; }, 50) } open() { clearInterval(this.durationId); const divMessageBox = this.createBoxMessage(this.typeMessage); document.body.append(divMessageBox); this.boxContainer = document.querySelector(".boxWrapper"); this.progressBar = this.boxContainer.querySelector(".progressBar"); this.boxContainer.style.animationName = "appear"; this.calcProgressBar(); divMessageBox.querySelector('#close') .addEventListener('click', () => this.close()) } close() { clearInterval(this.durationId); this.boxContainer.style.animationName = "vanish"; } removeBoxMessage() { document.querySelectorAll('.boxMessage').forEach(div => { div.remove(); }) } createBoxMessage(typeMessage) { this.removeBoxMessage(); const typeMessages = { success: { title: "Sucesso", description: "Usuário cadastrado" }, alert: { title: "Alerta", description: "Usuário ja cadastrado" }, error: { title: "Erro", description: "Usuário não encontrado" } } const div = document.createElement('div'); div.classList.add('boxMessage') div.innerHTML = ` <div class="boxWrapper ${typeMessage}"> <div class="content"> <h2>${typeMessages[typeMessage].title}</h2> <p>${typeMessages[typeMessage].description}</p> </div> <div class="progressBar"></div> <ion-icon name="close-outline" id="close"></ion-icon> </div> ` return div; } } export const MessageAlert = new MessageBox('alert'); export const MessageError = new MessageBox('error'); export const MessageSuccess = new MessageBox('success');
import React from 'react' import BaseModal from './BaseModal' import { FaTrash } from 'react-icons/fa'; import { IoClose } from "react-icons/io5"; import { Spinner } from '../Common'; interface Props{ open: boolean handleClose:()=>void; children: React.ReactNode; deleteAction: ()=>void; isLoading:boolean } const DeleteModal = ({open, handleClose, children, deleteAction, isLoading}:Props) => { return ( <BaseModal open={open} handleClose={handleClose} > <div className="flex justify-between items-center "> <h3 className='font-bold'>Delete Content</h3> <div onClick={handleClose} className="cursor-pointer p-3 rounded-full hover:bg-gray-100"><IoClose /></div> </div> <p className="text-red-500 my-4"> {children} </p> <button onClick={deleteAction} className="w-full justify-center flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-red-500 bg-red-100 hover:bg-red-500 hover:text-white" > {isLoading ? <div className='flex items-center gap-1'> <FaTrash /> Delete <Spinner sm /> </div> : <> <FaTrash /> Delete </> } </button> </BaseModal> ) } export default DeleteModal
import React from 'react'; import {View} from 'react-native'; import styled from 'styled-components/native'; import {Theme} from '../theme'; interface Props { label: string; value: string | number; onChange: (text: string) => void; error?: string; style?: any; secure?: boolean; } const Input = ({ label, value = '', onChange, error = '', secure = false, style, }: Props) => ( <View style={style}> <Label>{label}</Label> <TextInput value={String(value)} onChangeText={onChange} secureTextEntry={secure} /> {!!error && <Error>{error}</Error>} </View> ); const Label = styled.Text` font-size: 14px; font-weight: 500; margin-bottom: 6px; `; const Error = styled.Text<Theme>` font-size: 13px; color: ${props => props.theme.error}; margin-top: 4px; `; const TextInput = styled.TextInput<Theme>` border: 1px solid ${props => props.theme.inputBorder}; padding: 10px 8px; `; export default Input;
import { CART_ACTION_TYPES, CartItem } from './cart.types'; import { createAction, ActionWithPayload, withMatcher } from '../../utils/reducer/reducer.utils'; import { CategoryItem } from '../categories/categories.types'; export const addCartItem = ( cartItems: CartItem[], cartItemToAdd: CategoryItem, cartItemToAddQuantity: number ): CartItem[] => { const existingCartItem = cartItems.find( (cartItem) => cartItem.id === cartItemToAdd.id ); if (existingCartItem) { return cartItems.map((cartItem) => cartItem.id === cartItemToAdd.id ? { ...cartItem, quantity: cartItem.quantity + cartItemToAddQuantity } : cartItem ) } else { return [...cartItems, { ...cartItemToAdd, quantity: cartItemToAddQuantity }]; } } export const removeCartItem = ( cartItems: CartItem[], cartItemToRemove: CartItem ): CartItem[] => { const existingCartItem = cartItems.find( (cartItem) => cartItem.id === cartItemToRemove.id ); if (existingCartItem && existingCartItem.quantity === 1) { return cartItems.filter((cartItem) => cartItem.id !== cartItemToRemove.id); } else { return cartItems.map((cartItem) => cartItem.id === cartItemToRemove.id ? { ...cartItem, quantity: cartItem.quantity - 1 } : cartItem ) } } export const clearCartItem = ( cartItems: CartItem[], cartItemToClear: CartItem ): CartItem[] => { return cartItems.filter((cartItem) => cartItem.id !== cartItemToClear.id); } export type setCartItems = ActionWithPayload<CART_ACTION_TYPES.SET_CART_ITEMS, CartItem[]>; export type setIsCheckoutDone = ActionWithPayload<CART_ACTION_TYPES.SET_IS_CHECKOUT_DONE, boolean>; export type setIsCartOpen = ActionWithPayload<CART_ACTION_TYPES.SET_IS_CART_OPEN, boolean>; export const addItemToCart = ( cartItems: CartItem[], cartItem: CategoryItem, cartItemToAddQuantity: number ) => { const newCartItems = addCartItem(cartItems, cartItem, cartItemToAddQuantity); return setCartItems(newCartItems); } export const removeItemFromCart = ( cartItems: CartItem[], cartItem: CartItem ) => { const newCartItems = removeCartItem(cartItems, cartItem); return setCartItems(newCartItems); } export const clearItemFromCart = ( cartItems: CartItem[], cartItem: CartItem ) => { const newCartItems = clearCartItem(cartItems, cartItem); return setCartItems(newCartItems); } export const setCartItems = withMatcher( (newCartItems: CartItem[]): setCartItems => { return createAction(CART_ACTION_TYPES.SET_CART_ITEMS, newCartItems); } ); export const setIsCheckoutDone = withMatcher( (isCheckoutDone: boolean): setIsCheckoutDone => { return createAction(CART_ACTION_TYPES.SET_IS_CHECKOUT_DONE, isCheckoutDone); } ); export const setIsCartOpen = withMatcher( (isCartOpen: boolean): setIsCartOpen => { return createAction(CART_ACTION_TYPES.SET_IS_CART_OPEN, isCartOpen); } );
use sodigy_intern::InternedString; use sodigy_parse::Punct; mod endec; mod fmt; #[derive(Clone, Copy)] pub enum PrefixOp { Not, Neg, } impl TryFrom<Punct> for PrefixOp { type Error = (); fn try_from(p: Punct) -> Result<Self, ()> { match p { Punct::Sub => Ok(PrefixOp::Neg), Punct::Not => Ok(PrefixOp::Not), _ => Err(()), } } } #[derive(Clone, Copy)] pub enum PostfixOp { Range, QuestionMark, } impl TryFrom<Punct> for PostfixOp { type Error = (); fn try_from(p: Punct) -> Result<Self, ()> { match p { Punct::DotDot => Ok(PostfixOp::Range), Punct::QuestionMark => Ok(PostfixOp::QuestionMark), _ => Err(()), } } } #[derive(Clone, Copy)] pub enum InfixOp { Add, Sub, Mul, Div, Rem, Eq, Gt, Lt, Ne, Ge, Le, BitwiseAnd, BitwiseOr, LogicalAnd, LogicalOr, Xor, ShiftRight, ShiftLeft, /// `[]` Index, /// `<>` Concat, /// `<+` Append, /// `+>` Prepend, /// `..` Range, /// `..~` InclusiveRange, /// `` ` `` FieldModifier(InternedString), } impl TryFrom<Punct> for InfixOp { type Error = (); fn try_from(p: Punct) -> Result<Self, ()> { match p { Punct::Add => Ok(InfixOp::Add), Punct::Sub => Ok(InfixOp::Sub), Punct::Mul => Ok(InfixOp::Mul), Punct::Div => Ok(InfixOp::Div), Punct::Rem => Ok(InfixOp::Rem), Punct::Concat => Ok(InfixOp::Concat), Punct::Eq => Ok(InfixOp::Eq), Punct::Gt => Ok(InfixOp::Gt), Punct::Lt => Ok(InfixOp::Lt), Punct::Ne => Ok(InfixOp::Ne), Punct::Ge => Ok(InfixOp::Ge), Punct::Le => Ok(InfixOp::Le), Punct::AndAnd => Ok(InfixOp::LogicalAnd), Punct::OrOr => Ok(InfixOp::LogicalOr), Punct::And => Ok(InfixOp::BitwiseAnd), Punct::Or => Ok(InfixOp::BitwiseOr), Punct::Xor => Ok(InfixOp::Xor), Punct::GtGt => Ok(InfixOp::ShiftRight), Punct::LtLt => Ok(InfixOp::ShiftLeft), Punct::Append => Ok(InfixOp::Append), Punct::Prepend => Ok(InfixOp::Prepend), Punct::DotDot => Ok(InfixOp::Range), Punct::InclusiveRange => Ok(InfixOp::InclusiveRange), Punct::FieldModifier(id) => Ok(InfixOp::FieldModifier(id)), // Don't use wildcard here Punct::At | Punct::Not | Punct::Assign | Punct::Comma | Punct::Dot | Punct::Colon | Punct::SemiColon | Punct::Backslash | Punct::Dollar | Punct::Backtick | Punct::QuestionMark | Punct::RArrow => Err(()), } } } impl TryFrom<PostfixOp> for InfixOp { type Error = (); fn try_from(op: PostfixOp) -> Result<Self, ()> { match op { PostfixOp::Range => Ok(InfixOp::Range), _ => Err(()) } } } pub(crate) fn postfix_binding_power(op: PostfixOp) -> u32 { match op { PostfixOp::Range => RANGE, PostfixOp::QuestionMark => QUESTION, } } pub(crate) fn prefix_binding_power(op: PrefixOp) -> u32 { match op { PrefixOp::Not | PrefixOp::Neg => NEG, } } /// ref: https://doc.rust-lang.org/reference/expressions.html#expression-precedence\ /// ref: https://hexdocs.pm/elixir/main/operators.html\ pub fn infix_binding_power(op: InfixOp) -> (u32, u32) { match op { InfixOp::Add | InfixOp::Sub => (ADD, ADD + 1), InfixOp::Mul | InfixOp::Div | InfixOp::Rem => (MUL, MUL + 1), InfixOp::Concat => (CONCAT, CONCAT + 1), InfixOp::Range | InfixOp::InclusiveRange => (RANGE, RANGE + 1), InfixOp::Index => (INDEX, INDEX + 1), InfixOp::Gt | InfixOp::Lt | InfixOp::Ge | InfixOp::Le => (COMP, COMP + 1), InfixOp::Eq | InfixOp::Ne => (COMP_EQ, COMP_EQ + 1), InfixOp::ShiftRight | InfixOp::ShiftLeft => (SHIFT, SHIFT + 1), InfixOp::BitwiseAnd => (BITWISE_AND, BITWISE_AND + 1), InfixOp::Xor => (XOR, XOR + 1), InfixOp::BitwiseOr => (BITWISE_OR, BITWISE_OR + 1), InfixOp::Append | InfixOp::Prepend => (APPEND, APPEND + 1), InfixOp::FieldModifier(_) => (MODIFY, MODIFY + 1), InfixOp::LogicalAnd => (LOGICAL_AND, LOGICAL_AND + 1), InfixOp::LogicalOr => (LOGICAL_OR, LOGICAL_OR + 1), } } pub fn call_binding_power() -> (u32, u32) { (CALL, CALL + 1) } pub fn path_binding_power() -> (u32, u32) { (PATH, PATH + 1) } pub fn index_binding_power() -> (u32, u32) { (INDEX, INDEX + 1) } pub fn struct_init_binding_power() -> (u32, u32) { (STRUCT_INIT, STRUCT_INIT + 1) } const PATH: u32 = 37; const STRUCT_INIT: u32 = 35; const CALL: u32 = 33; const INDEX: u32 = 31; const QUESTION: u32 = 29; const NEG: u32 = 27; const MUL: u32 = 25; const ADD: u32 = 23; const SHIFT: u32 = 21; const BITWISE_AND: u32 = 19; const XOR: u32 = 17; const BITWISE_OR: u32 = 15; const APPEND: u32 = 13; const CONCAT: u32 = 11; const RANGE: u32 = 11; const COMP: u32 = 9; const COMP_EQ: u32 = 7; const MODIFY: u32 = 5; const LOGICAL_AND: u32 = 3; const LOGICAL_OR: u32 = 1;
// // NetworkErrorHandler.swift // Pods // // Created by Elliot Schrock on 9/11/17. // // import Foundation import ReactiveSwift public protocol ErrorMessage { var message: String { get } var forCode: Int { get } } public protocol NetworkErrorHandler { var disposable: ScopedDisposable<CompositeDisposable> { get } static var errorMessages: [ErrorMessage]? { get } static func handle(error: NetworkError, messages: [String]) } public extension NetworkErrorHandler { func observe(signal: Signal<NSError, Never>) { disposable.inner.add(signal.observeValues({ error in Self.handle(error: NetworkError(message: error.localizedDescription, url: "", code: error.code), messages: []) })) } func observe(signal: Signal<(NetworkError, [String]), Never>) { disposable.inner.add(signal.observeValues({ (error, response) in Self.handle(error: error, messages: response) })) } func observe(signal: Signal<[NetworkError], Never>) { disposable.inner.add(signal.observeValues({ messages in Self.handle(error: messages.first ?? NetworkError(message: "", url: ""), messages: messages.map({ error in return error.message })) })) } } public class PrintNetworkErrorHandler: NetworkErrorHandler { public let disposable = ScopedDisposable(CompositeDisposable()) public static var errorMessages: [ErrorMessage]? public static func handle(error: NetworkError, messages: [String] = []) { for message in messages { print(message) } print(error.localizedDescription) } } extension UIAlertController { public func show(animated flag: Bool = true, completion: (() -> Void)? = nil) { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = UIViewController() window.backgroundColor = UIColor.clear window.windowLevel = UIWindow.Level.alert if let rootViewController = window.rootViewController { window.makeKeyAndVisible() rootViewController.present(self, animated: flag, completion: completion) } } } public class NetworkError: NSError { public var url: String var message: String init(message: String, url: String, code: Int = -1000) { self.message = message self.url = url super.init(domain: "NetworkError", code: code, userInfo: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var localizedDescription: String { return message } }
package com.strongit.oa.bo; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.apache.commons.lang.builder.ToStringBuilder; import org.hibernate.annotations.GenericGenerator; /** * @hibernate.class * table="T_OA_MSG_STATE_MEAN" * */ @Entity @Table(name="T_OA_MSG_STATE_MEAN") public class ToaMsgStateMean implements Serializable { /** identifier field */ private String msgStateId; /** nullable persistent field */ private String msgState; /** nullable persistent field */ private String msgStateMean; /** persistent field */ private com.strongit.oa.bo.ToaMessage toaMessage; private String modelCode;//模块ID private String increaseCode;//业务ID /** full constructor */ public ToaMsgStateMean(String msgStateId, String msgState, String msgStateMean, com.strongit.oa.bo.ToaMessage toaMessage) { this.msgStateId = msgStateId; this.msgState = msgState; this.msgStateMean = msgStateMean; this.toaMessage = toaMessage; } /** default constructor */ public ToaMsgStateMean() { } /** minimal constructor */ public ToaMsgStateMean(String msgStateId, com.strongit.oa.bo.ToaMessage toaMessage) { this.msgStateId = msgStateId; this.toaMessage = toaMessage; } /** * @hibernate.id * generator-class="assigned" * type="java.lang.String" * column="MSG_STATE_ID" * */ @Id @Column(name="MSG_STATE_ID", nullable=false,length = 32) @GeneratedValue(generator="hibernate-uuid") @GenericGenerator(name = "hibernate-uuid", strategy = "uuid") public String getMsgStateId() { return this.msgStateId; } public void setMsgStateId(String msgStateId) { this.msgStateId = msgStateId; } /** * @hibernate.property * column="MSG_STATE" * length="1" * */ @Column(name="MSG_STATE",nullable=true) public String getMsgState() { return this.msgState; } public void setMsgState(String msgState) { this.msgState = msgState; } /** * @hibernate.property * column="MSG_STATE_MEAN" * length="50" * */ @Column(name="MSG_STATE_MEAN",nullable=true) public String getMsgStateMean() { return this.msgStateMean; } public void setMsgStateMean(String msgStateMean) { this.msgStateMean = msgStateMean; } /** * @hibernate.many-to-one * not-null="true" * @hibernate.column name="MSG_ID" * */ @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="MSG_ID") public com.strongit.oa.bo.ToaMessage getToaMessage() { return this.toaMessage; } public void setToaMessage(com.strongit.oa.bo.ToaMessage toaMessage) { this.toaMessage = toaMessage; } /** * @hibernate.property * column="increaseCode" * length="32" * */ @Column(name="increaseCode",nullable=true) public String getIncreaseCode() { return increaseCode; } public void setIncreaseCode(String increaseCode) { this.increaseCode = increaseCode; } /** * @hibernate.property * column="MODEL_CODE" * length="3" * */ @Column(name="MODEL_CODE",nullable=true) public String getModelCode() { return modelCode; } public void setModelCode(String modelCode) { this.modelCode = modelCode; } public String toString() { return new ToStringBuilder(this) .append("msgStateId", getMsgStateId()) .toString(); } }
CKEDITOR.dialog.add( 'mathjaxDialog', function( editor ) { return { title : 'Math Input Dialog', minWidth : 400, minHeight : 200, contents: [ { id: 'input-tab', label: 'Eingabe', elements:[ { //input element for the width type: 'textarea', id: 'mathInput', label: 'Eingabefenster f&uuml;r LaTeX-Quelltext', setup: function( element ) { this.setValue( element.getText() ) }, commit: function( element ) { element.setText( this.getValue() ) } }, { type: 'html', html: '<label>Vorschau</label><div id="math-live-preview"></div>', setup: function (element) { var textarea = editor.document.getElementsByTag("textarea") editor.document.getById("math-live-preview").setText("") // clear preview // register live-preview handler if (textarea) { var t = textarea.$[0] // initial preview-build up var preview = editor.document.getById("math-live-preview") preview.setText(t.value) MathJax.Hub.Queue(["Typeset", MathJax.Hub, "math-live-preview"]) // render preview after every keychange t.onkeyup = function(e) { console.log("user is typing tex: ") preview.setText(t.value) MathJax.Hub.Queue(["Typeset", MathJax.Hub, "math-live-preview"]) } } } } ] }, { id: 'help-tab', label: 'Hilfe (LaTeX-Spickzettel)', elements:[ { type: 'html', html: '<b>LaTeX Spickzettel</b></br><p>What you type.. | What you get..</p>' } ] } ], onLoad: function() { console.log("onLoad..") // initial pop-up this.setupContent(editor.document.createText("$$ $$")) }, onShow: function() { var selection = editor.getSelection() var element = selection.getStartElement() var latexSource = undefined // this is what we need to edit this math-formula // find our ascendant math-output/div container if ( element ) { var mathjaxDiv = element.getAscendant('div') // here we have the output container generated by mathjax at hand if ( mathjaxDiv ) { // truncate ID from DOM Element works with (MathJax 2.0) var mathjaxId = mathjaxDiv.$.firstChild.id.replace('-Frame', '') element = mathjaxDiv.getAscendant('div') // now we have our output container at hand console.log("find mathjax-element with id " + mathjaxId) var math = getInputSourceById(MathJax.Hub.getAllJax("MathDiv"), mathjaxId) if ( math ) { latexSource = math.originalText } else { console.log("Not found.. ") // ### prevent dialog from opening up } } } // edit or insert math-formula // console.log(element) if ( !element || element.getName() != 'div') { // console.log("Show... insert") this.insertMode = true } else { // console.log("Show... edit") if (latexSource) { // override verbose html generated and inserted by mathjax-renderer // replace it with our source within two dollar signs element.setHtml("$$ "+ latexSource + " $$") var preview = editor.document.getById("math-live-preview") preview.setText(element.getHtml()) this.insertMode = false } else { // Oops, no latex-source.. 404 } } this.element = element if ( !this.insertMode ) { this.setupContent( this.element ) } else { this.setupContent(editor.document.createText("$$ $$")) } function getInputSourceById(elements, id) { for (obj in elements) { var element = elements[obj] if (element.inputID === id) return element } return undefined } }, onOk: function () { console.log("Ok...") var dialog = this, mathjaxInput = dialog.element if (dialog.insertMode) { var math = dialog.getValueOf( 'input-tab', 'mathInput' ) var mathObjectId = MathJax.Hub.getAllJax("MathDiv").length // this element is our mathjax-source container var content = editor.document.createElement('div') content.setAttribute('class', 'math-output') content.setAttribute('id', 'formula-'+ mathObjectId) // this element gets replaced by the mathjax-renderer var preview = editor.document.createElement('span') preview.setAttribute('class', 'math-preview') preview.setText(math) content.append(preview) editor.insertElement( content ) } else { dialog.commitContent( mathjaxInput ) } MathJax.Hub.Typeset() }, onHide: function() { console.log("just hiding the dialog, typesetting math in any case..") MathJax.Hub.Typeset() }, onCancel: function() { console.log("just cancelled the dialog, typesetting math in any case..") MathJax.Hub.Typeset() } } });
<!DOCTYPE html> <html lang="en"> {% load static %} {% load widget_tweaks %} <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Login</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static 'assets/img/favicon.png' %}" rel="icon"> <link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.gstatic.com" rel="preconnect"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/boxicons/css/boxicons.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/quill/quill.snow.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/quill/quill.bubble.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/remixicon/remixicon.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/simple-datatables/style.css' %}" rel="stylesheet"> <!-- Template Main CSS File --> <link href="{% static 'assets/css/main.css' %}" rel="stylesheet"> * Template Name: NiceAdmin * Updated: Sep 18 2023 with Bootstrap v5.3.2 * Template URL: https://bootstrapmade.com/nice-admin-bootstrap-admin-html-template/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ <style> .alert-container { position: fixed; bottom: 40px; left: 50%; transform: translateX(-50%); z-index: 1000; width: 80%; max-width: 400px; } body { margin: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; height: 100vh; background: linear-gradient(135deg, #7cbeff1c, #ffffff); animation: water 4s infinite alternate; } @keyframes water { 0% { background-position: 0% 0%; } 100% { background-position: 100% 100%; } } .curve { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #ffffff; clip-path: ellipse(50% 30% at 50% 0); z-index: -1; } .reflections { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(45deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0)); animation: reflections 4s infinite alternate; } @keyframes reflections { 0% { background-position: 0% 0%; } 100% { background-position: 100% 100%; } } </style> </head> <body> <div class="curve"></div> <div class="reflections"></div> <main> <div class="container"> <section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-5 col-md-8 d-flex flex-column align-items-center justify-content-center"> <div class="card mb-5 border shadow-lg"> <div class="card-title"> <div class="d-flex justify-content-center py-4 px-5"> <a href="index.html" class="logo d-flex align-items-center w-auto"> <img src="{% static 'assets/img/logounl.png' %}" alt="" height="110" width="350"> </a> </div><!-- End Logo --> </div> <div class="card-body"> <div> <h5 class="card-title text-center pb-0 fs-4">Iniciar Sesión</h5> </div> {% if messages %} <div id="alert-container" class="alert-container" style="display: none;"> <div class="alert alert-danger" role="alert"> {% for message in messages %} {{ message }} {% endfor %} </div> </div> <script> // Mostrar la alerta flotante cuando hay mensajes window.onload = function() { mostrarAlerta(); }; </script> {% endif %} <form action="" method="POST" class="row g-3 needs-validation" novalidate> {% csrf_token %} <div class="form-group mb-2"> <label for="username">Usuario</label> <input type="text" class="form-control" id="username" name="username" required> <div class="invalid-feedback"> Por favor ingrese su usuario. </div> </div> <div class="form-group mb-2"> <label for="password">Contraseña</label> <input type="password" class="form-control" id="password" name="password" required> <div class="form-check d-flex justify-content-between align-items-center mt-2"> <label class="form-check-label text-muted fs-6 mb-0" for="show-password"><input class="form-check-input" type="checkbox" id="show-password" onclick="togglePassword()">Mostrar contraseña</label> </div> <div class="invalid-feedback"> Por favor ingrese su contraseña. </div> </div> <button class="btn btn-primary" type="submit">Ingresar</button> <div class="text-center"> <a href="{% url 'password_reset' %}">¿Olvidaste tu contraseña?</a> <p>No tienes cuenta? <a href="{% url 'crear_usuario' %}">Regístrate</a></p> </div> </form> </div> </div> </div> </div> </div> </section> </div> </main><!-- End #main --> <!-- Vendor JS Files --> <script src="{% static 'assets/vendor/apexcharts/apexcharts.min.js' %}"></script> <script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'assets/vendor/chart.js/chart.umd.js' %}"></script> <script src="{% static 'assets/vendor/echarts/echarts.min.js' %}"></script> <script src="{% static 'assets/vendor/quill/quill.min.js' %}"></script> <script src="{% static 'assets/vendor/simple-datatables/simple-datatables.js' %}"></script> <script src="{% static 'assets/vendor/tinymce/tinymce.min.js' %}"></script> <script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script> <!-- Template Main JS File --> <script src="{% static 'assets/js/main.js' %}"></script> <script> // Función para mostrar la alerta flotante function mostrarAlerta() { var alertContainer = document.getElementById('alert-container'); alertContainer.style.display = 'block'; setTimeout(function() { alertContainer.style.display = 'none'; }, 5000); } // Función para mostrar/ocultar la contraseña function togglePassword() { var passwordField = document.getElementById('password'); var showPasswordCheckbox = document.getElementById('show-password'); if (showPasswordCheckbox.checked) { passwordField.type = 'text'; } else { passwordField.type = 'password'; } } </script> </body> </html>
def dfs(): global cnt while stack: i, j, origin_d = stack.pop() if arr[i][j] == 0: # 현재 칸이 아직 청소되지 않은 경우, 현재 칸을 청소한다. arr[i][j] = -1 # -1은 청소 완료의 의미 cnt += 1 # 카운트 # 인접 칸 탐색 is_blank = False # 빈칸이 있는지 확인할 변수 for offset_d in range(1,5): # 반시계 방향으로 90도 회전 d = (origin_d - offset_d) % 4 ni = i + di[d] nj = j + dj[d] if arr[ni][nj] == 0: stack.append([ni, nj, d]) is_blank = True break # 청소되지 않은 빈 칸이 있는 경우, 앞으로 한 칸 전진 -> break # 현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 없는 경우 if not is_blank: # 바라보는 방향을 유지한 채로 한 칸 후진할 수 있다면 한 칸 후진 ni = i - di[origin_d] # 바라보는 방향의 역방향 = 값을 빼주기 nj = j - dj[origin_d] if arr[ni][nj] == 1: # 바라보는 방향의 뒤쪽 칸이 벽이라 후진할 수 없다면 작동을 멈춘다. return else: stack.append([ni,nj,origin_d]) import sys input = sys.stdin.readline n, m = map(int, input().split()) i, j, d = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] # 0은 청소되지 않은 빈 칸 # 1은 벽 # 0-북쪽 1-동쪽 2-남쪽 3-서쪽 di = [-1,0,1,0] dj = [0,1,0,-1] stack = [] stack.append([i, j, d]) arr[i][j] = -1 # 현재 칸 청소 cnt = 1 dfs() print(cnt)
//! Creation of archives are defined here use std::ops::Sub; use std::time::Instant; use borgbackup::asynchronous::CreateProgress; use borgbackup::common::{CommonOptions, CompressionMode, CreateOptions}; use borgbackup::output::create::Create; use byte_unit::Byte; use common::{CreateStats, ErrorReport, State}; use log::{error, info}; use tokio::sync::mpsc; use crate::api::Api; use crate::config::Config; async fn start_create( options: &CreateOptions, common_options: &CommonOptions, ) -> Result<Create, ErrorReport> { borgbackup::asynchronous::create(options, common_options) .await .map_err(|err| ErrorReport { state: State::Create, custom: Some(err.to_string()), stdout: None, stderr: None, }) } async fn start_create_progress( options: &CreateOptions, common_options: &CommonOptions, ) -> Result<Create, ErrorReport> { let (tx, mut rx) = mpsc::channel(1); tokio::spawn(async move { while let Some(CreateProgress::Progress { original_size, compressed_size, deduplicated_size, path, .. }) = rx.recv().await { info!( "O: {o}, C: {c}, D: {d}, Path: {path}", o = Byte::from(original_size as u128).get_appropriate_unit(false), c = Byte::from(compressed_size as u128).get_appropriate_unit(false), d = Byte::from(deduplicated_size as u128).get_appropriate_unit(false), ) } }); borgbackup::asynchronous::create_progress(options, common_options, tx) .await .map_err(|err| ErrorReport { state: State::Create, custom: Some(err.to_string()), stdout: None, stderr: None, }) } /// Create a backup using the settings from [Config]. pub async fn create(config: &Config, progress: bool) -> Result<CreateStats, ErrorReport> { let start = Instant::now(); let common_options = CommonOptions { remote_path: config.borg.remote_path.clone(), rsh: Some("ssh -o 'StrictHostKeyChecking accept-new'".to_string()), ..CommonOptions::default() }; let options = CreateOptions { repository: config.borg.repository.clone(), archive: "{utcnow}".to_string(), passphrase: Some(config.borg.passphrase.clone()), comment: None, compression: Some(CompressionMode::Lz4), paths: vec![], exclude_caches: false, patterns: vec![], pattern_file: Some(config.borg.pattern_file_path.clone()), excludes: vec![], exclude_file: None, numeric_ids: false, sparse: true, read_special: false, no_xattrs: false, no_acls: false, no_flags: false, }; let stats = if progress { start_create_progress(&options, &common_options).await? } else { start_create(&options, &common_options).await? }; let duration = Instant::now().sub(start); Ok(CreateStats { original_size: stats.archive.stats.original_size, compressed_size: stats.archive.stats.compressed_size, deduplicated_size: stats.archive.stats.deduplicated_size, nfiles: stats.archive.stats.nfiles, duration: duration.as_secs(), }) } /// Wrapper for [create]. /// /// This will do the error handling for the create call. pub async fn run_create(api: &Api, config: &Config, progress: bool) -> Result<CreateStats, String> { let stats = match create(config, progress).await { Ok(stats) => stats, Err(err) => { error!("Error while creating archive: {err:#?}"); if let Err(err) = api.send_error(err.clone()).await { error!("Error while sending error to vinculum: {err}"); } return Err(format!("{err:?}")); } }; Ok(stats) }
import { TokenAmount, Pair, Currency, ProtocolName } from '@amaterasu-fi/sdk' import { useMemo } from 'react' import { abi as IUniswapV2PairABI } from '@foxswap/core/build/IUniswapV2Pair.json' import { Interface } from '@ethersproject/abi' import { useActiveWeb3React } from '../hooks' import { useMultipleContractSingleData } from '../state/multicall/hooks' import { wrappedCurrency } from '../utils/wrappedCurrency' import { DEFAULT_PROTOCOL } from '../constants' const PAIR_INTERFACE = new Interface(IUniswapV2PairABI) export enum PairState { LOADING, NOT_EXISTS, EXISTS, INVALID } export function usePairs( currencies: [Currency | undefined, Currency | undefined][], protocol?: ProtocolName ): [PairState, Pair | null][] { const activeProtocol = protocol ?? DEFAULT_PROTOCOL const { chainId } = useActiveWeb3React() const tokens = useMemo(() => { return currencies.map(([currencyA, currencyB]) => [ wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId) ]) }, [chainId, currencies]) const pairAddresses = useMemo( () => tokens.map(([tokenA, tokenB]) => { return tokenA && tokenB && tokenA.chainId === tokenB.chainId && !tokenA.equals(tokenB) ? Pair.getAddress(tokenA, tokenB, activeProtocol) : undefined }), [tokens] ) // console.log('usePairs - pairAddresses', pairAddresses) const results = useMultipleContractSingleData(pairAddresses, PAIR_INTERFACE, 'getReserves') // console.log('usePairs - results', results) return useMemo(() => { return results.map((result, i) => { const { result: reserves, loading } = result const tokenA = tokens[i][0] const tokenB = tokens[i][1] if (loading) return [PairState.LOADING, null] if (!tokenA || !tokenB || tokenA.chainId !== tokenB.chainId || tokenA.equals(tokenB)) return [PairState.INVALID, null] if (!reserves) return [PairState.NOT_EXISTS, null] const { reserve0, reserve1 } = reserves const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA] return [ PairState.EXISTS, new Pair( new TokenAmount(token0, reserve0.toString()), new TokenAmount(token1, reserve1.toString()), activeProtocol ) ] }) }, [results, tokens]) } export function usePair(tokenA?: Currency, tokenB?: Currency, protocol?: ProtocolName): [PairState, Pair | null] { return usePairs([[tokenA, tokenB]], protocol)[0] }
<div class="grid-100 row controls"> <div class="grid-30"> <!-- TODO Add directives to the select elememt in order to populate the list with the categories from the database. You'll also need to add directives to handle when the user selects a new category so that you can refresh the recipes list. --> <select ng-change="updateRecipeList(activeCategory)" ng-model="activeCategory"> <option value="">All Categories</option> <option value="{{category.name}}" ng-repeat="category in categories">{{category.name}}</option> </select> </div> <div class="grid-70"> <div class="flush-right"> <!-- TODO Add a directive to this button in order to handle when the user clicks to add a new recipe. --> <button ng-click="goToAddRecipePage()">+ Add Recipe</button> </div> </div> </div> <div class="clear"></div> <!-- TODO Add a directive to this div element so that it only displays when there are no recipes to display. --> <div class="grid-100 row" ng-show="recipes.length === 0"> <div class="grid-70"> <p>No recipes found!</p> </div> </div> <!-- TODO Add a directive to this div element so that it repeats for each recipe to display. Also, add a directive to this div element so that it only displays when there are recipes to display. --> <div class="grid-100 row addHover" ng-show="recipes.length > 0 && recipe.category === activeCategory || activeCategory === ''" ng-repeat="recipe in recipes"> <!-- TODO Replace this anchor element's href attribute with a directive so that you can route the user to the Recipe Detail screen when they click on a row. --> <a href="/#!/edit/{{recipe._id}}"> <div class="grid-70"> <!-- TODO Add binding expressions here in order to display information about the recipe. --> <h2>{{recipe.name}}</h2> <!-- <p><strong>Description:</strong> <i>{{recipe.description}}</i></p> <p><strong>Preparation Time:</strong> <i>{{recipe.prepTime + ' min'}}</i></p> <p><strong>Cook Time:</strong> <i>{{recipe.cookTime + ' min'}}</i></p> --> </div> </a> <div class="hoverBlock"> <div class="grid-30"> <div class="flush-right"> <p> <!-- TODO Replace this anchor element's href attribute with a directive so that you can route the user to the Recipe Detail screen when they click on the 'Edit' link. --> <a href="/#!/edit/{{recipe._id}}"> <img src="images/edit.svg" height="12px"> Edit </a> <!-- TODO Add a directive to this anchor element so that you can delete the recipe when the user clicks on the 'Delete' link. --> <a confirm-deletion class="no-action-link" tabindex="-1" recipe-index="{{$index}}" recipes="recipes"> <img src="images/delete.svg" height="12px"> Delete </a> </p> </div> </div> </div> </div>
Task: Напишите программу, которая будет преобразовывать переводы строк из формата Windows в формат Unix. Данные в формате Windows подаются программе в System.in, преобразованные данные должны выводиться в System.out. На этот раз вам надо написать программу полностью, т.е. объявить класс (с именем Main — таково ограничение проверяющей системы), метод main, прописать все import'ы. Требуется заменить все вхождения пары символов '\r' и '\n' на один символ '\n'. Если на входе встречается одиночный символ '\r', за которым не следует '\n', то символ '\r' выводится без изменения. Кодировка входных данных такова, что символ '\n' представляется байтом 10, а символ '\r' — байтом 13. Поэтому программа может осуществлять фильтрацию на уровне двоичных данных, не преобразуя байты в символы. Из-за буферизации данных в System.out в конце вашей программы надо явно вызвать System.out.flush(). Иначе часть выведенных вами данных не будет видна проверяющей системе. import java.io.*; public class Main { public static void main(String[] args) throws Exception { //InputStream from byte[] array InputStream bis = new ByteArrayInputStream(new byte[] {65, 13, 10, 10, 13}); readByByte(System.in, System.out); // System.out.print("\n\n\n"); } public static void readByByte(InputStream in, OutputStream out)throws IOException{ int next = in.read(); int prev; while (next != -1){ prev = next; next = in.read(); if (!(prev == 13 && next == 10)){ out.write(prev); } } System.out.flush(); } }
# Electrónica IV - TP - Arquitectura de Computadora Este trabajo práctico debe realizarse en modalidad *individual*. *Plazo*: **1 Semana**. ## 1. Objetivos Al completar este trabajo habras estudiado y elaborado tus propias conclusiones sobre las siguientes cuestiones. 1. ¿Qué es una computadora? 2. ¿Qué es la arquitectura de computadora? 3. ¿Cómo se compone una arquitectura de computadora? 4. ¿De qué manera se puede clasificar una arquitectura de computadora? 5. ¿Qué es la arquitectura ARMv7M? ## 2. Metodología de trabajo Realizarás un relevamiento de la literatura en materia de arquitectura de computadoras y escribiras un informe con tus resultados, trabajando sobre la plantilla provista `informe_arquitectura_de_computadoras.md`. En tu investigación puedes consultar libros en la biblioteca y en eLibro, estándares, artículos científicos, sitios web, videos en línea, material de cursos de distintas universidades, documentación de fabricantes, publicaciones de fabricantes, etc. Ten en cuenta la fiabilidad de las fuentes que consultas y usa el sentido común. Para trabajar con mayor libertad puedes ir guardando cada cambio que hagas en tu repositorio git usando mensajes de *commit* descriptivos de lo que hiciste. Luego puedes borrar o modificar drásticamente el manuscrito sin perder tu trabajo anterior (pues siempre puedes verlo en el historial). ## 3. Calificación La calificación de este trabajo se realizará según los siguientes criterios: 1. El informe es un trabajo original, individual y de autoría propia 2. El contenido satisface las consignas indicadas en la plantilla 3. La bibliografía citada es relevante y sustenta las ideas presentadas 4. La evidencia presentada en el desarrollo del trabajo sustenta las conclusiones de manera lógica 5. Se respeta el plazo de entrega pactado *Notas:* - El práctico no se desaprueba sino que es devuelto para corrección hasta su aprovación. Salvo faltas a los criterios 1 y 5 el puntaje de aprobación será 10 para el práctico. - Una falta al criterio 1 implica rehacer el práctico y reduce la calificación del mismo a 4 una vez aprobado. - La entrega tardía resta 2 punto con demora hasta una semana, 3 puntos a las dos semanas y 6 puntos si demora tres semanas. Esto es, si demora 3 semanas en entregar aprobará con 4.