text
stringlengths
184
4.48M
import { Injectable } from "@angular/core"; import { NgToastService } from 'ng-angular-popup'; @Injectable({ providedIn: 'root' }) export class ToastService { constructor( private ngToastService: NgToastService, ) { } showSuccess(message: string) { this.ngToastService.success({ detail: "SUCCESS", summary: message, sticky: false, position: 'topRight', duration: 5000 }); } showError(message: string) { this.ngToastService.error({ detail: "ERROR", summary: message, sticky: false, position: 'topRight', duration: 5000 }); } showInfo(message: string) { this.ngToastService.info({ detail: "INFO", summary: message, sticky: false, position: 'topRight', duration: 5000 }); } showWarn(message: string) { this.ngToastService.warning({ detail: "WARN", summary: message, sticky: false, position: 'topRight', duration: 5000 }); } }
import Countdown from 'react-countdown'; import './styles.css'; const natalGif = 'https://i.pinimg.com/originals/e8/0c/f3/e80cf36f4eb13dca261438a58d39b390.gif'; const Header = () => { // Defina a data de destino para o Natal de 2023 (ano, mês - 1, dia) const targetDate = new Date(2023, 11, 25); const renderer = ({ days, hours, minutes, seconds, completed }) => { if (completed) { // Se o countdown estiver concluído, exiba uma mensagem return <p>Natal chegou!</p>; } else { // Se o countdown ainda está em andamento, exiba os dias, horas, minutos e segundos restantes return ( <div> <p className="weekDay">{`${new Date().toLocaleDateString('pt-BR', { weekday: 'long' })}`}</p> <p className="daysOfChristmas">{`${days}d ${hours}h ${minutes}m ${seconds}s Para o natal!`}</p> </div> ); } }; return ( <header className="header"> <img src={natalGif} alt="GIF Natalino Kawaii" className="background-gif" /> <div className="content"> <Countdown date={targetDate} renderer={renderer} /> </div> </header> ); }; export default Header;
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule } from '@angular/material'; import { routing } from './app.routing'; import { HttpService } from './http/http.service'; import { AuthService } from './auth/auth.service'; import { AuthGuardService } from './auth/auth-guard.service'; import { UserAuthService } from './auth/user-auth.service'; import { LogService } from './log/log.service'; import { AppComponent } from './app.component'; import { AppLoggedComponent } from './app-logged/app-logged.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { LoginComponent } from './login/login.component'; @NgModule({ imports: [ BrowserModule, HttpModule, FormsModule, MaterialModule.forRoot(), routing, ], declarations: [ AppComponent, AppLoggedComponent, DashboardComponent, PageNotFoundComponent, LoginComponent, ], providers: [ HttpService, AuthService, AuthGuardService, UserAuthService, LogService, ], bootstrap: [AppComponent] }) export class AppModule { }
package PageObjects; import java.time.Duration; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import AbstractComponents.AbstractComponents; public class ProductCatalogue extends AbstractComponents{ WebDriver driver; public ProductCatalogue(WebDriver driver) { super(driver); this.driver=driver; PageFactory.initElements(driver, this); } By toast = By.id("toast-container"); By animator = By.cssSelector(".ng-animating"); public List<WebElement> getProductList() { waitForElementClickByLoc(By.className("card-body")); List<WebElement> items = driver.findElements(By.className("card-body")); return items; } public WebElement getItem(String itemName) { List<WebElement> items = getProductList(); WebElement prod = items.stream().filter(product->product.findElement(By.tagName("h5")).getText().equals(itemName)).findFirst().orElse(null); return prod; } public CartPage addItems(List<String> itemList) throws InterruptedException { for(int i=0;i<itemList.size();i++) { // String ele = itemList.get(i); WebElement prod = getItem(itemList.get(i)); prod.findElement(By.xpath(".//button[2]")).click(); // Thread.sleep(500); waitForElementVisible(toast); waitForElementInvisible(animator); } goTo("cart"); CartPage cp = new CartPage(driver); return cp; } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.node.plugin.cache.hazelcast; import com.hazelcast.config.Config; import com.hazelcast.config.EvictionPolicy; import com.hazelcast.config.MapConfig; import com.hazelcast.core.HazelcastInstance; import io.gravitee.common.service.AbstractService; import io.gravitee.node.api.cache.Cache; import io.gravitee.node.api.cache.CacheConfiguration; import io.gravitee.node.api.cache.CacheManager; import io.gravitee.node.plugin.cache.common.InMemoryCache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * @author Kamiel Ahmadpour (kamiel.ahmadpour at graviteesource.com) * @author GraviteeSource Team */ @Slf4j @RequiredArgsConstructor public class HazelcastCacheManager extends AbstractService<CacheManager> implements CacheManager { private final ConcurrentMap<String, Cache<?, ?>> caches = new ConcurrentHashMap<>(); private final HazelcastInstance hazelcastInstance; @Override protected void doStop() { if (hazelcastInstance != null) { hazelcastInstance.shutdown(); } } @Override public <K, V> Cache<K, V> getOrCreateCache(final String name) { return getOrCreateCache(name, new CacheConfiguration()); } @SuppressWarnings("unchecked") @Override public <K, V> Cache<K, V> getOrCreateCache(final String name, final CacheConfiguration configuration) { return (Cache<K, V>) caches.computeIfAbsent( name, s -> { if (configuration.isDistributed()) { // First, configure the cache using Hazelcast config configureCache(s, configuration); // Then create the cache entity return new HazelcastCache<>(hazelcastInstance.getMap(name), configuration.getTimeToLiveInMs()); } else { return new InMemoryCache<>(name, configuration); } } ); } @Override public void destroy(final String cacheName) { Cache<?, ?> cache = caches.remove(cacheName); if (cache != null) { cache.clear(); } } private void configureCache(String name, CacheConfiguration configuration) { Config config = hazelcastInstance.getConfig(); if (!config.getMapConfigs().containsKey(name)) { MapConfig mapConfig = new MapConfig(name); if (configuration.getMaxSize() > 0) { mapConfig.getEvictionConfig().setSize((int) configuration.getMaxSize()); } if (mapConfig.getEvictionConfig().getEvictionPolicy().equals(EvictionPolicy.NONE)) { // Set "Least Recently Used" eviction policy if not have eviction configured mapConfig.getEvictionConfig().setEvictionPolicy(EvictionPolicy.LRU); } if (configuration.getTimeToIdleInMs() > 0) { mapConfig.setMaxIdleSeconds((int) TimeUnit.SECONDS.convert(configuration.getTimeToIdleInMs(), TimeUnit.MILLISECONDS)); } if (configuration.getTimeToLiveInMs() > 0) { mapConfig.setTimeToLiveSeconds((int) TimeUnit.SECONDS.convert(configuration.getTimeToLiveInMs(), TimeUnit.MILLISECONDS)); } config.addMapConfig(mapConfig); } } }
""" Language Models are Multilingual Chain-of-Thought Reasoners https://arxiv.org/abs/2210.03057 Multilingual Grade School Math Benchmark (MGSM) is a benchmark of grade-school math problems, proposed in the paper [Language models are multilingual chain-of-thought reasoners](http://arxiv.org/abs/2210.03057). The same 250 problems from [GSM8K](https://arxiv.org/abs/2110.14168) are each translated via human annotators in 10 languages. The 10 languages are: - Spanish - French - German - Russian - Chinese - Japanese - Thai - Swahili - Bengali - Telugu GSM8K (Grade School Math 8K) is a dataset of 8.5K high quality linguistically diverse grade school math word problems. The dataset was created to support the task of question answering on basic mathematical problems that require multi-step reasoning. You can find the input and targets for each of the ten languages (and English) as `.tsv` files. We also include few-shot exemplars that are also manually translated from each language in `exemplars.py`. Homepage: https://github.com/google-research/url-nlp/tree/main/mgsm """ import re from lm_eval.base import Task, rf from lm_eval.metrics import mean import datasets from lm_eval.utils import InstructionTemplates _CITATION = """ @misc{cobbe2021training, title={Training Verifiers to Solve Math Word Problems}, author={Karl Cobbe and Vineet Kosaraju and Mohammad Bavarian and Jacob Hilton and Reiichiro Nakano and Christopher Hesse and John Schulman}, year={2021}, eprint={2110.14168}, archivePrefix={arXiv}, primaryClass={cs.LG} } @misc{shi2022language, title={Language Models are Multilingual Chain-of-Thought Reasoners}, author={Freda Shi and Mirac Suzgun and Markus Freitag and Xuezhi Wang and Suraj Srivats and Soroush Vosoughi and Hyung Won Chung and Yi Tay and Sebastian Ruder and Denny Zhou and Dipanjan Das and Jason Wei}, year={2022}, eprint={2210.03057}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ ANS_RE = re.compile(r"(\-?\d+)") INVALID_ANS = "[invalid]" class MGSM(Task): VERSION = 0 DATASET_PATH = "juletxara/mgsm" DATASET_NAME = None QUESTION = "Question:" ANSWER = "Step-by-Step Answer:" ORCA_SYSTEM = ( "You are an AI assistant. User will you give you a task. " "Your goal is to complete the task as faithfully as you can. " "While performing the task think step-by-step and justify your steps." ) def download(self, data_dir=None, cache_dir=None, download_mode=None): self.dataset = datasets.load_dataset( self.DATASET_PATH, self.DATASET_NAME, data_dir=data_dir, cache_dir=cache_dir, download_mode=download_mode, ) if self.DATASET_NAME == "en": return self.en_dataset = datasets.load_dataset( self.DATASET_PATH, "en", data_dir=data_dir, cache_dir=cache_dir, download_mode=download_mode, ) self.dataset['train'] = self.dataset['train'].remove_columns('answer') self.dataset['train'] = self.dataset['train'].add_column( 'answer', self.en_dataset['train']['answer']) def has_training_docs(self): return True def has_validation_docs(self): return False def has_test_docs(self): return True def training_docs(self): return self.dataset["train"] def validation_docs(self): raise NotImplementedError def test_docs(self): return self.dataset["test"] def doc_to_text(self, doc, instruction_template=None): if doc["answer"] is not None: text = doc["question"] else: text = self.QUESTION + " " + doc["question"] if not instruction_template: text = text + "\n" + self.ANSWER if instruction_template: template = InstructionTemplates.get_template(instruction_template) if instruction_template == "orca": text = template.format( system_message=self.ORCA_SYSTEM, user_message=text) elif instruction_template == 'metamath': text = template.format( user_message=text) elif instruction_template == 'mathoctopus': text = template.format( input_lang=self.LANG_NAME, output_lang=self.LANG_NAME, user_message=text) return text def doc_to_target(self, doc, instruction_template=None): if doc["answer"] is not None: return " " + doc["answer"][len(self.ANSWER) + 1:] + '[END]' else: return " " + str(doc["answer_number"]) + '[END]' def construct_requests(self, doc, ctx, instruction_template=None): """Uses RequestFactory to construct Requests and returns an iterable of Requests which will be sent to the LM. :param doc: The document as returned from training_docs, validation_docs, or test_docs. :param ctx: str The context string, generated by fewshot_context. This includes the natural language description, as well as the few shot examples, and the question part of the document for `doc`. """ if instruction_template: completion = rf.greedy_until( ctx, {"until": [self.QUESTION, '[END]', '</s>', '<|im_end|>']}) else: completion = rf.greedy_until( ctx, {"until": [self.QUESTION, '[END]']}) return completion def _extract_answer(self, completion): # code copied from MathOctopus, the original regex in lm_eval is wrong completion = re.sub(r"(\d),(\d)", "\g<1>\g<2>", completion) # 123,456 res = re.findall(r"(\d+(\.\d+)?)", completion) # 123456.789 if len(res) > 0: num_str = res[-1][0] return float(num_str) else: return 0.0 def _is_correct(self, completion, answer): gold = answer assert gold != INVALID_ANS, "No ground truth answer found in the document." return self._extract_answer(completion) == float(gold) def process_results(self, doc, results): """Take a single document and the LM results and evaluates, returning a dict where keys are the names of submetrics and values are the values of the metric for that one document :param doc: The document as returned from training_docs, validation_docs, or test_docs. :param results: The results of the requests created in construct_requests. """ completion = results[0] answer = doc["answer_number"] return {"acc": self._is_correct(completion, answer)} def aggregation(self): """ :returns: {str: [float] -> float} A dictionary where keys are the names of submetrics and values are functions that aggregate a list of metrics """ return {"acc": mean} def higher_is_better(self): """ :returns: {str: bool} A dictionary where keys are the names of submetrics and values are whether a higher value of the submetric is better """ return {"acc": True} class MGSM_English(MGSM): DATASET_NAME = "en" LANG_NAME = "English" QUESTION = "Question:" class MGSM_Spanish(MGSM): DATASET_NAME = "es" LANG_NAME = "Spanish" QUESTION = "Pregunta:" class MGSM_French(MGSM): DATASET_NAME = "fr" LANG_NAME = "French" QUESTION = "Question :" class MGSM_German(MGSM): DATASET_NAME = "de" LANG_NAME = "German" QUESTION = "Frage:" class MGSM_Russian(MGSM): DATASET_NAME = "ru" LANG_NAME = "Russian" QUESTION = "\u0417\u0430\u0434\u0430\u0447\u0430:" class MGSM_Chinese(MGSM): DATASET_NAME = "zh" LANG_NAME = "Chinese" QUESTION = "\u95ee\u9898:" class MGSM_Japanese(MGSM): DATASET_NAME = "ja" LANG_NAME = "Japanese" QUESTION = "\u554f\u984c:" class MGSM_Thai(MGSM): DATASET_NAME = "th" LANG_NAME = "Thai" QUESTION = "\u0e42\u0e08\u0e17\u0e22\u0e4c:" class MGSM_Swahili(MGSM): DATASET_NAME = "sw" LANG_NAME = "Swahili" QUESTION = "Swali:" class MGSM_Bengali(MGSM): DATASET_NAME = "bn" LANG_NAME = "Bengali" QUESTION = "\u09aa\u09cd\u09b0\u09b6\u09cd\u09a8:" class MGSM_Telugu(MGSM): DATASET_NAME = "te" LANG_NAME = "Telugu" QUESTION = "\u0c2a\u0c4d\u0c30\u0c36\u0c4d\u0c28:" LANGS = ["en", "es", "fr", "de", "ru", "zh", "ja", "th", "sw", "bn", "te"] LANG_CLASSES = [ MGSM_English, MGSM_Spanish, MGSM_French, MGSM_German, MGSM_Russian, MGSM_Chinese, MGSM_Japanese, MGSM_Thai, MGSM_Swahili, MGSM_Bengali, MGSM_Telugu, ] def construct_tasks(): tasks = {} for lang, lang_class in zip(LANGS, LANG_CLASSES): tasks[f"mgsm_{lang}"] = lang_class return tasks
package web import ( "fmt" "github.com/gorilla/websocket" "net" "sync" "time" ) type Client struct { mu sync.RWMutex hub *hub conn *websocket.Conn Send chan []byte ID uint8 Metadata struct { RemoteAddr string UserAgent string Username string } avgLatency uint16 connectedAt time.Time player chan []byte } func (c *Client) ReadPump() { // deferred function to handle unregistering client // and closing connection defer func() { c.hub.unregister <- c c.conn.Close() c.avgLatency = 0 // c.mu.Unlock() }() // read messages from client read: for { _, message, err := c.conn.ReadMessage() if err != nil { return // connection closed } switch message[0] { case 10: // system related messages c.hub.mu.Lock() switch message[1] { case Compression: c.hub.compression = message[2] == 1 case CompressionLevel: c.hub.compressionLevel = int(message[2]) case FramePatching: c.hub.framePatching = message[2] == 1 case FrameSkipping: c.hub.frameSkipping = message[2] == 1 case FrameCaching: // TODO implement case RegisterUsername: c.Metadata.Username = string(message[2:]) message = []byte{} message = append(message, c.Metadata.RemoteAddr...) message = append(message, 0) message = append(message, c.Metadata.UserAgent...) message = append(message, 0) message = append(message, c.Metadata.Username...) message = append(message, 0) message = append(message, c.ID) message = append(message, byte('\n')) c.Send <- append([]byte{ClientInfo, RegisterUsername, 0xFF}, message...) c.hub.sendAllButClient(c, append([]byte{ClientInfo, RegisterUsername}, message...)) c.hub.mu.Unlock() continue read // special case of register username handled case Player2Confirmation: fmt.Println("recieved player 2 confirmation") // has a player 2 already attached to this client if c.hub.player2.c != nil { continue read // skip this message } fmt.Println("upgrading player 2") /* TODO reimplement this if !c.hub.player2.gb.IsRunning() { go c.hub.player2.Start() }*/ c.hub.player2.clientConnect <- c } c.hub.sendAllButClient(c, append([]byte{ClientInfo, message[1]}, message[2:]...)) c.hub.mu.Unlock() continue read case 255: // websocket client request close c.hub.sendAllButClient(c, append([]byte{ClientClosing}, []byte(c.Metadata.RemoteAddr)...)) // TODO send ID instead of IP c.hub.unregister <- c return default: // send through to player if not nil if c.player != nil { c.player <- message } } } } func (c *Client) WritePump() { // deferred function to handle unregistering client // and closing connection defer func() { c.hub.unregister <- c c.conn.WriteMessage(websocket.CloseMessage, []byte{}) c.mu.Unlock() }() for { select { case message, ok := <-c.Send: c.mu.Lock() // connection hub closed the connection if !ok { c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } // try to write message to client if err := c.conn.WriteMessage(websocket.BinaryMessage, message); err != nil { return } // update average latency info, err := tcpInfo(c.conn.UnderlyingConn().(*net.TCPConn)) if err != nil { return } c.avgLatency = ((c.avgLatency * 9) + uint16(info.Rtt/1000)) / 10 c.mu.Unlock() } } }
import React, { createContext, useEffect, useState } from 'react'; import {createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signInWithEmailAndPassword, signInWithPopup, signOut, updateProfile} from 'firebase/auth' import app from '../../firebase/firebase.config'; export const AuthContext = createContext(); const auth = getAuth(app); const AuthProvider = ({children}) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const providerLogin = (provider) => { setLoading(true); return signInWithPopup(auth, provider); } const createUser = (email, password) => { setLoading(true); return createUserWithEmailAndPassword(auth, email, password) } const signIn = (email,password) => { setLoading(true); return signInWithEmailAndPassword(auth, email, password); } const updateUserProfile = (profile) => { return updateProfile(auth.currentUser, profile); } const logOut = () => { setLoading(true); return signOut(auth); } useEffect( () => { const unSubscribe = onAuthStateChanged(auth, (currentUser) => { // console.log('user inside state change', currentUser); setUser(currentUser); setLoading(false); }); return () => { unSubscribe(); } } , []) const authInfo = { user, loading, providerLogin, logOut, createUser, signIn, updateUserProfile }; return ( <AuthContext.Provider value={authInfo}> {children} </AuthContext.Provider> ); }; export default AuthProvider;
import type { Metadata } from "next"; import { Montserrat } from "next/font/google"; import "./globals.css"; import "@fontsource/roboto/300.css"; import "@fontsource/roboto/400.css"; import "@fontsource/roboto/500.css"; import "@fontsource/roboto/700.css"; import Header from "@/components/Header/Header"; import Footer from "@/components/Footer/Footer"; import StoreProvider from "./StoreProvider"; const montserrat = Montserrat({ style: ["normal", "italic"], weight: ["100", "200", "300", "400", "500", "600", "700"], display: "swap", subsets: ["latin"], }); export const metadata: Metadata = { title: "Ecommerce", description: "This is a sample Ecommerce site", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body className={montserrat.className}> <StoreProvider> <Header /> {children} <Footer /> </StoreProvider> </body> </html> ); }
#include <iostream> #include <cmath> using namespace std; #include <cuda.h> #include <cuda_runtime.h> #include <helper_cuda.h> int main() { //Declare a CUDA Device property structure variable cudaDeviceProp prop; //An integer variable to store the number of GPUs int nCountDevices{}; //Query the RT system about the number of GPUs cudaGetDeviceCount(&nCountDevices); cout << "Number of GPUs " << nCountDevices << endl; for (int i = 0; i < nCountDevices; i++) { //Call the get device api and store the information in the structure variable: prop cudaGetDeviceProperties(&prop, i); cout << "Name = " << prop.name << endl; //Compute Capability of GPU cout << "Compute Capability " << prop.major << "." << prop.minor << endl; cout << "Streaming Multiprocessors = " << prop.multiProcessorCount << endl; cout << "Streaming Processors/SM(SP) = " << _ConvertSMVer2Cores(prop.major, prop.minor) << endl; cout << "GPU CLock Rate: " << (prop.clockRate / pow(10.0, 3.0)) << " MHz" << endl; cout << "Global Memory CLock Rate: " << (prop.memoryClockRate / pow(10.0, 3.0)) << " MHz" << endl; cout << "Memory Bus Width = " << prop.memoryBusWidth << " bits" << endl; cout << "Global Memory = " << (prop.totalGlobalMem / (1024 * 1024)) << " MB" << endl; cout << "Maximum # Blocks/SM = " << prop.maxBlocksPerMultiProcessor << endl; cout << "Maximum Threads/SM = " << prop.maxThreadsPerMultiProcessor << endl; cout << "Maximum Threads/Block = " << prop.maxThreadsPerBlock << endl; } return 0; }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_METRICS_METRICS_LOG_MANAGER_H_ #define COMPONENTS_METRICS_METRICS_LOG_MANAGER_H_ #include <stddef.h> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "components/metrics/metrics_log.h" #include "components/metrics/persisted_logs.h" namespace metrics { // Manages all the log objects used by a MetricsService implementation. Keeps // track of both an in progress log and a log that is staged for uploading as // text, as well as saving logs to, and loading logs from, persistent storage. class MetricsLogManager { public: // The metrics log manager will persist it's unsent logs by storing them in // |local_state|, and will not persist ongoing logs over // |max_ongoing_log_size|. MetricsLogManager(PrefService* local_state, size_t max_ongoing_log_size); ~MetricsLogManager(); // Makes |log| the current_log. This should only be called if there is not a // current log. void BeginLoggingWithLog(std::unique_ptr<MetricsLog> log); // Returns the in-progress log. MetricsLog* current_log() { return current_log_.get(); } // Closes current_log(), compresses it, and stores the compressed log for // later, leaving current_log() NULL. void FinishCurrentLog(); // Returns true if there are any logs waiting to be uploaded. bool has_unsent_logs() const { return initial_log_queue_.size() || ongoing_log_queue_.size(); } // Populates staged_log_text() with the next stored log to send. // Should only be called if has_unsent_logs() is true. void StageNextLogForUpload(); // Returns true if there is a log that needs to be, or is being, uploaded. bool has_staged_log() const { return initial_log_queue_.has_staged_log() || ongoing_log_queue_.has_staged_log(); } // The text of the staged log, as a serialized protobuf. // Will trigger a DCHECK if there is no staged log. const std::string& staged_log() const { return initial_log_queue_.has_staged_log() ? initial_log_queue_.staged_log() : ongoing_log_queue_.staged_log(); } // The SHA1 hash of the staged log. // Will trigger a DCHECK if there is no staged log. const std::string& staged_log_hash() const { return initial_log_queue_.has_staged_log() ? initial_log_queue_.staged_log_hash() : ongoing_log_queue_.staged_log_hash(); } // Discards the staged log. void DiscardStagedLog(); // Closes and discards |current_log|. void DiscardCurrentLog(); // Sets current_log to NULL, but saves the current log for future use with // ResumePausedLog(). Only one log may be paused at a time. // TODO(stuartmorgan): Pause/resume support is really a workaround for a // design issue in initial log writing; that should be fixed, and pause/resume // removed. void PauseCurrentLog(); // Restores the previously paused log (if any) to current_log(). // This should only be called if there is not a current log. void ResumePausedLog(); // Saves any unsent logs to persistent storage. void PersistUnsentLogs(); // Loads any unsent logs from persistent storage. void LoadPersistedUnsentLogs(); // Saves |log_data| as the given type. Public to allow to push log created by // external components. void StoreLog(const std::string& log_data, MetricsLog::LogType log_type); private: // Tracks whether unsent logs (if any) have been loaded from the serializer. bool unsent_logs_loaded_; // The log that we are still appending to. std::unique_ptr<MetricsLog> current_log_; // A paused, previously-current log. std::unique_ptr<MetricsLog> paused_log_; // Logs that have not yet been sent. PersistedLogs initial_log_queue_; PersistedLogs ongoing_log_queue_; DISALLOW_COPY_AND_ASSIGN(MetricsLogManager); }; } // namespace metrics #endif // COMPONENTS_METRICS_METRICS_LOG_MANAGER_H_
<template> <section class="contactus"> <div class="contactus__wrapper"> <div :class="{ roow: true, inview: screenSize > 992 }"> <div :class="{ 'cool-3': true, inview: screenSize > 768 }"> <div class="contactus__wrapper__list"> <ul> <contact-cart v-for="(item, i) in items" :key="i" :isActive="activeId == i" :color="item.color" :topic="item.topic" :text="item.text" :icon="item.icon" :class="{ inview: screenSize < 768 }" @click="onCartClicked(i)" ></contact-cart> </ul> </div> </div> <div class="cool-9"> <div :class="{ contactus__wrapper__item: true, inview: screenSize < 992 }"> <contact-text :contactText="items[activeId].contactText" :contactTopic="items[activeId].contactTopic" ></contact-text> <contact-form :name="name" @inputChanged="onInputChanged"></contact-form> </div> </div> </div> </div> </section> </template> <script> import contactCart from "./contact-cart.vue"; import ContactForm from "./contact-form.vue"; import ContactText from "./contact-text.vue"; export default { components: { contactCart, ContactText, ContactForm }, name: "innerContact", mounted() { window.addEventListener("resize", this.onResize); this.onResize(); }, methods: { onInputChanged: function (data) { if (data.name == "name") { this.name = data.text; } else if (data.name == "email") { this.email = data.text; } else if (data.name == "ticketText") { this.ticketText = data.text; } }, onResize() { this.screenSize = window.innerWidth; console.log(this.screenSize); }, onCartClicked(id) { this.activeId = id; }, }, data() { return { activeId: 0, name: "", email: "", ticketText: "", screenSize: 993, items: [ { contactTopic: "آدرس", contactText: "متن مخصوص آدرس", color: "#00ffd1", iconColor: "#131129", textColor: "", icon: "dn-location", topic: "آدرس", text: "تهران-خ فاطمه غربی – پلاک ۴۵۲", }, { contactTopic: "ایمیل", contactText: "متن مخصوص ایمیل", color: "#ffcd6b", icon: "dn-email", topic: "ایمیل", text: "mpadyabm@gmail.com", }, { contactTopic: "تلفن", contactText: "متن مخصوص تلفن", color: "#d5a0ff", icon: "dn-call", topic: "تلفن", text: "۰۹۱۲۰۷۴۴۰۹۷ – ۰۹۱۹۴۱۰۹۵۶۶", }, { contactTopic: "ساعت کاری", contactText: "لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده" + " از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و" + "سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای" + "متنوع با هدف بهبود", color: "#fd6b63", icon: "dn-timer", topic: "ساعت کاری", text: "از 8 صبح تا 9 شب", }, ], }; }, }; </script>
import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { emitter } from '../../utils/emitter'; class ModalUser extends Component { constructor(prop) { super(prop); this.state = { email: '', password: '', firstName: '', lastName: '', address: '' } this.listenToEmiiter(); } listenToEmiiter() { emitter.on('EVENT_CLEAR_MODAL_DATA', () => { this.setState({ email: '', password: '', firstName: '', lastName: '', address: '' }) }) } //bus event componentDidMount() { // console.log('mouting modal') } toggle = () => { this.props.toggelFromParent(); } handleOnChangeInput = (event, id) => { //bad code // this.state[id] = event.target.value; // this.setState({ // ...this.state // }, () => { // console.log('check bad state', this.state) // }) //good code let copyState = { ...this.state }; copyState[id] = event.target.value; this.setState({ ...copyState }) } checkValidateInput = () => { let isValid = true; let arrInput = ['email', 'password', 'firstName', 'lastName', 'address']; for (let i = 0; i < arrInput.length; i++) { console.log('check inside loop:', this.state[arrInput[i]], arrInput[i]) if (!this.state[arrInput[i]]) { isValid = false; alert('Missing parameters: ' + arrInput[i]); break; } } return isValid; } handleAddNewuser = () => { let isValid = this.checkValidateInput(); if (isValid === true) { this.props.createNewUser(this.state); } } render() { return ( <Modal isOpen={this.props.isOpen} toggle={() => { this.toggle() }} className={'modal-user-container'} size="lg" > <ModalHeader toggle={() => { this.toggle() }}>Create a new user</ModalHeader> <ModalBody> <div className='modal-user-body'> <div className='col-6 input-container'> <label>Email</label> <input type='text' onChange={(event) => { this.handleOnChangeInput(event, "email") }} value={this.state.email} ></input> </div> <div className='col-6 input-container'> <label>Password</label> <input type='password' onChange={(event) => { this.handleOnChangeInput(event, "password") }} value={this.state.password} ></input> </div> <div className='col-6 input-container'> <label>First Name</label> <input type='text' onChange={(event) => { this.handleOnChangeInput(event, "firstName") }} value={this.state.firstName} ></input> </div> <div className='col-6 input-container'> <label>Last Name</label> <input type='text' onChange={(event) => { this.handleOnChangeInput(event, "lastName") }} value={this.state.lastName} ></input> </div> <div className='col-6 input-container max-width-input'> <label>Address</label> <input type='text' onChange={(event) => { this.handleOnChangeInput(event, "address") }} value={this.state.address} ></input> </div> </div> </ModalBody> <ModalFooter> <Button color="primary" className='px-3' onClick={() => { this.handleAddNewuser() }} >Add New</Button>{' '} <Button color="secondary" className='px-3' onClick={() => { this.toggle() }}>Cancel</Button> </ModalFooter> </Modal> ) } } const mapStateToProps = state => { return { }; }; const mapDispatchToProps = dispatch => { return { }; }; export default connect(mapStateToProps, mapDispatchToProps)(ModalUser);
import { Uri, UriResolutionContext } from "@polywrap/core-js"; import { expectHistory } from "../helpers/expectHistory"; import { PolywrapCoreClient } from "@polywrap/core-client-js"; import { UriResolverAggregator } from "../../aggregator"; import { ResultOk } from "@polywrap/result"; jest.setTimeout(20000); describe("UriResolverAggregator", () => { const client = new PolywrapCoreClient({ resolver: new UriResolverAggregator( [ { from: Uri.from("test/1"), to: Uri.from("test/2"), }, { from: Uri.from("test/2"), to: Uri.from("test/3"), }, { from: Uri.from("test/3"), to: Uri.from("test/4"), }, ], "TestAggregator" ), }); it("can resolve using first resolver", async () => { const uri = new Uri("test/1"); let resolutionContext = new UriResolutionContext(); let result = await client.tryResolveUri({ uri, resolutionContext }); await expectHistory( resolutionContext.getHistory(), "aggregator-resolver", "can-resolve-using-first-resolver" ); expect(result).toMatchObject( ResultOk({ type: "uri", uri: { uri: "wrap://test/2", }, }) ); }); it("can resolve using last resolver", async () => { const uri = new Uri("test/3"); let resolutionContext = new UriResolutionContext(); let result = await client.tryResolveUri({ uri, resolutionContext }); await expectHistory( resolutionContext.getHistory(), "aggregator-resolver", "can-resolve-using-last-resolver" ); expect(result).toMatchObject( ResultOk({ type: "uri", uri: { uri: "wrap://test/4", }, }) ); }); it("does not resolve a uri when not a match", async () => { const uri = new Uri("test/not-a-match"); let resolutionContext = new UriResolutionContext(); let result = await client.tryResolveUri({ uri, resolutionContext }); await expectHistory( resolutionContext.getHistory(), "aggregator-resolver", "not-a-match" ); expect(result).toMatchObject( ResultOk({ type: "uri", uri: { uri: "wrap://test/not-a-match", }, }) ); }); });
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld' // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' Shader "Unlit/Volume1" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #pragma multi_compile_fog #include "UnityCG.cginc" #define STEPS 64 #define STEP_SIZE 0.1 #define _Center float3(0,0,0) #define _Radius 0.5 struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; float3 worldPosition : TEXCOORD1; }; sampler2D _MainTex; float4 _MainTex_ST; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.worldPosition = mul(unity_ObjectToWorld, v.vertex).xyz; return o; } bool sphereHit (float3 p) { return distance(p,_Center) < _Radius; } bool raymarchHit (float3 position, float3 direction) { for (int i = 0; i < STEPS; i++) { if ( sphereHit(position) ) return true; position += direction * STEP_SIZE; } return false; } fixed4 frag (v2f i) : SV_Target { float3 worldPosition = i.worldPosition; float3 viewDirection = normalize(i.worldPosition - _WorldSpaceCameraPos); if(raymarchHit(worldPosition, viewDirection)) return fixed4(1,0,0,1); else return fixed4(1,1,1,1); } ENDCG } } }
// // OnboardingView.swift // Restart // // Created by Ashish Yadav on 06/02/22. // import SwiftUI struct OnboardingView: View { //MARK: - PROPERTY WRAPPER @AppStorage("onboarding") var isOnboaringViewActive = true //Its primary purpose to establish some constraints to the button horizontal moment. @State private var buttonWidth : Double = UIScreen.main.bounds.width - 80 @State private var buttonOffset : CGFloat = 0 //Button has two states, //there is an active state, when user is dragging it //there is an idle state when button is inactive //That's why we intialized the offset size with a zero value and this offset value will constantly be changing during the dragging activity. //---------------- //think about this animation property as some kind of Switcher //A Property to control the Animation @State private var isAnimating : Bool = false //False : Animation start //true : Animation stop //---------------- @State private var imageOffset : CGSize = .zero // OR CGSize(width: 0, height: 0) @State private var indicatorOpacity : Double = 1.0 @State private var textTitle : String = "Share." let hapticFeedback = UINotificationFeedbackGenerator() //MARK: - BODY var body: some View { ZStack { Color("ColorBlue") .ignoresSafeArea(SafeAreaRegions.all, edges: .all) VStack(spacing: 20) { //MARK: - HEADER Spacer() VStack(spacing: 0) { Text(textTitle) .font(Font.system(size: 60)) .fontWeight(.heavy) .foregroundColor(.white) .transition(.opacity) .id(textTitle) Text(""" It's not how much we give but How much love we put into giving. """) .font(.title3) .fontWeight(.light) .foregroundColor(.white) .multilineTextAlignment(.center) .padding(.horizontal, 20) } //: HEADER .opacity(isAnimating ? 1 : 0) .offset(y: isAnimating ? 0 : -40) .animation(.easeOut(duration: 1), value: isAnimating) //MARK: - CENTER ZStack { // Horizontal parallax Effect CircleGroupView(shapeColor: .white, shapeOpacity: 0.2) .offset(x: imageOffset.width * -1) .blur(radius: abs(imageOffset.width / 5)) .animation(.easeOut(duration: 1), value: imageOffset) Image("char1") .resizable() .scaledToFit() .opacity(isAnimating ? 1 : 0) .animation(.easeOut(duration: 0.5), value: isAnimating) .offset(x: imageOffset.width * 1.2, y: 0) .rotationEffect(Angle.degrees(Double(imageOffset.width)/20)) // This will rotate the image .gesture( DragGesture() .onChanged({ gesture in // MARK: This can drag the image to infinity // imageOffset = gesture.translation // MARK: This will limit the image dragging till 150 from left and right both if abs(imageOffset.width) <= 150 { imageOffset = gesture.translation withAnimation(.linear(duration: 0.25)) { indicatorOpacity = 0 textTitle = "Give." } } }) .onEnded({ _ in imageOffset = .zero withAnimation(.linear(duration: 0.25)) { indicatorOpacity = 1.0 textTitle = "Share." } }) ) //: GESTURE .animation(.easeOut(duration: 1), value: imageOffset) } //: CENTER .overlay( Image(systemName: "arrow.left.and.right.circle") .font(.system(size: 44, weight: .ultraLight)) .foregroundColor(.white) .offset(y: 20) .opacity(isAnimating ? 1 : 0) .animation(.easeOut(duration: 1).delay(2), value: isAnimating) .opacity(indicatorOpacity) , alignment: .bottom ) Spacer() //MARK: - FOOTER ZStack { //PARTS OF THE CUSTOM BUTTON // 1. BACKGROUND (STATIC) Capsule() .fill(.white.opacity(0.2)) Capsule() .fill(.white.opacity(0.2)) .padding(8) // 2. CALL-TO-ACTION (STATIC) Text("Get Started") .font(.system(.title3, design: .rounded)) .fontWeight(.bold) .foregroundColor(Color.white) .offset(x: 20) // 3. CAPSULE (DYNAMIC WIDTH) HStack { Capsule() .fill(Color("ColorRed")) .frame(width: buttonOffset+80) Spacer() } // 4. CIRCLE (DRAGGABLE) HStack { ZStack { Circle() .fill(Color("ColorRed")) Circle() .fill(Color.black.opacity(0.15)) .padding(8) Image(systemName: "chevron.right.2") .font(Font.system(size: 24, weight: .bold)) } //: ZSTACK .foregroundColor(.white) .frame(width: 80, height: 80, alignment: .center) .offset(x: buttonOffset) .gesture( DragGesture() .onChanged({ gesture in //We can put any action inside it and these action will be triggered every time the gesture value changes. if gesture.translation.width > 0 && buttonOffset <= buttonWidth - 80 { buttonOffset = gesture.translation.width } }) .onEnded({ _ in withAnimation(.easeOut(duration: 0.4)) { if buttonOffset > buttonWidth/2 { hapticFeedback.notificationOccurred(.success) playSound(sound: "chimeup", type: "mp3") buttonOffset = buttonWidth - 80 //this state variable will check and navigate to the particular screen from contentView isOnboaringViewActive = false } else { hapticFeedback.notificationOccurred(.warning) buttonOffset = 0 } } }) )//: GESTURE Spacer() }//: HSTACK } //: FOOTER .frame(width: buttonWidth, height: 80, alignment: .center) .padding() .opacity(isAnimating ? 1 : 0) .offset(y: isAnimating ? 0 : 40) .animation(.easeOut(duration: 1), value: isAnimating) } //: VSTACK } //: ZSTACK .onAppear { isAnimating = true //this value change will trigger the animation } .preferredColorScheme(.dark) } } struct OnboardingView_Previews: PreviewProvider { static var previews: some View { OnboardingView() } } //Drag Gesture: /* Every drag gesture have two particular state 1. when the drag user activity is happening 2. when the drag user activity has ended We can tell the program what we want to do with the red button by knowing the value Text("Ashish") .transition(.opacity) - This modifier should provide animated transition from transparent to Opaque on insertion and vice verca in removal */
#!/usr/bin/env python # Greedy algorithm for coin change problem import click def greedy_coin(amount): """ Greedy algorithm for coin change problem """ print(f"Your change for {amount} is:") coins = [0.25, 0.10, 0.05, 0.01] coin_lookup = {0.25: "quarter", 0.10: "dime", 0.05: "nickel", 0.01: "penny"} coin_dict = {} for coin in coins: coin_dict[coin] = 0 for coin in coins: while amount >= coin: amount -= coin amount = round( amount, 2 ) # to avoid floating point errors. e.g. 0.01 + 0.01 + 0.01 = 0.030000000000000002 coin_dict[coin] += 1 for coin in coin_dict: if coin_dict[coin] > 0: print(f"{coin_dict[coin]} {coin_lookup[coin]}") return coin_dict @click.command() @click.argument("amount", type=float) def main(amount): """ Return the change for a given amount using the least amount of coins Args:\n amount (float): Amount of change to return Returns:\n dict: Dictionary of coins and their counts Examples:\n $ ./greedy_coin.py 0.67\n Your change for 0.67 is:\n 2 quarter\n 1 dime\n 1 nickel\n 2 penny\n """ greedy_coin(amount) if __name__ == "__main__": # pylint: disable=no-value-for-parameter main()
import React from 'react'; import * as PropTypes from 'prop-types'; import Heading from '../atoms/Heading'; import Image from '../atoms/Image'; import Spacer from '../layouts/Spacer'; import Subtitle from '../atoms/Subtitle'; import Text from '../atoms/Text'; import styles from './PortfolioItemCard.module.css'; import Link from 'next/link'; const PortfolioItemCard: React.FunctionComponent<{ image: string; linkLabel: string; name: string; slug: string; text: string; title: string; }> = ({ linkLabel, image, name, slug, text, title }) => ( <div className={styles.cardContainer}> <Link href={`/portfolio/${slug}/`} className={styles.card}> <div className={styles.imageContainer}> <Image // height={1280} // width={720} alt={name} className={styles.image} layout="fill" src={image} /> </div> <div className={styles.contentContainer}> <Spacer height="8px" /> <Subtitle>{name}</Subtitle> <Spacer height="8px" /> <Heading customClasses={styles.heading} tag="h3"> {title} </Heading> <Text customClasses={styles.text}>{text}</Text> </div> <Spacer height="16px" /> <div className={styles.buttonContainer}> <div className={styles.button}>{linkLabel}</div> </div> </Link> </div> ); PortfolioItemCard.propTypes = { image: PropTypes.string.isRequired, linkLabel: PropTypes.string.isRequired, name: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, text: PropTypes.string.isRequired, title: PropTypes.string.isRequired, }; export default PortfolioItemCard;
import { SVGProps } from 'react'; export function Spinner(props: SVGProps<SVGSVGElement>) { return ( <svg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' viewBox='0 0 24 24' {...props} > <g> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.14' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.29' transform='rotate(30 12 12)' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.43' transform='rotate(60 12 12)' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.57' transform='rotate(90 12 12)' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.71' transform='rotate(120 12 12)' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' opacity='.86' transform='rotate(150 12 12)' ></rect> <rect width='2' height='5' x='11' y='1' fill='currentColor' transform='rotate(180 12 12)' ></rect> <animateTransform attributeName='transform' calcMode='discrete' dur='0.75s' repeatCount='indefinite' type='rotate' values='0 12 12;30 12 12;60 12 12;90 12 12;120 12 12;150 12 12;180 12 12;210 12 12;240 12 12;270 12 12;300 12 12;330 12 12;360 12 12' ></animateTransform> </g> </svg> ); }
import { Component } from "react"; import SomethingWentWrong from "../pages/error-boundary-page/SomethingWentWrong"; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false, errorMessage: "", }; } static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, errorInfo) { this.setState({ errorMessage: errorInfo.componentStack }); } render() { if (this.state.hasError) { return <SomethingWentWrong errorMessage={this.state.errorMessage} />; } return this.props.children; } } export default ErrorBoundary;
******************** CHAPTER: 43 ******************** ## Automatic Numbering With Counters To work with CSS counters we will use the following properties: counter-reset - Creates or resets a counter counter-increment - Increments a counter value content - Inserts generated content counter() or counters() function - Adds the value of a counter to an element Example: <!DOCTYPE html> <html> <head> <style> body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; } </style> </head> <body> <h1>Using CSS Counters</h1> <h2>HTML Tutorial</h2> <h2>CSS Tutorial</h2> <h2>JavaScript Tutorial</h2> <h2>Python Tutorial</h2> <h2>SQL Tutorial</h2> </body> </html> ## Nesting Counters Example: <!DOCTYPE html> <html> <head> <style> body { counter-reset: section; } h1 { counter-reset: subsection; } h1::before { counter-increment: section; content: "Section " counter(section) ". "; } h2::before { counter-increment: subsection; content: counter(section) "." counter(subsection) " "; } </style> </head> <body> <h1>HTML/CSS Tutorials</h1> <h2>HTML</h2> <h2>CSS</h2> <h2>Bootstrap</h2> <h2>W3.CSS</h2> <h1>Scripting Tutorials</h1> <h2>JavaScript</h2> <h2>jQuery</h2> <h2>React</h2> <h1>Programming Tutorials</h1> <h2>Python</h2> <h2>Java</h2> <h2>C++</h2> </body> </html> Example 2: <!DOCTYPE html> <html> <head> <style> ol { counter-reset: section; list-style-type: none; } li::before { counter-increment: section; content: counters(section,".") " "; } </style> </head> <body> <ol> <li>item</li> <li>item <ol> <li>item</li> <li>item</li> <li>item <ol> <li>item</li> <li>item</li> <li>item</li> </ol> </li> <li>item</li> </ol> </li> <li>item</li> <li>item</li> </ol> <ol> <li>item</li> <li>item</li> </ol> </body> </html>
examine Usage: examine [player1 [player2, game_number] This command starts a game in the examine mode where you, as the examiner, can move the pieces for both white and black, take moves back and analyze side variations. You can examine a new game from scratch, a stored (adjourned) game, a finished game from "history" or a game in someone's "journal". STARTING EXAMINE MODE There are four ways to begin an examine session: 1) New Game from Scratch -- "Examine" used alone without any player names begins examine mode for a new game and, in essence, you will be playing yourself. Typing "match your_handle" is also a way to enter examine mode for a new game. 2) Stored Games (adjourned) -- "Examine player1" will examine your stored game against player1 (if one exists). "Examine white_player black_player" will examine the stored game (adjourned) between the two players. Example: "examine dav thedane". 3) Completed Game from History -- "Examine player1 game_number" will examine that game from player1's "history". Example: "examine theviking 45". 4) Game from a Journal -- "Examine player1 game_slot" will examine that game from player1's "journal" (unless the journal is private, namely "jprivate" variable has been set to non-zero). Example: "examine sms B". EXAMINE MODE No matter how you start the examine functions, the game will be played from the starting position, not the last, stored position. While in examine mode, you can move the pieces in order to set up a position and/or analyze side variations. There are three special commands you can use when examining a stored game: forward [#] goes forward # moves (default n=1) backward [#] goes backward # moves (default n=1) revert goes back to the main variation (the last branch) For new games, only "backward" works; the other commands have no effect since there is no main line stored. Therefore, once you go backward, you will need to move the pieces again in order to move forward. Lastly, the command "unexamine" leaves the examine mode and ends your analysis of the game. GROUP EXAMINE Other users can also examine the game you are reviewing. But must you decide who these other examiners are. Here are the steps involved: (1) The other examiner must first "observe" your game. (2) You, as the main examiner, must type "mexamine <user>" in order to give "user" access to the examine mode. As long as there is at least one designated examiner of a game, the analysis can continue even when the first examiner who started the examine session leaves. In order to communicate with another examiner of the game, it is best to use the "kibitz" command. If you use "whisper", the game's observers but not examiners will hear your message. SPECIAL NOTES (1) Players examining games have a # next to their handles in the (short) "who" display, and examined games are listed in both the "games" and "allobservers" displays. (2) "Unexamine" stops your participation in the analysis, and also stops your observer status. Other examiners of the game may continue, however, even if you started the examine session initially. (3) Clock times displayed are unimportant, of course, since time is not a factor when analyzing games. See Also: allobservers backward forward games history kibitz journal match mexamine observe stored unexamine variables whisper who [Last modified: December 17, 1995 -- Friar]
<?php declare(strict_types=1); namespace FSMS\Chronopost\StructType; use InvalidArgumentException; use WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for resultMonoParcelExpeditionValue StructType * @subpackage Structs */ #[\AllowDynamicProperties] class ResultMonoParcelExpeditionValue extends ResultExpeditionValueV3 { /** * The pdfEtiquette * Meta information extracted from the WSDL * - minOccurs: 0 * @var string|null */ protected ?string $pdfEtiquette = null; /** * Constructor method for resultMonoParcelExpeditionValue * @uses ResultMonoParcelExpeditionValue::setPdfEtiquette() * @param string $pdfEtiquette */ public function __construct(?string $pdfEtiquette = null) { $this ->setPdfEtiquette($pdfEtiquette); } /** * Get pdfEtiquette value * @return string|null */ public function getPdfEtiquette(): ?string { return $this->pdfEtiquette; } /** * Set pdfEtiquette value * @param string $pdfEtiquette * @return \FSMS\Chronopost\StructType\ResultMonoParcelExpeditionValue */ public function setPdfEtiquette(?string $pdfEtiquette = null): self { // validation for constraint: string if (!is_null($pdfEtiquette) && !is_string($pdfEtiquette)) { throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($pdfEtiquette, true), gettype($pdfEtiquette)), __LINE__); } $this->pdfEtiquette = $pdfEtiquette; return $this; } }
--- id: bad82fee1322bd9aedf08721 title: Diferenciar entre unidades absolutas e relativas challengeType: 0 videoUrl: 'https://scrimba.com/c/cN66JSL' forumTopicId: 301089 dashedName: understand-absolute-versus-relative-units --- # --description-- Todos os últimos desafios definiram a margem ou preenchimento de um elemento usando pixels (`px`). Pixels são um tipo de unidade de comprimento, que informa ao navegador como dimensionar ou espaçar um item. Além do `px`, o CSS possui outras opções de unidades de comprimento que você pode usar. Os dois principais tipos de unidades de comprimento são: absoluto e relativo. As unidades absolutas estão vinculadas às unidades físicas de comprimento. Por exemplo, `in` e `mm` referem-se a polegadas e milímetros, respectivamente. As unidades de comprimento absoluto aproximam-se da medida real em uma tela, mas existem algumas diferenças dependendo da resolução da tela. Unidades relativas, como `em` ou `rem`, são relativas a outro valor de comprimento. Por exemplo, `em` é baseado no tamanho da tipografia de um elemento. Se você usá-la para definir o valor da propriedade `font-size`, esse valor será relativo a propriedade `font-size` do elemento pai. **Observação:** existem diversas unidades do tipo relativo que são vinculadas ao tamanho da janela do navegador (viewport). Elas serão abordadas na seção Princípios de Web Design Responsivo. # --instructions-- No elemento que possui a classe `red-box`, adicione a propriedade `padding` com o valor `1.5em`. # --hints-- A classe `red-box` deve ter a propriedade `padding`. ```js assert( $('.red-box').css('padding-top') != '0px' && $('.red-box').css('padding-right') != '0px' && $('.red-box').css('padding-bottom') != '0px' && $('.red-box').css('padding-left') != '0px' ); ``` A classe `red-box` deve dar aos elementos 1.5em de `padding`. ```js assert(code.match(/\.red-box\s*?{[\s\S]*padding\s*:\s*?1\.5em/gi)); ``` # --seed-- ## --seed-contents-- ```html <style> .injected-text { margin-bottom: -25px; text-align: center; } .box { border-style: solid; border-color: black; border-width: 5px; text-align: center; } .yellow-box { background-color: yellow; padding: 20px 40px 20px 40px; } .red-box { background-color: red; margin: 20px 40px 20px 40px; } .green-box { background-color: green; margin: 20px 40px 20px 40px; } </style> <h5 class="injected-text">margin</h5> <div class="box yellow-box"> <h5 class="box red-box">padding</h5> <h5 class="box green-box">padding</h5> </div> ``` # --solutions-- ```html <style> .injected-text { margin-bottom: -25px; text-align: center; } .box { border-style: solid; border-color: black; border-width: 5px; text-align: center; } .yellow-box { background-color: yellow; padding: 20px 40px 20px 40px; } .red-box { background-color: red; margin: 20px 40px 20px 40px; padding: 1.5em; } .green-box { background-color: green; margin: 20px 40px 20px 40px; } </style> <h5 class="injected-text">margin</h5> <div class="box yellow-box"> <h5 class="box red-box">padding</h5> <h5 class="box green-box">padding</h5> </div> ```
#include "../base_types.h" #include "../basic_functions.h" #include "../image.h" #include "../image_operations.h" template<typename ElementT> void print3(std::vector<TinyDIP::Image<ElementT>> input) { for (std::size_t i = 0; i < input.size(); i++) { input[i].print(); std::cout << "*******************\n"; } } template<typename T> void idct3DetailTest(const std::size_t N1, const std::size_t N2, const std::size_t N3) { std::vector<TinyDIP::Image<T>> test_input; for (std::size_t z = 0; z < N3; z++) { test_input.push_back(TinyDIP::Image<T>(N1, N2)); } for (std::size_t z = 1; z <= N3; z++) { for (std::size_t y = 1; y <= N2; y++) { for (std::size_t x = 1; x <= N1; x++) { test_input[z - 1].at(y - 1, x - 1) = x * 100 + y * 10 + z; } } } print3(test_input); auto dct_plane = TinyDIP::dct3_one_plane(test_input, 0); std::vector<decltype(dct_plane)> dct_planes; for (std::size_t z = 0; z < N3; z++) { dct_planes.push_back(TinyDIP::dct3_one_plane(test_input, z)); } auto idct_result = TinyDIP::idct3_one_plane(dct_planes, 0); idct_result.print(); } int main() { auto start = std::chrono::system_clock::now(); idct3DetailTest<double>(10, 10, 10); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; }
const express = require("express"); const mongoose = require("mongoose"); const annoucementModel = require("../models/announcement.model.js"); const createAnnoucementController = async(req, res) => { const data = req.body; data.createdBy = req._id try { const newData = await annoucementModel.create(data); if(!newData){ return res.status(400).json("Error creating new announcement"); } return res.status(200).json(newData); } catch (error) { console.log(error.message); return res.status(500).json(error.message); } } const editAnnoucementController = async(req, res) => { const data = req.body; try { const updatedData = await annoucementModel.findOneAndUpdate({_id: data._id}, data, {new: true}); if(!updatedData){ return res.status(400).json("Error updating the data"); } return res.status(200).json(updatedData); } catch (error) { console.log(error.message); return res.status(500).json(error.message); } } const deleteAnnoucementController = async(req, res) => { const id = req.params.id; try { const deletedData = await annoucementModel.findOneAndDelete({_id: id}); if(!deletedData){ return res.status(400).json("Error deleting the data"); } return res.status(200).json("Data deleted Succesfully !"); } catch (error) { console.log(error.message); return res.status(500).json(error.message); } } const getAllAnnouncementController = async(req, res) => { try { const allData = await annoucementModel.find(); if(!allData) { return res.status(400).json("Error getting all annoucenemts"); } return res.status(200).json(allData); } catch (error) { console.log(error.message); return res.status(500).json(error.message); } } const getAnnouncementController = async(req, res) => { const id = req.params.id; try { const data = await annoucementModel.findOne({_id: id}); if(!data) { return res.status(400).json("Error getting annoucenemt"); } return res.status(200).json(data); } catch (error) { console.log(error.message); return res.status(500).json(error.message); } } module.exports = { createAnnoucementController, editAnnoucementController, deleteAnnoucementController, getAllAnnouncementController, getAnnouncementController }
/* * Copyright (C) 2005-present, 58.com. All rights reserved. * * 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.wuba.wsilk.codegen; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Collection; import com.google.common.base.Function; import com.wuba.wsilk.codegen.model.Parameter; import com.wuba.wsilk.codegen.model.Type; import com.wuba.wsilk.codegen.spec.FieldElement; import com.wuba.wsilk.codegen.spec.MethodElement; /** * * 写java * * @author mindashuang */ public interface IJavaWriter<T extends AbstractCodeWriter<T>> extends CodeWriter<T> { /** * * 通过类型获得原始名字 * * @param type 类型 * @return 获得原始名字 */ String getRawName(Type type); /** * 获得泛型名字 * * @param asArgType 是否是参数类型 * @param type 类型 * @return 获得泛型名字 */ String getGenericName(boolean asArgType, Type type); /** * 获得类的常量 * * @param className 类名 * * @return 类的常量名 */ String getClassConstant(String className); /** * 设置包路径 * * @param packageName 包路径 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T packageDecl(String packageName) throws IOException; /** * 导入的类 * * @param imports 类信息 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T imports(Class<?>... imports) throws IOException; /** * 导入的包 * * @param imports 包信息 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T imports(Package... imports) throws IOException; /** * 导入的类 * * @param classes 类数组 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T importClasses(String... classes) throws IOException; /** * 导入包 * * @param packages 导入的包 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T importPackages(String... packages) throws IOException; /** * 静态导入 * * @param imports 导入的类 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T staticimports(Class<?>... imports) throws IOException; /** * 添加注解 * * @param annotation 注解 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T annotation(Annotation annotation) throws IOException; /** * 添加注解 * * @param annotation 注解 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T annotation(Class<? extends Annotation> annotation) throws IOException; /** * 创建一个类 * * @param modifier 修饰符 * @param type 类的类型 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginClass(Modifier.Class modifier, Type type) throws IOException; /** * 创建一个类 * * @param modifier 修饰符 * @param type 类的类型 * @param superClass 父类类型 * @param interfaces 继承的接口 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginClass(Modifier.Class modifier, Type type, Type superClass, Type... interfaces) throws IOException; /** * 创建一个接口 * * @param modifier 修饰符 * @param type 接口类型 * @param interfaces 继承的接口 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginInterface(Modifier.Class modifier, Type type, Type... interfaces) throws IOException; /** * 添加构造器 * * @param modifier 修饰符 * @param params 方法参数 * @param transformer 参数转换器 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ <M> T beginConstructor(Modifier.Field modifier, Collection<M> params, Function<M, Parameter> transformer) throws IOException; /** * 添加构造器 * * @param modifier 修饰符 * @param params 方法参数 * * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginConstructor(Modifier.Field modifier, Parameter... params) throws IOException; /** * 添加方法 * * @param modifier 修饰符 * @param returnType 返回值 * @param exceptions 异常类型 * @param methodName 方法名 * @param args 方法参数 * * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginMethod(Modifier.Field modifier, Type returnType, String methodName, Type[] exceptions, Parameter... args) throws IOException; /** * 添加方法 * * @param modifier 修饰符 * @param returnType 返回值 * @param methodName 方法名 * @param parameters 方法参数 * @param transformer 参数转换器 * * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ <M> JavaWriter beginMethod(Modifier.Field modifier, Type returnType, String methodName, Collection<M> parameters, Function<M, Parameter> transformer) throws IOException; /** * 添加方法 * * @param methodElement 方法的结构 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginMethod(MethodElement methodElement) throws IOException; /** * 结束方法 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T end() throws IOException; /** * 添加字段 * * @param type 类型 * @param name 名字 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T field(Type type, String name) throws IOException; /** * 添加字段 * * @param type 类型 * @param name 名字 * @param value 值 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T field(Type type, String name, String value) throws IOException; /** * 添加字段 * * @param modifier 修饰符 * @param type 类型 * @param name 名字 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T field(Modifier.Field modifier, Type type, String name) throws IOException; /** * 添加字段 * * @param modifier 修饰符 * @param type 类型 * @param name 名字 * @param value 值 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T field(Modifier.Field modifier, Type type, String name, String value) throws IOException; /** * 添加字段 * * @param fieldElement 字段结构 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T field(FieldElement fieldElement) throws IOException; /** * 添加doc * * @param lines 代码片段 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T javadoc(String... lines) throws IOException; /** * 添加一行数据 * * @param segments 代码片段 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T beginLine(String... segments) throws IOException; /** * 按照行输出代码 * * @param segments 代码片段 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T line(String... segments) throws IOException; /** * 换行 * * @return 返回代码输出器 * @throws IOException 代码输出异常 */ T nl() throws IOException; /** * 添加警告注解 * * @param type 类型 * * @return 返回代码输出器 * @throws IOException 代码输出异常 * */ T suppressWarnings(String type) throws IOException; /** * 添加警告注解 * * @param types 类型 * * @return 返回代码输出器 * @throws IOException 代码输出异常 * */ T suppressWarnings(String... types) throws IOException; }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { Permissions } from '@shared/types'; import { AuthGuard } from '../auth'; import { AddEmployeeComponent, EditEmployeeComponent, ListEmployeeComponent } from './pages'; const rootRoutes: Routes = [ { path: '', redirectTo: 'list', pathMatch: 'full' }, { path: 'list', component: ListEmployeeComponent, canActivate: [AuthGuard], data: { breadcrumb: 'List', permission: Permissions.Employee.View } }, { path: 'add', component: AddEmployeeComponent, canActivate: [AuthGuard], data: { breadcrumb: 'Add', permission: Permissions.Employee.Create } }, { path: 'edit/:id', component: EditEmployeeComponent, canActivate: [AuthGuard], data: { breadcrumb: 'Edit', permission: Permissions.Employee.Edit } }, ]; @NgModule({ imports: [RouterModule.forChild(rootRoutes)], exports: [RouterModule], }) export class EmployeeRoutingModule {}
# -*- encoding: utf-8 -*- ''' @Author : hesy @Contact : hesy519@gmail.com @Desc : [hard] ''' from typing import Dict, List from util import * from loguru import logger as log #ipdb.set_trace=blockIpdb blockPrint() enablePrint() from collections import deque, defaultdict class Solution: res = 0 def minJumps(self, arr: List[int]) -> int: if len(arr) < 2: return 0 idxs = deque([0]) visited = [False for _ in range(len(arr))] visited[0] = True hashMap = defaultdict(list) for i in range(len(arr)): hashMap[arr[i]].append(i) self.BFS(visited, hashMap, 1, idxs, arr) return self.res def BFS(self, visited, hashMap, step, idxs, arr): newIdxs = deque() while len(idxs): curIdx = idxs.popleft() for nextIdx in [curIdx + 1, curIdx - 1]: if 0 <= nextIdx < len(arr) and not visited[nextIdx]: if nextIdx == len(arr) - 1: self.res = step return newIdxs.append(nextIdx) visited[nextIdx] = True for nextIdx in hashMap[arr[curIdx]]: if not visited[nextIdx]: if nextIdx == len(arr) - 1: self.res = step return newIdxs.append(nextIdx) visited[nextIdx] = True hashMap[arr[curIdx]] = [] #* important for o(n^2)'s bad case self.BFS(visited, hashMap, step + 1, newIdxs, arr) if __name__ == "__main__": sol = Solution() print(f"res is {sol.minJumps([100, -23, -23, 404, 100, 23, 23, 23, 3, 404])}") # 3 print(f"res is {sol.minJumps([0,1,2,3])}") # 3 print(f"res is {sol.minJumps([0,1,0,3])}") # 2 print(f"res is {sol.minJumps([7,6,9,6,9,6,9,7])}") # 1 print(f"res is {sol.minJumps([7])}") # 0
import React from "react"; interface BrandInputProps { className?: string; placeholder: string; name: string; type: string; } const BrandInput: React.FC<BrandInputProps> = ({ className, placeholder, name, type, }) => { return ( <input type={type} name={name} placeholder={placeholder} className={`border-b-2 outline-0 focus:border-brand_neutral-100 ${className}`} /> ); }; export default BrandInput;
// global constants const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence //Global Variables var pattern = [6, 5, 3, 5, 3, 1, 4, 2, 5, 6, 4, 2]; var progress = 0; var gamePlaying = false; var tonePlaying = false; var volume = 0.5; var guessCounter = 0; var clueHoldTime = 1000; //how long to hold each clue's light/sound var cluePauseTime = 333; //how long to pause in between clues var min = Math.ceil(1); var max = Math.floor(7); function startGame(){ //initialize game variables progress = 0; gamePlaying = true; clueHoldTime = 1000; cluePauseTime = 333; randPattern(); // swap the Start and Stop buttons document.getElementById("startBtn").classList.add("hidden"); document.getElementById("stopBtn").classList.remove("hidden"); playClueSequence(); } function stopGame() { gamePlaying = false; document.getElementById("startBtn").classList.remove("hidden"); document.getElementById("stopBtn").classList.add("hidden"); } // Sound Synthesis Functions const freqMap = { 1: 200.6, 2: 260.6, 3: 320, 4: 380.2, 5: 450.2, 6: 510.2, } function playTone(btn,len){ o.frequency.value = freqMap[btn] g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025) tonePlaying = true setTimeout(function(){ stopTone() },len) } function startTone(btn){ if(!tonePlaying){ o.frequency.value = freqMap[btn] g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025) tonePlaying = true } } function stopTone(){ g.gain.setTargetAtTime(0,context.currentTime + 0.05,0.025) tonePlaying = false } //Page Initialization // Init Sound Synthesizer var context = new AudioContext() var o = context.createOscillator() var g = context.createGain() g.connect(context.destination) g.gain.setValueAtTime(0,context.currentTime) o.connect(g) o.start(0) function lightButton(btn){ document.getElementById("button"+btn).classList.add("lit") } function clearButton(btn){ document.getElementById("button"+btn).classList.remove("lit") } function playSingleClue(btn){ if(gamePlaying){ lightButton(btn); playTone(btn,clueHoldTime); setTimeout(clearButton,clueHoldTime,btn); } } function playClueSequence(){ guessCounter = 0; let delay = nextClueWaitTime; //set delay to initial wait time for(let i=0;i<=progress;i++){ // for each clue that is revealed so far console.log("play single clue: " + pattern[i] + " in " + delay + "ms") setTimeout(playSingleClue,delay,pattern[i]) // set a timeout to play that clue delay += clueHoldTime delay += cluePauseTime; } } function loseGame(){ stopGame(); alert("Game Over. You lost."); } function winGame() { stopGame(); alert("Congratulations! You win!"); } function guess(btn){ console.log("user guessed: " + btn); if(!gamePlaying){ return; } if(btn == pattern[guessCounter]) { if(guessCounter == progress) { if(progress == pattern.length - 1) { winGame(); } else { progress++; clueHoldTime -= 70; cluePauseTime -= 15; playClueSequence(); } } else { guessCounter++; } } else { loseGame(); } } function randPattern() { for(let i = 0;i < 12; i++) { pattern[i] = Math.floor(Math.random() * (max - min) + min); } }
# Class Notes ## Table of Contents - [Class Notes](#class-notes) - [Resources](#resources) - [Python_5](#python_5) - [封装的概念](#封装的概念) - [Function 的优势](#function-的优势) - [模块化](#模块化) - [Function Calls and Definition](#function-calls-and-definition) - [Positional Arguments](#positional-arguments) - [Keyword Arguments](#keyword-arguments) - [Default Parameters](#default-parameters) - [Argument Tuple Packing](#argument-tuple-packing) - [Argument Dictionary Packing](#argument-dictionary-packing) - [Putting It All Together](#putting-it-all-together) - [lambda function](#lambda-function) - [dis 库](#dis-库) - [lambda 的优势和使用场景](#lambda-的优势和使用场景) - [Decorator](#decorator) - [Decorator 例子 1: 计算运行时间](#decorator-例子-1-计算运行时间) - [计算函数平均执行时间 - timeit 库](#计算函数平均执行时间---timeit-库) - [Decorator 例子 2: logging](#decorator-例子-2-logging) - [Decorator 的其他应用场景](#decorator-的其他应用场景) - [cProfile](#cprofile) - [map/filter/reduce](#mapfilterreduce) - [map 返回一个迭代器 (对每个元素统一执行相同操作)](#map-返回一个迭代器-对每个元素统一执行相同操作) - [filter 返回一个迭代器 (挑选满足条件的元素)](#filter-返回一个迭代器-挑选满足条件的元素) - [reduce 返回一个值 (累加, 累乘)](#reduce-返回一个值-累加-累乘) - [List comprehension 实现 map/filter/reduce](#list-comprehension-实现-mapfilterreduce) - [为什么推荐使用 List comprehension 而不是直接使用 map/filter/reduce?](#为什么推荐使用-list-comprehension-而不是直接使用-mapfilterreduce) - [使用 List comprehension 实现 map](#使用-list-comprehension-实现-map) - [两种错误写法](#两种错误写法) - [使用 List comprehension 实现 filter](#使用-list-comprehension-实现-filter) - [使用 List comprehension 实现 reduce](#使用-list-comprehension-实现-reduce) - [List comprehension vs map/filter/reduce 总结](#list-comprehension-vs-mapfilterreduce-总结) - [Generator Expression 为什么比 List comprehension 更好?](#generator-expression-为什么比-list-comprehension-更好) - [Generator expression vs List comprehension 执行结果](#generator-expression-vs-list-comprehension-执行结果) - [Generator expression vs List comprehension 总结](#generator-expression-vs-list-comprehension-总结) ## Resources - [Python_lambda](https://www.w3schools.com/python/python_lambda.asp) - [Python_decorator](https://foofish.net/python-decorator.html) - [Python_map](https://www.w3schools.com/python/ref_func_map.asp) - [Python_filter](https://www.freecodecamp.org/chinese/news/python-filter-function) - [Python_reduce](https://www.runoob.com/python/python-func-reduce.html) - [Generator Expression vs List Comprehension](./Generator%20Expression%20vs%20List%20Comprehension.py) ## Python_5 #### 封装的概念 - 在编程中,封装是一种将数据(属性)和代码(方法)绑定到一起的机制,以隐藏具体实现的方式 - 这是面向对象编程(OOP)的四大基本原则之一 - 封装的主要目的是保护对象内部的状态和实现细节,只允许通过定义好的接口(即公有方法)来访问对象的状态 - 老师的理解:开发者之间只通过接口进行交流,不需要去管封装里面的内容 #### Function 的优势 ##### 模块化 - Reusable - 模块化之前,每个功能都要重新写一遍内容 ![](../image/模块化1.png) - 模块化之后,所有的功能只需要在写完一遍之后分别调用就好 ![](../image/模块化2.png) #### Function Calls and Definition ![](../image/Function Calls and Definition.png) #### Positional Arguments - 即 Arguments 是按顺序出现的 ![](../image/Positional Arguments.png) - input parameters: signature of the function(参数即签名) - polymorphism(多态:只要符合位置要求,任何类型的参数均可填入) - 但注意不能超过或少于参数数量范围 ![](../image/Positional Arguments1.png) #### Keyword Arguments - 正常情况下,每个 keyword 对应的参数会按顺序输出 ![](../image/Keyword Arguments1.png) - 修改 keyword 关键词会导致报错 ![](../image/Keyword Arguments2.png) - 省去一两个 keyword 不会影响输出,系统会按照 Positional Arguments 的顺序继续执行 ![](../image/Keyword Arguments3.png) - 注意:当所有 arguments 中只有一个 keyword 时,只能出现在最右边,不然会报错 ![](../image/Keyword Arguments4.png) #### Default Parameters - 当定义了默认值时,少输或者不输入内容时系统会自动用默认值补齐 ![](../image/Default Parameters.png) #### Argument Tuple Packing - 当不确定 parameter 的个数时,可以采用 packing ![](../image/Argument Tuple Packing.png) #### Argument Dictionary Packing - 多个 value 变成一个 Dic ![](../image/Argument Dictionary Packing.png) #### Putting It All Together - 当所有类型的数据放在一起 packing 时,keyword 类型也要放在最右边 packing ![](../image/Putting It All Together.png) ### lambda function lambda function是有返回值的匿名函数, 并且只能执行返回值操作。 > 提升可读性, 对于一些只调用一次的函数, 没必要定义一个命名函数, 使用 lambda funciton 是较好的。 ```python # lambda input: expression # 1. 求和 print((lambda x, y: x + y)(2, 3)) #5 # 2. array每个元素平方 arr = [1,2,3,4,5] new_arr=list(map(lambda x:x**2, arr)) print(new_arr) # [1, 4, 9, 16, 25] # 3. sort a = [2, 3, 9, 7, 4] a.sort(key=lambda x: x) print(a) # [2, 3, 4, 7, 9] a.sort(key=lambda x: -x) print(a) # [9, 7, 4, 3, 2] ``` #### dis 库 ```python import dis # 使用 dis 模块查看代码在底层是如何执行的 dis.dis(lambda x, y: x + y) ``` #### lambda 的优势和使用场景 - 简洁性&匿名性: 减少了不必要的命名和函数定义,使代码更加紧凑 - 匿名性: 避免命名冲突, 覆盖本地库 - 内联使用: Lambda 函数通常用于一些只在一个地方被调用一次的操作,避免了为简单操作创建单独的命名函数; 避免覆盖本地库 > lambda 不能直接使用->这种 annotation, 但可以使用 Callable 检查 ```python from typing import Callable addition: Callable[[int], int] = lambda x: x + 1 result = addition([3]) # 会提示type error print(result) ``` ### Decorator `Higher Order Function` - 一定是嵌套函数(nested function) - 在不修改原始代码的情况下, 对函数或类的功能进行增强或修改 ```python from typing import Callable, Tuple addition: Callable[[int, int, int], int] = lambda x, y, z: x + y + z def high_order(func, input: Tuple[int, int, int]) -> int: return func(*input) print(high_order(addition, (1, 2, 3))) # 6 ``` ```python def my_decorator(func): def wrapper(): print('before') func() print('after') return wrapper @my_decorator def say_hello(): print('Hello') say_hello() # before Hello after def say_hi(): print('Hi') decorated_say_hi = my_decorator(say_hi) print(decorated_say_hi) ``` #### Decorator 例子 1: 计算运行时间 ```python import time def calculate_runtime(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() runtime = end_time - start_time print(f"Function {func.__name__} took {runtime:.6f} seconds to run.") return result return wrapper @calculate_runtime def slow_function(n): total = 0 for i in range(n): total += i time.sleep(0.1) return total print(slow_function(5)) ``` ##### 计算函数平均执行时间 - timeit 库 ```python import timeit def example_code(): total = 0 for i in range(20): total += i return total # 测量 example_code 的平均执行时间,执行 1000 次 execution_time = timeit.timeit(example_code, number=10) print(f"Average execution time: {execution_time:.6f} seconds") ``` #### Decorator 例子 2: logging ```python import logging def log_function_calls(func): logging.basicConfig(level=logging.INFO) def wrapper(*args, **kwargs): logging.info( f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}" ) result = func(*args, **kwargs) logging.info(f"{func.__name__} returned: {result}") return result return wrapper @log_function_calls def add(a, b): return a + b @log_function_calls def multiply(x, y): return x * y result1 = add(3, 5) result2 = multiply(2, 4) ``` #### Decorator 的其他应用场景 装饰器在的其他应用场景: - Authorization: You can use decorators to check if a user has the permission to execute specific requests. - Caching/Memoization: Decorators can be used for caching the results of a function to improve speed. If a function is frequently called with the same parameters, decorators can store the previous results. - Data Validation: Decorators can be used to automatically validate the input and output of a function, ensuring they meet certain requirements. - Retry Mechanism: In network requests or other potentially failing operations, decorators can be used for automatic retries. - Feature Toggling: Decorators can control the enabling or disabling of specific features, making feature toggling easier. - Monitoring and Statistics: Decorators can be used to gather information about how a function is used and may send this information to external tools for monitoring or analysis. - AOP (Aspect-Oriented Programming): Decorators allow you to separate cross-cutting concerns like logging and security from business logic, making the code cleaner and more maintainable. - Response Handling: In web frameworks, decorators can be used for pre-processing or post-processing HTTP responses, such as adding headers or changing status codes. - Routing: Many web frameworks use decorators to link functions with URL routes. - Event Registration: Decorators can be used for registering event handlers in a system. #### cProfile > 提供了一个轻量级的性能分析器,可以用来测量函数调用的时间和调用次数,帮助您识别代码中的瓶颈和优化点。 ```python import cProfile def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) if __name__ == "__main__": cProfile.run("fibonacci(30)") ``` ### map/filter/reduce #### map 返回一个迭代器 (对每个元素统一执行相同操作) ```python print(list(map(lambda x: x * 2, [1, 2, 3, 4, 5]))) # [2, 4, 6, 8, 10] ``` #### filter 返回一个迭代器 (挑选满足条件的元素) ```python print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))) # [2, 4, 6] ``` #### reduce 返回一个值 (累加, 累乘) ```python from functools import reduce print(reduce(lambda x, y: x * y, [1,2,3])) # 6 ``` **一般推荐使用 list comprehensive 或 generator expression 而避免使用 map/filter. reduce** ### List comprehension 实现 map/filter/reduce #### 为什么推荐使用 List comprehension 而不是直接使用 map/filter/reduce? ![](../image/List comprehension vs map:filter:reduce.png) #### 使用 List comprehension 实现 map ```python print([i * 2 for i in [1, 2, 3, 4, 5, 6]]) # [2, 4, 6, 8, 10, 12] ``` ##### 两种错误写法 ```python print([i *= 2 for i in [1, 2, 3, 4, 5, 6]]) ``` > 第一个写法的错误原因是 i\*=2 没有返回值 ```python print([i := i * 2 for i in [1, 2, 3, 4, 5, 6]]) ``` > 第二种写法的错误原因是迭代变量 i 在 List comprehension 中是只读的, 不能重新绑定 #### 使用 List comprehension 实现 filter ```python print([i for i in [1, 2, 3, 4, 5, 6] if i % 2 == 0]) # [2, 4, 6] ``` #### 使用 List comprehension 实现 reduce ```python product = 1 print([product := product * num for num in [1, 2, 3]][-1]) # 6 ``` 使用了 python3.8 版本引入的 Assignment Expresions 实现了 reduce 操作. 累乘实际上直接用 reduce 实现起来更容易些, 但对于[简单的情况](#为什么推荐使用list-comprehension而不是直接使用mapfilterreduce), 可以用 List comprehension #### List comprehension vs map/filter/reduce 总结 对于简单操作且数据量较少, 用写法简洁的list comprehension好; 数据集庞大且需要复杂处理时, 用map等内置方法能节约内存 (map方法return的是iterator不是iterable) ### Generator Expression 为什么比 List comprehension 更好? #### Generator expression vs List comprehension 执行结果 ```python """ list()+generator和list_comprehension都能得到list 但使用list()+generator的写法比用list_comprehension更省内存, 执行速度快一点 """ from sys import getsizeof as getsize import time list_comprehension_a = [i * 2 for i in range(1000000)] generator_expression_a = (i * 2 for i in range(1000000)) generator_expression_list_a = list(generator_expression_a) print( f"value: {len(list_comprehension_a)} | 使用列表生成式的size: {getsize(list_comprehension_a)}" ) print( f"value: {len(generator_expression_list_a)} | 使用生成式+list()的size: {getsize(generator_expression_list_a)}" ) start_time = time.time() print(sum(list_comprehension_a)) end_time = time.time() print(f"使用列表生成式的sum执行时间: {end_time - start_time} 秒") start_time = time.time() print(sum(generator_expression_list_a)) end_time = time.time() print(f"使用生成器表达式的sum执行时间: {end_time - start_time} 秒") # 用生成式做需要iterable方法的参数, 可以省略(), 更简洁 print(sum([x for x in range(3)])) print(sum(x for x in range(3))) ``` #### Generator expression vs List comprehension 总结 - 大多数情况下, 对于需要 iterable 做参数的内置方法, 可以优先使用 Generator Expression. 这样写法更简洁, 也能达到相同效果 - 即使需要输出一个 list, 也可以通过 list() + Generator Expression 轻松实现. 更重要是在数据量很大时, 使用 list() + Generator Expression [不仅节省内存而且可以提升效率](#generator-expression-vs-list-comprehension执行结果)
<div class="row mb-3"> <div class="mb-3 mb-sm-0"> <div class="card"> <div class="card-header"> <h4>Карточка товара</h4> </div> <div class="card-body"> <div class="row mb-3"> <div class="col-6"> <h6>id</h6> <p>{{ electroItem.id }}</p> <h6>Наименование товара</h6> <p>{{ electroItem.name }}</p> <h6>Тип</h6> <p>{{ electroItem.electroType?.name }}</p> <h6>Цена, руб</h6> <p>{{ electroItem.price }}</p> </div> <div class="col-6"> <h6>Количество</h6> <p>{{ electroItem.count }}</p> <h6>Доступность товара</h6> <div class="text-danger" *ngIf="electroItem.archive; else unset">в архиве</div> <ng-template #unset> <div class="text-success mb-3">доступен для заказа</div> </ng-template> <h6>Описание</h6> <p>{{ electroItem.description }}</p> </div> </div> </div> <div class="card-footer"> <!-- Update button trigger modal --> <button type="button" class="btn btn-warning me-md-2" data-bs-toggle="modal" data-bs-target="#updateModal"> Редактировать </button> <!-- Delete button trigger modal --> <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteModal"> Удалить </button> </div> </div> </div> </div> <h4 class="p-3">Наличие товара по магазинам</h4> <table class="table table-sm table-striped"> <thead> <tr> <th>Магазин</th> <th>Адрес</th> <th>Количество</th> <th></th> </tr> </thead> <tbody class="table-group-divider"> <tr *ngFor="let shopDto of shopDtoList"> <td> {{ shopDto.name }}</td> <td> {{ shopDto.address }}</td> <td> {{ shopDto.count }}</td> <td> <!-- Add button trigger modal --> <button type="button" class="btn btn-sm btn-outline-primary me-md-2" data-bs-toggle="modal" data-bs-target="#addModal" (click)="setElectroShop(shopDto, shopDto.count)"> Пополнить товар </button> </td> </tr> </tbody> </table> <hr> <!-- Import from csv --> <h5 class="mb-3">Распределить товар по магазинам согласно данным из csv-файла</h5> <p>Распределение выполнится для всех товаров списка</p> <div class="form-group mb-3"> <input class="form-control" type="file" (change)="onFileSelected($event)" #fileUpload id="formFile" accept=".csv"> </div> <div *ngIf="importedData" class="mb-3"> <h6 class="mb-3">Данные к импорту</h6> <table class="table table-sm table-striped"> <thead> <tr> <th>Магазин</th> <th>Адрес</th> <th>Количество</th> </tr> </thead> <tbody class="table-group-divider"> <tr *ngFor="let electroShop of importedData"> <td> {{ electroShop.electroShopPK?.shop?.name }}</td> <td> {{ electroShop.electroShopPK?.electroItem?.name }}</td> <td> {{ electroShop.count }}</td> </tr> </tbody> </table> <button type="button" class="btn btn-warning" (click)="saveImportedDataToDatabase()"> Распределить </button> </div> <!-- Add Modal --> <div class="modal fade" id="addModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="addModalLabel">Пополнение товара</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-group mb-3"> <label for="amount" class="form-label">Количество</label> <input type="number" step="1" class="form-control" id="amount" [(ngModel)]="addedAmount" name="amount"> <div id="amount_help" class="form-text"> Количество товара, добавляемого в указанный магазин </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <button type="button" class="btn btn-success" data-bs-dismiss="modal" (click)="updateElectroShop()"> Сохранить </button> </div> </div> </div> </div> <!-- Update Modal --> <div class="modal fade" id="updateModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="updateModalLabel">Редактирование товара</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-group mb-3"> <label for="item_name" class="form-label">Наименование *</label> <input type="text" class="form-control" id="item_name" [(ngModel)]="electroItem.name" name="item_name"> <div id="item_name_help" class="form-text"> Наименование товара </div> </div> <div class="form-group mb-3"> <label for="item_type" class="form-label">Тип товара *</label> <select class="form-select" [ngModel]="ElectroType" (ngModelChange)="onChangeType($event)" name="type_select"> <option *ngFor="let itemType of electroTypeList" [ngValue]="itemType" id="item_type"> {{ itemType.name }} </option> </select> <div id="item_type_help" class="form-text"> Выберите тип товара </div> </div> <div class="form-group mb-3"> <label for="item_price" class="form-label">Стоимость, руб *</label> <input type="number" step="1" class="form-control" id="item_price" [(ngModel)]="electroItem.price" name="item_price"> <div id="item_price_help" class="form-text"> Стоимость товара </div> </div> <div class="form-group mb-3"> <label for="description" class="form-label">Описание *</label> <textarea class="form-control" id="description" rows="3" [(ngModel)]="electroItem.description"></textarea> <div id="description_help" class="form-text"> Описание товара </div> </div> <label class="form-label"> <mark>Поля, отмеченные "*" обязательны к заполнению</mark> </label> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <button type="button" class="btn btn-success" data-bs-dismiss="modal" (click)="updateElectroItem()"> Сохранить </button> </div> </div> </div> </div> <!-- Delete Modal --> <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header text-bg-danger"> <h1 class="modal-title fs-5" id="deleteModalLabel">Подтвердите удаление</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Внимание! Данное действие приведет к полному удалению без возможности восстановления </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <button type="button" class="btn btn-danger" data-bs-dismiss="modal" (click)="deleteElectroItem()"> Подтвердить </button> </div> </div> </div> </div>
part of '../ecs.dart'; class Vector3Component extends ComponentInstance<Vector3> { Vector3Component(super.type); Vector3? _data; @override void set(Vector3? data) { _data = data; } @override Vector3? get() { return _data; } } class Vector3ComponentFactory extends ComponentFactory<Vector3> { @override ComponentInstance<Vector3> allocInstance(ComponentType<Vector3> type) { assert(type._factory == this); return Vector3Component(type); } @override void freeInstance(ComponentInstance<Vector3> instance) {} } class Float32ListComponent extends ComponentInstance<Float32List> { Float32ListComponent(this._data, super.type); final Float32List _data; @override void set(Float32List? data) { assert(data != null); assert(data != null && _data.length == data.length); for (int i = 0; i < _data.length; i++) { _data[i] = data![i]; } } @override Float32List? get() { return _data; } } class Float4ComponentFactory extends ComponentFactory<Float32List> { @override ComponentInstance<Float32List> allocInstance( ComponentType<Float32List> type) { assert(identical(type._factory, this)); return Float32ListComponent(Float32List(4), type); } @override void freeInstance(ComponentInstance<Float32List> instance) {} } class Float16ComponentFactory extends ComponentFactory<Float32List> { @override ComponentInstance<Float32List> allocInstance( ComponentType<Float32List> type) { assert(identical(type._factory, this)); return Float32ListComponent(Float32List(16), type); } @override void freeInstance(ComponentInstance<Float32List> instance) {} } /// Vector3 component type. late ComponentType<Vector3> vector3ComponentType; // Float32List of length 4 component type. late ComponentType<Float32List> float4ComponentType; // Float32List of length 16 component type. late ComponentType<Float32List> float16ComponentType; registerBuiltins(World world) { vector3ComponentType = registerComponentType(Vector3ComponentFactory()); float4ComponentType = registerComponentType(Float4ComponentFactory()); float16ComponentType = registerComponentType(Float16ComponentFactory()); }
package com.starwacki.budgettracker.expense; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.LocalTime; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; class ExpenseMapperUnitTest { @Test void shouldReturn_Expense() { //given ExpenseDTO expenseDTO = ExpenseDTO .builder() .name("NAME") .expenseCategory("FOOD") .date(LocalDate.of(2023,10,12)) .moneyValue(200.0) .description("DESC") .time(LocalTime.of(20,12)) .build(); String username = "username"; //when Expense expense = ExpenseMapper.mapExpenseDtoAndUsernameToExpense(expenseDTO,username); //then assertThat(expense.getExpenseCategory(),is("FOOD")); assertThat(expense.getExpenseDate(),is(LocalDate.of(2023,10,12))); assertThat(expense.getExpenseTime(),is(LocalTime.of(20,12))); assertThat(expense.getDescription(),is("DESC")); assertThat(expense.getName(),is("NAME")); assertThat(expense.getUsername(),is("username")); assertThat(expense.getMoneyValue(),is(200.0)); } }
import React from 'react'; import parse from 'html-react-parser'; import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogContent from '@mui/material/DialogContent'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import WarningAmberIcon from '@mui/icons-material/WarningAmber'; import { AddOrderItem } from '../helpers/cartHelper'; import { hasExistentProperty } from '../helpers/genericHelper' import ProductAddRemoveButtons from './ProductAddRemoveButtons'; import './ProductDialog.css'; export const ProductDialog = ({reactOpen, selectedProduct}) => { const [selectedProductCount, setCount] = React.useState(1.0); const [isOpen, setOpen] = reactOpen; const handleClose = () => { setOpen(false); setTimeout(() => setCount(1.0), 500); // Revert to one }; return ( <Dialog open={isOpen} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description"> <DialogContent sx={{ padding: 0 }}> <Stack className="product-dialog"> <Box className="product-dialog__img"> {hasExistentProperty(selectedProduct, 'fieldImage') ? <img src={selectedProduct.fieldImage.imageStyleUri.popupLargeImage} alt={selectedProduct.fieldImage.alt} title={selectedProduct.fieldImage.title} width={selectedProduct.fieldImage.width} height={selectedProduct.fieldImage.height} /> : <img src="https://source.unsplash.com/random" alt="random item"/>} </Box> <Box className="product-dialog__content"> <Box sx={{ margin: '0.5rem 0 1rem' }}> <Typography id="modal-product-title" variant="h6" component="h2" sx={{ mt: 0.5, fontWeight: 'bold' }}> {selectedProduct.title} </Typography> <Typography id="modal-product-description" component="p" sx={{ mb: 1 }}> {selectedProduct.fieldExpired ? <span><WarningAmberIcon sx={{verticalAlign: 'top', color: '#FA9500' }}/>Expired</span> : <span>Not expired</span>} </Typography> {hasExistentProperty(selectedProduct, 'body') ? parse(selectedProduct.body.processed) : null} </Box> <Box sx={{ display: 'flex', justifyContent: 'center' }}> <ProductAddRemoveButtons selectedProduct={selectedProduct} currentQuantity={selectedProductCount} direction="row" iconFontSize={22} onAddOrderItemClick={(maxQuantity) => { const count = Math.min(selectedProductCount+1, maxQuantity); setCount(count); }} onMinusOrderItemClick={(minQuantity) => { const count = Math.max(selectedProductCount-1, minQuantity); setCount(count); }} enableMinQuantityCheck={true} showZeroIfMaxQuantityIsZero={true} /> <div style={{marginRight: 'auto'}}></div> <Button variant="contained" sx={{ backgroundColor: '#75F348', color: 'black', borderRadius: '20px', fontWeight: 'bold', padding: '0 10%' }} disabled={selectedProductCount === 0.0} onClick={() => { AddOrderItem(selectedProduct, selectedProductCount); handleClose(); }}> Add to cart </Button> </Box> </Box> </Stack> </DialogContent> </Dialog> ) }
"use client" import React from "react"; import EndpointContent from './endpointContent'; import { SlArrowDown, SlArrowUp } from "react-icons/sl"; import Link from "next/link"; export default function Endpoint({ status, path, desc, payload, response }: { status: string, path: string, desc: string, payload: Object | null, response: Object | null }) { let colors: any = { "GET": "bg-blue-400", "PUT": "bg-yellow-400", "PATCH": "bg-yellow-400", "POST": "bg-green-400", "DELETE": "bg-red-400", } let color: string = colors[status]; const [toggle, setToggle] = React.useState(false); function handleToggle() { setToggle(!toggle); } return <div> <div className="flex flex-col xl:flex-row lg:flex-row md:flex-col items-center p-2 lg:justify-between mt-3 bg-gray-800"> <h1 className={`${color} font-bold text-sm text-center rounded-3xl w-24 text-gray-900 lg:mr-14`}>{status}</h1> <code className="lg:w-60 hover:underline"> <Link href={path} >{path}</Link> </code> <h3 className="text-sm"> {desc} </h3> <button onClick={handleToggle}> { toggle ? <SlArrowUp className="w-6 h-6" /> : <SlArrowDown className="w-6 h-6" /> } </button> </div> { toggle ? <EndpointContent payload={payload} response={response} /> : false } </div> }
--- ## Front matter title: "Отчёт по лабораторной работе №4" subtitle: "НКНбд-00-21" author: "Самигуллин Эмиль Артурович" ## Generic otions lang: ru-RU toc-title: "Содержание" ## Bibliography bibliography: bib/cite.bib csl: pandoc/csl/gost-r-7-0-5-2008-numeric.csl ## Pdf output format toc: true # Table of contents toc-depth: 2 fontsize: 12pt linestretch: 1.5 papersize: a4 documentclass: scrreprt ## I18n polyglossia polyglossia-lang: name: russian options: - spelling=modern - babelshorthands=true polyglossia-otherlangs: name: english ## I18n babel babel-lang: russian babel-otherlangs: english ## Fonts mainfont: PT Serif romanfont: PT Serif sansfont: PT Sans monofont: PT Mono mainfontoptions: Ligatures=TeX romanfontoptions: Ligatures=TeX sansfontoptions: Ligatures=TeX,Scale=MatchLowercase monofontoptions: Scale=MatchLowercase,Scale=0.9 ## Biblatex biblatex: true biblio-style: "gost-numeric" biblatexoptions: - parentracker=true - backend=biber - hyperref=auto - language=auto - autolang=other* - citestyle=gost-numeric ## Pandoc-crossref LaTeX customization figureTitle: "Рис." tableTitle: "Таблица" listingTitle: "Листинг" lofTitle: "Цель Работы" lotTitle: "Ход Работы" lolTitle: "Листинги" ## Misc options indent: true header-includes: - \usepackage{indentfirst} - \usepackage{float} # keep figures where there are in the text - \floatplacement{figure}{H} # keep figures where there are in the text --- # Цель работы - Научиться вычислять системы линейных уравнений, используя ПО Octave. # Ход работы 1. Решили систему, используя метод Гаусса.(рис. [-@fig:001]) ![Метод Гаусса](image/1.png){ #fig:001 width=70% } 2. Использовали левое деление. (рис. [-@fig:002]) ![Левое Деление](image/2.png){ #fig:002 width=70% } 3. Использовали LU-разложение. (рис. [-@fig:003]) ![LU-разложение](image/3.png){ #fig:003 width=70% } 4. Использовали LUP-разложение (рис. [-@fig:004]) ![LUP-разложение](image/4.png){ #fig:004 width=70% } # Выводы Во время выполнения лабораторной работы мы научились решать системы линейных уравнений, используя Octave. ::: {#refs} :::
<template> <div> <div class="text-h3">CSR Management Panel</div> <!-- CSR Table --> <v-data-table :headers="csrHeaders" :items="items" :expanded.sync="expanded" item-key="name" show-expand id="csr-table" class="elevation-1" > <!-- Title --> <template v-slot:top> <v-toolbar flat> <v-toolbar-title>Certificate Signing Requests</v-toolbar-title> <v-spacer></v-spacer> <v-btn color="primary" dark class="mb-2" @click="getCSRs()" > <v-icon>mdi-refresh</v-icon> Refresh </v-btn> </v-toolbar> </template> <!-- Expanded Item --> <template v-slot:expanded-item="{ headers, item }"> <td :colspan="headers.length"> Signer : {{ item.signer }} </td> </template> <!-- Actions --> <template v-slot:[`item.actions`]="{ item }"> <v-tooltip bottom> <template v-slot:activator="{ on, attrs }"> <v-btn icon @click="approve(item)" :disabled="!(item.status == 'Pending')" v-bind="attrs" v-on="on" > <v-icon small>mdi-check</v-icon> </v-btn> </template> <span>Approve</span> </v-tooltip> <v-tooltip bottom> <template v-slot:activator="{ on, attrs }"> <v-btn icon @click="deny(item)" :disabled="!(item.status == 'Pending')" v-bind="attrs" v-on="on" > <v-icon small>mdi-cancel</v-icon> </v-btn> </template> <span>Deny</span> </v-tooltip> </template> </v-data-table> </div> </template> <script> export default { name: 'CSRPanel', data: () => { return { expanded: [], csrHeaders: [ { text: 'CSR Name', value: 'name', sortable: false }, { text: 'User Name', value: 'username', sortable: false }, { text: 'Status', value: 'status', sortable: false }, { text: 'Created At', value: 'createdAt', sortable: false }, { text: 'Approval', value: 'actions', sortable: false }, ], items: [] } }, mounted() { this.getCSRs() }, methods: { approve(item) { this._approveOrDeny(item, true) }, deny(item) { this._approveOrDeny(item, false) }, clearItems() { this.items = [] }, getCSRs() { const host = this.$host const vm = this this.$axios.get(host + '/api/res/v1/csrs') .then((resp) => { vm.clearItems() const csrs = resp.data.data.csrs csrs.forEach(csr => { vm.items.push({ name: csr.name, username: csr.username, status: csr.status, createdAt: csr.created_at, signer: csr.signer_name }) }) }) .catch((error) => { console.log('[ERROR]', error) alert('Unexpected error occurred.') }) }, _approveOrDeny(item, approval=true) { const host = this.$host const vm = this this.$axios.patch(host + '/api/res/v1/csrs/' + item.name, { condition: approval ? 'Approved' : 'Denied', reason: 'no reason', message: 'no message' }) .then((resp) => { let changed = resp.data.data.changed_condition alert('The status of CertificateSigningRequest ' + item.name + ' has been changed to ' + changed + '.') vm.getCSRs() }) .catch((error) => { console.log('[ERROR]', error) alert('Unexpected error occurred.') }) } } } </script> <style lang="sass"> $data-table-expanded-content-box-shadow: null !default #csr-table margin-top: 50px </style>
import { Component, ViewEncapsulation } from '@angular/core'; import { AppComponent } from '../app.component'; import { MatDialog } from '@angular/material/dialog'; @Component({ selector: 'app-heading', encapsulation: ViewEncapsulation.None, template: ` <div class="left"> <img src="assets/images/logo-mobile.svg" alt=""> <button [disabled]="app.innerWidth >= 768" class="boardName" mat-button (menuOpened)="this.chevronIcon = 'up'" (menuClosed)="this.chevronIcon = 'down'" [matMenuTriggerFor]="menu">{{ app.currentBoard.name }} <img class="chevronIcon" [src]="'assets/images/icon-chevron-' + this.chevronIcon + '.svg'" alt=""></button> <mat-menu class="menuStyles" xPosition="after" #menu="matMenu"> <div class="boards"> <h3 class="boardNumber">All Boards ({{ app.data.length }})</h3> <button [classList]="app.currentBoard.id == board.id ? 'boardBtn selected' : 'boardBtn'" (click)="app.changeCurrentBoard(board)" *ngFor="let board of app.data"> <img src="assets/images/icon-board.svg" alt=""> <p class="boardName">{{ board.name }}</p> </button> <button (click)="app.openNewBoardDialog()" class="createNewBoardBtn"> <img class="boardIcon" src="assets/images/icon-board.svg" alt=""> <p>+ Create New Board</p> </button> </div> <app-theme-toggle></app-theme-toggle> </mat-menu> </div> <div class="right"> <button class="addTaskBtn" (click)="app.openNewTaskDialog()" [disabled]="this.app.data.length == 0"><img src="assets/images/icon-add-task-mobile.svg" alt=""><span class="addNewText">Add New Task</span></button> <button [matMenuTriggerFor]="options" [disabled]="this.app.data.length == 0"><img src="assets/images/icon-vertical-ellipsis.svg" alt=""></button> <mat-menu class="menuStyles" #options="matMenu"> <div class="optionsBtns"> <button (click)="app.openEditBoardDialog()" class="editBoardBtn">Edit Board</button> <button (click)="app.openDeleteBoardDialog()" class="deleteBoardBtn">Delete Board</button> </div> </mat-menu> </div> `, styles: [` .boardName { font-weight: 600; } .optionsBtns { padding: 10px; display: grid; gap: 16px; } .left { display: flex; align-items: center; gap: 16px; } .right { display: flex; align-items: center; gap: 20px; } .addTaskBtn { background-color: var(--purple); border-radius: 20px; padding: 5px 20px; } .addTaskBtn:disabled { opacity: 0.25; } .left > button { display: flex; align-items: center; gap: 8px; } .right > button:last-child { padding: 3px 0 0 0; } .addNewText { display: none; color: var(--white); } @media (min-width: 768px) { .boardName { font-size: 20px; } .boardName:disabled { cursor: auto; } .chevronIcon { display: none; } .boardName:disabled { cursor: auto; } .left > img { display: none; } .addNewText { display: inline; font-size: 15px; font-weight: 600; margin: 0 0 0 10px; } .addTaskBtn { padding: 15px 25px; border-radius: 30px; } } /* DESKTOP STYLES */ @media (min-width: 1281px) { .boardName { font-size: 24px; } } `] }) export class HeadingComponent { constructor(public app: AppComponent, public dialog: MatDialog) {} chevronIcon:any = 'down'; }
import './style.css' import type { WithElementProps } from '../types.tsx' import type { JSX, ComponentChildren } from 'preact' import classnames from 'classnames' type RadioProps = WithElementProps<'input', { label?: ComponentChildren, size?: 'small'|'medium'|'large', fill?: boolean, block?: boolean, onChange?: (event: JSX.TargetedEvent<HTMLInputElement>, checked?: boolean) => void class?: HTMLElement['className'], style?: string, children?: ComponentChildren }> export default function Radio(props: RadioProps): JSX.Element { const { label, size = 'medium', fill, block, onChange, class: className, style, children, ...attributes } = props const classes = classnames( 'ui-radio', block && 'ui-radio--block', fill && 'ui-radio--fill', size && `ui-radio--${size}`, className ) return <> <label class={classes} style={style}> <div class="ui-radio__inner"> <input type="radio" class="ui-radio__input" {...attributes} /> <span class="ui-radio__label">{label}</span> </div> {children && <div class="ui-radio__children"> <div class="ui-radio__children__inner">{children}</div> </div>} </label> </> }
import React, {useEffect, createContext, useReducer,useContext} from 'react' import Navbar from './components/Navbar' import "./App.css" import {BrowserRouter, Route, Switch, useHistory} from 'react-router-dom' import Home from './components/screens/Home' import Signin from './components/screens/Signin' import Signup from './components/screens/Signup' import Profile from './components/screens/Profile' import CreatePost from './components/screens/CreatePost' import {reducer, initialState} from './reducers/userReducer' import UserProfile from './components/screens/UserProfile' import SubscribedUserPosts from "./components/screens/SubscribesUserPosts"; export const UserContext = createContext() const Routing =() =>{ const history = useHistory() const {state, dispatch} = useContext(UserContext) useEffect(()=>{ const user = JSON.parse(localStorage.getItem("user")) if(user){ dispatch({type:"USER", payload:user}) } else{ history.push('/signin') } },[]) return( <Switch> <Route exact path = "/"> <Home/> </Route> <Route path = "/signin"> <Signin/> </Route> <Route path = "/signup"> <Signup/> </Route> <Route exact path = "/profile"> <Profile/> </Route> <Route path = "/create"> <CreatePost/> </Route> <Route path = "/profile/:userid"> <UserProfile/> </Route> <Route path="/myfollowingpost"> <SubscribedUserPosts /> </Route> </Switch> ) } function App() { const [state, dispatch] = useReducer(reducer, initialState) return ( <UserContext.Provider value = {{state,dispatch}}> <BrowserRouter> <Navbar/> <Routing/> </BrowserRouter> </UserContext.Provider> ); } export default App;
!----------------------------------------------------------------------! ! metropolis.f90 ! ! ! ! Module containing routines relating to the Metropolis algorithm ! ! using Kawasaki dynamics. ! ! ! ! C. D. Woodgate, Warwick 2023 ! !----------------------------------------------------------------------! module metropolis use initialise use kinds use shared_data use io use comms use c_functions use energetics use random_site use analytics use write_netcdf use write_xyz use write_diagnostics implicit none contains !--------------------------------------------------------------------! ! Runs Metropolis with Kawasaki dynamics and performs simulated ! ! annealing. ! ! ! ! C. D. Woodgate, Warwick 2023 ! !--------------------------------------------------------------------! subroutine metropolis_simulated_annealing(setup, my_rank) ! Rank of this processor integer, intent(in) :: my_rank ! Arrays for storing data type(run_params) :: setup ! Integers used in calculations integer :: i,j, div_steps, accept, n_save !,ierr ! Temperature and temperature steps real(real64) :: beta, temp, sim_temp, current_energy, step_E, & step_Esq, C, acceptance ! Name of file for grid state and xyz file at this temperature !character(len=34) :: grid_file character(len=36) :: xyz_file ! Name of file for writing diagnostics at the end character(len=43) :: diagnostics_file ! Name of file for writing radial densities at the end character(len=37) :: radial_file ! Set up the lattice call initial_setup(setup, config) call lattice_shells(setup, shells, config) n_save=floor(real(setup%mc_steps)/real(setup%sample_steps)) div_steps = setup%mc_steps/1000 ! Are we swapping neighbours or on the whole lattice? if (setup%nbr_swap) then setup%mc_step => monte_carlo_step_nbr else setup%mc_step => monte_carlo_step_lattice end if if(my_rank == 0) then write(6,'(/,72("-"),/)') write(6,'(24("-"),x,"Commencing Simulation!",x,24("-"),/)') end if ! Loop over temperature steps do j=1, setup%T_steps step_E = 0.0_real64; step_Esq=0.0_real64 acceptance = 0.0_real64 ! Work out the temperature and corresponding beta temp = setup%T + real(j-1, real64)*setup%delta_T sim_temp = temp*k_b_in_Ry beta = 1.0_real64/sim_temp ! Store this in an array temperature(j) = temp !---------! ! Burn in ! !---------! if (setup%burn_in) then do i=1, setup%burn_in_steps ! Make one MC move accept = setup%mc_step(config, beta) end do end if !-----------------------! ! Main Monte Carlo loop ! !-----------------------! do i=1, setup%mc_steps ! Make one MC move accept = setup%mc_step(config, beta) acceptance = acceptance + accept ! Write percentage progress to screen if (mod(i, setup%sample_steps) .eq. 0) then current_energy = setup%full_energy(config) step_E = step_E + current_energy step_Esq = step_Esq + current_energy**2 end if end do ! Store the average energy per atom at this temperature energies_of_T(j) = step_E/n_save/setup%n_atoms ! Heat capacity (per atom) at this temperature C = (step_Esq/n_save - (step_E/n_save)**2)/(sim_temp*temp)/setup%n_atoms ! Acceptance rate at this temperature acceptance_of_T(j) = acceptance/real(setup%mc_steps) ! Store the specific heat capacity at this temperature C_of_T(j) = C ! Dump grids if needed if (setup%dump_grids) then ! write(grid_file, '(A11 I3.3 A11 I4.4 F2.1 A3)') 'grids/proc_', my_rank, '_grid_at_T_', & ! int(temp), temp-int(temp), '.nc' write(xyz_file, '(A11 I3.3 A12 I4.4 F2.1 A4)') 'grids/proc_', & my_rank, 'config_at_T_', int(temp), temp-int(temp),'.xyz' ! Write xyz file call xyz_writer(xyz_file, config, setup) ! ! Write grid to file ! call ncdf_grid_state_writer(grid_file , ierr, & ! config, temp, setup) end if ! Compute the radial densities at the end of this temperature call radial_densities(setup, config, setup%wc_range, shells, rho_of_T, j) if (my_rank ==0) then ! Write that we have completed a particular temperature write(6,'(a,f7.2,a)',advance='yes') & " Temperature ", temp, " complete on process 0." write(6,'(a,f7.2,a)',advance='yes') & " Internal energy was ", 13.606_real64*1000*energies_of_T(j), " meV/atom" write(6,'(a,f9.4,a)',advance='yes') & " Heat capacity was ", C_of_T(j)/k_B_in_Ry, " kB/atom" write(6,'(a,f7.2,a,/)',advance='yes') & " Swap acceptance rate was ", 100.0*acceptance_of_T(j), "%" end if end do ! Loop over temperature write(radial_file, '(A22 I3.3 A12)') 'radial_densities/proc_', my_rank, '_rho_of_T.nc' write(diagnostics_file, '(A17 I4.4 A22)') 'diagnostics/proc_', my_rank, & 'energy_diagnostics.dat' ! Write energy diagnostics call diagnostics_writer(diagnostics_file, temperature, & energies_of_T, C_of_T, acceptance_of_T) ! Write the radial densities to file call ncdf_radial_density_writer(radial_file, rho_of_T, & shells, temperature, energies_of_T, setup) ! Average results across the simulation call comms_reduce_results(setup) if (my_rank .eq. 0) then ! Write energy diagnostics call diagnostics_writer('diagnostics/av_energy_diagnostics.dat', temperature, & av_energies_of_T, av_C_of_T, av_acceptance_of_T) !Write the radial densities to file call ncdf_radial_density_writer('radial_densities/av_radial_density.nc', av_rho_of_T, & shells, temperature, av_energies_of_T, setup) end if if(my_rank == 0) then write(6,'(25("-"),x,"Simulation Complete!",x,25("-"))') end if end subroutine metropolis_simulated_annealing !--------------------------------------------------------------------! ! Runs Metropolis with Kawasaki dynamics. Simulates annealing down ! ! to a target temperature then draws samples N steps apart, where N ! ! is chosen by the user. ! ! ! ! C. D. Woodgate, Warwick 2023 ! !--------------------------------------------------------------------! subroutine metropolis_decorrelated_samples(setup, my_rank) ! Rank of this processor integer, intent(in) :: my_rank ! Arrays for storing data type(run_params) :: setup ! Integers used in calculations integer :: i,j, div_steps, accept, n_save ! Temperature and temperature steps real(real64) :: beta, temp, sim_temp, current_energy, acceptance ! Name of xyz file character(len=42) :: xyz_file ! Set up the lattice call initial_setup(setup, config) call lattice_shells(setup, shells, config) n_save=floor(real(setup%mc_steps)/real(setup%sample_steps)) div_steps = setup%mc_steps/1000 ! Are we swapping neighbours or on the whole lattice? if (setup%nbr_swap) then setup%mc_step => monte_carlo_step_nbr else setup%mc_step => monte_carlo_step_lattice end if if(my_rank == 0) then write(6,'(/,72("-"),/)') write(6,'(24("-"),x,"Commencing Simulation!",x,24("-"),/)') end if !---------------------------------------------------! ! Burn-in at each temperature (simulated annealing) ! !---------------------------------------------------! do j=1, setup%T_steps ! Work out the temperature and corresponding beta temp = setup%T + real(j-1, real64)*setup%delta_T sim_temp = temp*k_b_in_Ry beta = 1.0_real64/sim_temp ! Burn in if (setup%burn_in) then acceptance = 0.0_real64 do i=1, setup%burn_in_steps ! Make one MC move accept = setup%mc_step(config, beta) acceptance = acceptance + accept end do if(my_rank == 0) then write(6,'(a,f7.2,a)',advance='yes') & " Burn-in complete at temperature ", temp, " on process 0." write(6,'(a,i7,a)',advance='yes') & " Accepted ", int(acceptance), " Monte Carlo moves at this temperature," write(6,'(a,f7.2,a,/)',advance='yes') & " Corresponding to an acceptance rate of ", & 100.0*acceptance/float(setup%burn_in_steps), " %" end if end if end do ! Loop over temperature !--------------------! ! Target Temperature ! !--------------------! acceptance=0 do i=1, setup%mc_steps ! Make one MC move accept = setup%mc_step(config, beta) acceptance = acceptance + accept ! Draw samples if (mod(i, setup%sample_steps) .eq. 0) then ! Get the energy of this configuration current_energy = setup%full_energy(config) write(xyz_file, '(A11 I3.3 A8 I4.4 A6 I4.4 F2.1 A4)') & 'grids/proc_', my_rank, '_config_', & int(i/setup%sample_steps), '_at_T_', int(temp), & temp-int(temp),'.xyz' ! Write xyz file call xyz_writer(xyz_file, config, setup) if (my_rank == 0) then write(6,'(a,i7,a,/)',advance='yes') & " Accepted an additional ", int(acceptance), " Monte Carlo moves before sample." end if acceptance=0 end if end do if(my_rank == 0) then write(6,'(25("-"),x,"Simulation Complete!",x,25("-"))') end if end subroutine metropolis_decorrelated_samples !--------------------------------------------------------------------! ! Runs one MC step assuming pairs swapped across entire lattice ! ! ! ! C. D. Woodgate, Warwick 2023 ! !--------------------------------------------------------------------! function monte_carlo_step_lattice(setup, config, beta) result(accept) !integer(int16), allocatable, dimension(:,:,:,:) :: config integer(int16), dimension(:,:,:,:) :: config class(run_params), intent(in) :: setup integer :: accept integer, dimension(4) :: rdm1, rdm2 real(real64) , intent(in) :: beta real(real64) :: e_unswapped, e_swapped, delta_e integer(int16) :: site1, site2 ! Generate random numbers rdm1 = setup%rdm_site() rdm2 = setup%rdm_site() ! Get what is on those sites site1 = config(rdm1(1), rdm1(2), rdm1(3), rdm1(4)) site2 = config(rdm2(1), rdm2(2), rdm2(3), rdm2(4)) ! Don't do anything if same species if (site1 == site2) then accept = 0 return end if e_unswapped = pair_energy(setup, config, rdm1, rdm2) call pair_swap(config, rdm1, rdm2) e_swapped = pair_energy(setup, config, rdm1, rdm2) delta_e = e_swapped - e_unswapped ! MC swap if(delta_e .lt. 0.0_real64) then accept = 1 return else if (genrand() .lt. exp(-beta*delta_E)) then accept = 1 return else accept = 0 call pair_swap(config, rdm1, rdm2) end if end function monte_carlo_step_lattice !--------------------------------------------------------------------! ! Runs one MC step assuming only neighbours can be swapped ! ! ! ! C. D. Woodgate, Warwick 2023 ! !--------------------------------------------------------------------! function monte_carlo_step_nbr(setup, config, beta) result(accept) !integer(int16), allocatable, dimension(:,:,:,:) :: config integer(int16), dimension(:,:,:,:) :: config class(run_params), intent(in) :: setup integer :: accept integer, dimension(4) :: rdm1, rdm2 real(real64) , intent(in) :: beta real(real64) :: e_unswapped, e_swapped, delta_e integer(int16) :: site1, site2 ! Generate random numbers rdm1 = setup%rdm_site() rdm2 = setup%rdm_nbr(rdm1) ! Get what is on those sites site1 = config(rdm1(1), rdm1(2), rdm1(3), rdm1(4)) site2 = config(rdm2(1), rdm2(2), rdm2(3), rdm2(4)) ! Don't do anything if same species if (site1 == site2) then accept=0 return end if e_unswapped = pair_energy(setup, config, rdm1, rdm2) call pair_swap(config, rdm1, rdm2) e_swapped = pair_energy(setup, config, rdm1, rdm2) delta_e = e_swapped - e_unswapped ! MC swap if(delta_e .lt. 0.0_real64) then accept = 1 return else if (genrand() .lt. exp(-beta*delta_E)) then accept = 1 return else accept = 0 call pair_swap(config, rdm1, rdm2) end if end function monte_carlo_step_nbr end module metropolis
package models; public class Segurado extends Veiculo implements ISeguroService{ private double seguro; public Segurado(double seguro){ this.seguro = seguro; } /** * Retorna o resultado do valor a pagar para o estacionamento através do cálculo * super.doTotal() - doDesconto(). * @return */ @Override public double doTotal(){ double total = super.doTotal() - doDesconto(); return total; } @Override public String doViewCupom(){ String mensagem = super.doViewCupom() + "\nDesconto do seguro: " + doDesconto() + "\nValor total a pagar: " + doTotal(); return mensagem; } /** * Retorna o valor do desconto para veículos segurados através do cálculo * super.doTotal() * seguro / 100 * @return double */ @Override public double doDesconto() { return super.doTotal() * this.seguro /100; } public double getSeguro() { return seguro; } public void setSeguro(double seguro) { this.seguro = seguro; } }
import "./App.css"; import { useSelector, useDispatch } from "react-redux"; import { renderGame } from "./redux/slices/gameSlice"; import Grid from "./components/Grid"; import "./App.css"; import Winner from "./components/Winner"; function App() { const { winner, started } = useSelector((state) => state.game); const dispatch = useDispatch(); const startGameHandler = () => { dispatch(renderGame()); }; return ( <div className="App"> {!started && !winner && ( <button className="reset-btn" onClick={startGameHandler}> Start Game! </button> )} {started && <Grid />} {started && winner && <Winner />} </div> ); } export default App;
const Category = require('../models/category'); const Instrument = require('../models/instrument'); const asyncHandler = require('express-async-handler'); const { body, validationResult } = require('express-validator'); exports.index = asyncHandler(async (req, res, next) => { const allCategories = await Category.find().exec(); res.render('index', { title: 'Inventory application', category_list: allCategories, }); }); exports.category_create_get = asyncHandler(async (req, res, next) => { res.render('category_form', { title: 'Create new category' }); }); exports.category_create_post = [ body('name', 'Category name must be at least 2 characters') .trim() .isLength({ min: 2 }) .escape(), body('description', 'Description must be minimum 5 characters long') .trim() .isLength({ min: 5 }) .escape(), asyncHandler(async (req, res, next) => { const errors = validationResult(req); const category = new Category({ name: req.body.name, description: req.body.description }); if (!errors.isEmpty()) { res.render('category_form', { title: 'Create new category', category: category, errors: errors.array(), }); return; } else { const categoryExists = await Category.findOne({ name: req.body.name }) .collation({ locale: 'en', strength: 2 }) .exec(); if (categoryExists) { res.redirect(categoryExists.url); } else { await category.save(); res.redirect(category.url); } } }), ]; exports.category_update_get = asyncHandler(async (req, res, next) => { const category = await Category.findById(req.params.id).exec(); if (category === null) { const err = new Error('Category not found'); err.status = 404; return next(err); } res.render('category_form', { title: 'Update ' + category.name, category: category, }); }); exports.category_update_post = [ body('name', 'Category name must be at least 2 characters') .trim() .isLength({ min: 2 }) .escape(), body('description', 'Description must be minimum 5 characters long') .trim() .isLength({ min: 5 }) .escape(), asyncHandler(async (req, res, next) => { const errors = validationResult(req); const category = new Category({ name: req.body.name, description: req.body.description, _id: req.params.id }); if (!errors.isEmpty()) { res.render('category_form', { title: 'Update' + category.name, category: category, errors: errors.array(), }); return; } else { await Category.findByIdAndUpdate(req.params.id, category); res.redirect(category.url); } }), ]; exports.category_delete_get = asyncHandler(async (req, res, next) => { const [category, allInstruments] = await Promise.all([ Category.findById(req.params.id).exec(), Instrument.find({ category: req.params.id }, "name").exec() ]); if (category === null) { req.redirect('/catalog'); } res.render('category_delete', { title: 'Delete ' + category.name, category: category, instruments : allInstruments, }); }); exports.category_delete_post = asyncHandler(async (req, res, next) => { const [category, allInstruments] = await Promise.all([ Category.findById(req.params.id).exec(), Instrument.find({ category: req.params.id }, "name").exec() ]); if (allInstruments.length > 0) { res.render('category_delete', { title: 'Delete ' + category.name, category: category, instruments : allInstruments, }); return; } else { await Category.findByIdAndRemove(req.params.id); res.redirect('/catalog'); } });
<!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- https://source.unsplash.com/random/1400x900/?nature --> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <title>Saroj Blog</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Saroj Blogger </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" > What's New </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="https://www.youtube.com/channel/UCnxD0alwvjCoKfLmc-yX27w">Watch My Video</a></li> <li><a class="dropdown-item" href="https://www.facebook.com/saraj.seer.5">Find me on social Media</a></li> <li><hr class="dropdown-divider" /></li> <li> <a class="dropdown-item" href="#">Ride With me </a> </li> <li> <a class="dropdown-item" href="#">Support</a> </li> </ul> <li class="nav-item"> <a class="nav-link" href="contactus.html">Contact Us</a> </li> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" /> <button class="btn btn-outline-light" type="submit"> Search </button> </div> </form> <div class="mx-2"> <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#loginModal"> Login</button> <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#signupModal">Sign Up</button> </div> </div> </nav> <!-- Login Modal --> <div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="loginModalLabel">Login</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Sign up Modal --> <div class="modal fade" id="signupModal" tabindex="-1" aria-labelledby="signupModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="signupModalLabel">SignUp</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="mb-3"> <label for="exampleInputPassword2" class="form-label"> Confirm Password</label> <input type="password" class="form-control" id="exampleInputPassword2"> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <button type="submit" class="btn btn-primary">Sign Up</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> </div> </div> </div> </div> <div id="carouselExampleCaptions" class="carousel slide carousel-fade" data-bs-ride="carousel" > <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://source.unsplash.com/random/1000x400/?motorbike" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>My World </h2> <p>Ride Safe,Travel and explore.</p> <button type="button" class="btn btn-primary">Find Me</button> <button type="button" class="btn btn-danger">Watch Me</button> <button type="button" class="btn btn-success">Support Me</button> </div> </div> <div class="carousel-item"> <img src="https://source.unsplash.com/random/1000x400/?nepal" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>My World </h2> <p>Ride Safe,Travel and explore.</p> <button type="button" class="btn btn-primary">Find Me</button> <button type="button" class="btn btn-danger">Watch Me</button> <button type="button" class="btn btn-success">Support Me</button> </div> </div> <div class="carousel-item"> <img src="https://source.unsplash.com/random/1000x400/?nature" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>My World </h2> <p>Ride Safe,Travel and explore.</p> <button type="button" class="btn btn-primary">Find Me</button> <button type="button" class="btn btn-danger">Watch Me</button> <button type="button" class="btn btn-success">Support Me</button> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <div class="container my-4"> <div class="row mb-2"> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">Way to Dharna</strong> <h3 class="mb-0">Featured post</h3> <div class="mb-1 text-muted">Nov 12</div> <p class="card-text mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p> <a href="#" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img src="https://source.unsplash.com/random/200x250/?dharan,nature" class="bd-placeholder-img" width="200" height="250" alt=""> </div> </div> </div> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Way to Pokhara</strong> <h3 class="mb-0">Post title</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p> <a href="#" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img src="https://source.unsplash.com/random/200x250/?pokhara,nature" class="bd-placeholder-img" width="200" height="250" alt=""> </div> </div> </div> </div> <div class="row mb-2"> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">Way to Mustang</strong> <h3 class="mb-0">Featured post</h3> <div class="mb-1 text-muted">Nov 12</div> <p class="card-text mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p> <a href="#" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img src="https://source.unsplash.com/random/200x250/?mustang district,nature" class="bd-placeholder-img" width="200" height="250" alt=""> </div> </div> </div> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Way to Dholpa</strong> <h3 class="mb-0">Post title</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p> <a href="#" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img src="https://source.unsplash.com/random/200x250/?dolpa,nature" class="bd-placeholder-img" width="200" height="250" alt=""> </div> </div> </div> </div> </div> <footer class="container text-aling-center"> <a href="https://www.facebook.com/saraj.seer.5" style="padding: .5rem;"> <ion-icon name="logo-facebook" size="large" ></ion-icon></a> <a href="https://www.youtube.com/channel/UCnxD0alwvjCoKfLmc-yX27w" style="padding: .5rem;"><ion-icon name="logo-youtube" size="large" style="color: red;" ></ion-icon></a> <a href="https://www.instagram.com/rs_chettri/" style="padding: .5rem;"> <ion-icon name="logo-instagram" size="large" style="color: #3f729b"></ion-icon></a> <p class="float-end"><a href="index.html">Back to top</a></p> <p>© 2017–2021 Sajor Blogger Inc. · <a href="#">Privacy</a> · <a href="#">Terms</a></p> </footer> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" ></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> --> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> </body> </html>
import React from "react"; import { BrowserRouter as Router, Routes, Route, Navigate, } from "react-router-dom"; import Home from "./components/Home"; import Login from "./components/Login"; import Signup from "./components/Signup"; import OrderParts from "./components/OrderParts"; import Service from "./components/Service"; import AboutUs from "./components/AboutUs"; import PartPage from "./components/Parts/PartPage"; import Billing from "./components/Billing"; import GenerateBill from "./components/GenerateBill"; import Bill from "./components/Bill"; import Users from "./admin/Users"; import ViewPart from "./admin/ViewPart"; import AddPart from "./admin/AddPart"; import { AuthState } from "./context/AuthContext"; import axios from "axios"; import Warehouse from "./warehouse/Warehouse"; import BillPage from "./warehouse/BillPage"; import AptStatus from "./components/AptStatus"; import GenerateApt from "./components/GenerateApt"; import Appointment from "./service/Appointment"; import AppointmentUpdate from "./service/AppointmentUpdate"; function App() { axios.defaults.baseURL = "https://forza-customs-api.vercel.app/api"; const { user } = AuthState(); return ( <Router> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={!user ? <Login /> : <Navigate to="/" />} /> <Route path="/signup" element={!user ? <Signup /> : <Navigate to="/" />} /> <Route path="/parts" element={user ? <OrderParts /> : <Navigate to="/login" />} /> <Route path="/service" element={user ? <Service /> : <Navigate to="/login" />} /> <Route path="/about" element={user ? <AboutUs /> : <Navigate to="/login" />} /> <Route path="/partPage" element={user ? <PartPage /> : <Navigate to="/login" />} /> {/* Admin Routes Starts */} <Route path="/addParts" element={ user && user.admin === true ? <AddPart /> : <Navigate to="/login" /> } /> <Route path="/viewParts" element={ user && user.admin === true ? ( <ViewPart /> ) : ( <Navigate to="/login" /> ) } /> <Route path="/users" element={ user && user.admin === true ? <Users /> : <Navigate to="/login" /> } /> {/* Admin Routes Ends */} <Route path="/billing" element={user ? <Billing /> : <Navigate to="/login" />} /> <Route path="/generateBill" element={user ? <GenerateBill /> : <Navigate to="/login" />} /> <Route path="/bill" element={user ? <Bill /> : <Navigate to="/login" />} /> {/* Warehouse Route starts */} <Route path="/warehouse" element={ user && user.warehouse === true ? ( <Warehouse /> ) : ( <Navigate to="/login" /> ) } /> {/* Warehouse Route Ends */} <Route path="/bill-page" element={user ? <BillPage /> : <Navigate to="/login" />} /> <Route path="/aptStatus" element={user ? <AptStatus /> : <Navigate to="/login" />} /> <Route path="/generateApt" element={user ? <GenerateApt /> : <Navigate to="/login" />} /> {/* Service Route Starts */} <Route path="/appointment" element={ user && user.service === true ? ( <Appointment /> ) : ( <Navigate to="/login" /> ) } /> <Route path="/updateApt" element={ user && user.service === true ? ( <AppointmentUpdate /> ) : ( <Navigate to="/login" /> ) } /> {/* Service Route Ends */} </Routes> </Router> ); } export default App;
### 服务器内部转发: - 1.`req.getRequestDispatcher("...").forward(req,resp);` - - 一次请求响应的过程,对于客户端而言,内部经过了多少次转发,客户端是不知道的 - 地址栏url没有变化 - 2.客户端重定向:`resp.sendRedirect("...");` - - 地址栏url有变化 - 在浏览器的network也可以看到原来访问的页面上有302状态码(转发) - ![image-20221124222550097](./images/image-20221124222550097.png) `req.getRequestDispatcher("...").forward(req,resp);`是服务器内部转发,客户端向它发送,改servlet转发给其他的servlet 重定向是服务器立即给客户端响应 --- code: `demo03`: ```java package com.guigu; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //演示转发 @WebServlet("/demo03") public class demo03 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("demo03"); //服务器内部转发 //req.getRequestDispatcher("demo04").forward(req, resp); //重定向 resp.sendRedirect("demo04"); } } ``` `demo04`: ```java package com.guigu; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/demo04") public class demo04 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("demo04接受到了重定向"); } } ```
package de.rieckpil.ppp; import java.math.BigDecimal; import java.util.Map; import de.rieckpil.ppp.db.postgresql.tables.records.PppRecord; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @Component public class OpenExchangeRatesClient { private final WebClient webClient; private final ApplicationProperties applicationProperties; public OpenExchangeRatesClient( WebClient openExchangeRatesWebClient, ApplicationProperties applicationProperties) { this.webClient = openExchangeRatesWebClient; this.applicationProperties = applicationProperties; } public Mono<ExchangeRateResult> fetchExchangeRates(PppRecord pppRecord) { return this.webClient .get() .uri( "/api/latest.json?app_id={appId}", this.applicationProperties.getOpenExchangeRatesApiId()) .retrieve() .bodyToMono(ExchangeRatesResponse.class) .map( exchangeRates -> new ExchangeRateResult( pppRecord, BigDecimal.valueOf( exchangeRates.rates().getOrDefault(pppRecord.getCurrencyCode(), 1.0)))); } public record ExchangeRatesResponse(Map<String, Double> rates) {} public record ExchangeRateResult(PppRecord pppRecord, BigDecimal exchangeRate) {} }
<template> <main class="post-page"> <section v-if="post" class="container mx-auto p-4"> <img :src="CreateURL(post.image, 1280, 300)" class="w-full mb-8"> <button @click="$router.back()" class="flex items-center text-lg text-green-500 hover:text-green-600 duration-300 mb-4"> <span class="material-icons text-lg mr-1">keyboard_double_arrow_left</span> Back </button> <h1 class="text-3xl md:text-5xl mb-8">{{ post.title }}</h1> <p class="text-gray-500 italic mb-8">{{ post.excerpt }}</p> <p v-html="TextToHTML(post.content)" class="text-lg mb-8"></p> <div class="flex items-center mb-4" v-if="post.author"> <img :src="CreateURL(post.author.avatar, 300, 300)" class="inline-block rounded-full w-10 h-10 mr-4" /> <h1 class="text-gray-500"> {{ post.author.full_name }} </h1> </div> </section> </main> </template> <script> import { onMounted, ref } from 'vue' import { useRoute } from 'vue-router' import sanity from '../../client' import { CreateURL, TextToHTML } from '../../utils' export default { setup () { const route = useRoute() const id = ref(route.params.id) const post = ref(null) onMounted(() => { const query = '*[_type == "post" && _id == $id][0] { ..., author-> }' const params = { id: id.value } sanity.fetch(query, params).then(data => { post.value = data }) }) return { post, CreateURL, TextToHTML } } } </script>
import{useForm} from 'react-hook-form'; import { useAuth } from '../context/AuthContext'; import {useNavigate,Link} from 'react-router-dom' import { useEffect } from 'react'; const RegisterPage = () => { const {register, handleSubmit,formState:{errors}}=useForm(); const {singup,isAuthenticated,errors:registerError}=useAuth(); const navigate=useNavigate() useEffect(()=>{ if(isAuthenticated) navigate('/login'); },[isAuthenticated]); const onSubmit=handleSubmit((values)=>{ console.log(values) singup(values); }) return ( <div className='flex h-[calc(100vh-100px)] items-center justify-center '> <div className='bg-zinc-600 max-w-md p-10 rounded-md'> { registerError.map((error,i)=>( <div key={i} className='bg-red-500 p-2 text-white text-center'> {error} </div> )) } <h1 className='text-3xl font-bold my-2 text-white'>Register</h1> <form onSubmit={onSubmit}> <input type="text" {...register('name',{required:true})} className='w-full bg-zinc-700 text-white px-4 p-y2 rounded-md my-2' placeholder='name'/> { errors.name && ( <p className='text-red-500 w-full'> name is required </p> ) } <input type="text" {...register('lastname',{required:true})} className='w-full bg-zinc-700 text-white px-4 p-y2 rounded-md my-2' placeholder='lastname'/> { errors.lastname && ( <p className='text-red-500 w-full'> lastname is required </p> ) } <input type="email" {...register('email',{required:true})} className='w-full bg-zinc-700 text-white px-4 p-y2 rounded-md my-2' placeholder='email'/> { errors.email && ( <p className='text-red-500 w-full'> email is required </p> ) } <input type="password" {...register('password',{required:true})} className='w-full bg-zinc-700 text-white px-4 p-y2 rounded-md my-2' placeholder='password'/> { errors.password && ( <p className='text-red-500'> password is required </p> ) } <button type="submit" className='bg-yellow-600 text-white px-4 py-2 rounded-md my-2 hover:bg-yellow-500'> Register </button> </form> <p className='text-white'>Already have account? <Link to='/login' className='flex gap-x-2 text-blue-400'>Sign up </Link></p> </div> </div> ) } export default RegisterPage
"use client" import { Search } from 'lucide-react' import { FormEvent, useState } from "react"; import { receitas } from "./data/recipe"; import { LogoChef } from './assets/logoChef'; import Link from 'next/link'; import { EmptySearch } from './utils/emptysearch'; import { SearchBarr } from './components/searchbarr'; export default function Home() { const [inputSearch, setInputSearch] = useState("") const [isNoResults, setIsNoResults] = useState(false) const [arrReceitas, setArrReceitas] = useState(receitas) function handleSubmit(event: FormEvent) { event?.preventDefault() setArrReceitas(receitas) setArrReceitas(value => value.filter(value => { return ( value.titulo.toUpperCase().includes(inputSearch.toUpperCase()) || value.instrucoes.join(' ').toUpperCase().includes(inputSearch.toUpperCase()) || value.ingredientes.join(' ').toUpperCase().includes(inputSearch.toUpperCase()) ) })) console.log("here") const isEmpty = arrReceitas.length == 0 ? true : false setIsNoResults(isEmpty) setInputSearch('') } return ( <div className="max-w-screen w-screen max-h-screen h-screen grid grid-flow-row grid-rows-3 md:grid-flow-col md:grid-cols-2 md:grid-rows-1"> <img src="/background-logo.jpg" alt="Background Plate Logo" className="w-full h-full" /> <div className="flex flex-col bg-slate-100 pt-4 px-2 md:pt-20 md:px-10 items-center"> <div className='flex items-center gap-3'> <LogoChef width={80} height={80} /> <h1 className="text-5xl md:text-7xl text-red-700 font-bold"> Prato do Dia </h1> </div> <SearchBarr inputSearch={inputSearch} handleSubmit={handleSubmit} setInputSearch={setInputSearch} onRedirectPage={false} /> <div className='flex w-full justify-end py-2'> <p>Quer sugerir uma receita? <a href="#" className='text-red-500 underline hover:text-red-700'>Clique Aqui</a></p> </div> <ul className="no-scrollbar flex items-start flex-col max-h-full h-full w-full m-2 overflow-y-scroll border-2 border-slate-300 rounded-md gap-4"> { !isNoResults ? (arrReceitas.map((receita) => { return ( <Link href={ { pathname: '/recipe', query: { id: receita.id, image: receita.image, titulo: receita.titulo, categoria: receita.categoria, dificuldade: receita.dificuldade, tempoPreparo: receita.tempoPreparo, ingredientes: receita.ingredientes, instrucoes: receita.instrucoes } } } key={receita.id} > <li className="item-recipe flex items-center h-full px-2"> <img src={receita.image} alt={receita.titulo} className="min-w-24 h-24 rounded-full" /> <div className="mx-4 py-2 border-b-2 border-red-800"> <h3 className="text-2xl overflow-hidden pb-1"> {receita.titulo} </h3> <p className="text-sm tracking-tight text-slate-600 text-justify max-h-24 overflow-hidden"> {receita.instrucoes.join(' ')} </p> </div> </li> </Link> ) })) : <EmptySearch /> } </ul> </div> </div> ); }
Vue 3を学ぶ上で、さまざまな機能を追加して実践的な経験を積むことは非常に有益です。以下に、初心者から中級者レベルのVue開発者が取り組むのに適したプロジェクトのアイデアをいくつか提案します。 ### 1. ToDoリストの拡張 - **状態管理の追加**: PiniaやVuexを使用して、ToDoリストの状態管理を実装します。 - **データの永続化**: Local Storageを使用して、ToDoアイテムの状態をブラウザに保存し、リロード後も維持します。 ### 2. ブログまたはニュースフィード - **API統合**: JSONPlaceholderや他の公開APIを使用してデータを取得し、ブログポストやニュース記事を表示します。 - **無限スクロール**: スクロールによるページネーションを実装し、ユーザーがスクロールダウンすると自動的に新しいコンテンツをロードします。 ### 3. シンプルなEコマースサイト - **製品リスト**: Vueコンポーネントを使用して製品を表示し、フィルタリングやソートの機能を追加します。 - **カート機能**: ユーザーが製品をカートに追加し、カート内のアイテムを管理できるようにします。 ### 4. チャットアプリケーション - **リアルタイム通信**: WebSocketやFirebaseを使用して、リアルタイムでのメッセージング機能を実装します。 - **ユーザー認証**: Firebase Authや他の認証サービスを使用して、ユーザー認証機能を追加します。 ### 5. ポートフォリオサイト - **パーソナライズ**: Vue Routerを使用して、異なるセクション(例:ホーム、プロジェクト、コンタクト)を持つシングルページアプリケーションを作成します。 - **アニメーション**: Vueのトランジションとアニメーション機能を利用して、動的なユーザーインターフェースを作成します。 ### 6. ダッシュボードアプリケーション - **データ可視化**: Chart.jsやD3.jsなどのライブラリを統合して、データをグラフやチャートとして表示します。 - **動的ウィジェット**: ユーザーがダッシュボード上でウィジェットを追加、削除、または並べ替えできるようにします。 これらのプロジェクトを通じて、Vue 3の基本的なコンセプト(リアクティブなデータバインディング、コンポーネントシステム、ディレクティブなど)に加えて、Vue Router、Vuex/Pinia、コンポーネントスロット、テレポートなどの高度な機能にも慣れることができます。また、実際のプロジェクトに取り組むことで、問題解決能力やデバッグ技術も磨かれます。
package org.example.Paneller.Hoca.HocaMesajlar; import org.example.Kisiler.Hoca; import org.example.Kisiler.Kullanici; import org.example.Kisiler.Mesaj; import org.example.Kisiler.Ogrenci; import org.example.Paneller.Hoca.HocaPaneli; import org.example.Veritabani.Sorgular; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class HocaGelenMesajlar extends JFrame{ private JPanel panel1=new JPanel(); ArrayList<Mesaj> gelenMesajlar=new ArrayList<>(); ArrayList<Kullanici> kullanicilar=new ArrayList<>(); ArrayList<Ogrenci> ogrenciler=new ArrayList<>(); ArrayList<JLabel> metinler=new ArrayList<>(); ArrayList<JButton> butonlar=new ArrayList<>(); public HocaGelenMesajlar(Hoca hoca){ Sorgular sorgular=new Sorgular(); gelenMesajlar=sorgular.hocayaGelenMesajlar(hoca.getId()); JButton geriButton=new JButton("Geri"); JLabel bosluk1=new JLabel(""); JLabel bosluk2=new JLabel(""); JLabel bosluk3=new JLabel(""); //veritabanindaki tüm mesajlar kategorilerinin gonderenId ye göre boolean durum=false; for(Mesaj mesaj:gelenMesajlar){ durum=false; for (Kullanici k:kullanicilar){ if(k.getId().equals(mesaj.getGonderen_id())){ durum=true; break; } } if(durum==false){ Kullanici kullanici=new Kullanici(); kullanici.setId(mesaj.getGonderen_id()); kullanicilar.add(kullanici); } } //mesaj atan kullanıcların detaylı bilgisi alinir for (Kullanici k:kullanicilar){ ogrenciler.add(sorgular.ogrenciGetir(k.getId())); } panel1.setLayout(new GridLayout(ogrenciler.size()+2,2)); panel1.add(geriButton); panel1.add(bosluk1); panel1.add(bosluk2); panel1.add(bosluk3); geriButton.setBackground(Color.lightGray); for(Ogrenci ogrenci:ogrenciler){ JLabel label=new JLabel(ogrenci.getOgrenciNo()+" "+ogrenci.getAd()+" "+ogrenci.getSoyad()); JButton button=new JButton("Mesaj Oku"); button.setBackground(Color.lightGray); metinler.add(label); butonlar.add(button); panel1.add(label); panel1.add(button); } for (int i = 0; i < butonlar.size(); i++) { int finalI = i; butonlar.get(i).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { HocaGelenMesajlarOku hocaGelenMesajlarOku=new HocaGelenMesajlarOku(hoca, ogrenciler.get(finalI).getId()); hocaGelenMesajlarOku.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); hocaGelenMesajlarOku.setVisible(true); } }); } }); } geriButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { HocaMesajlarPanel hocaMesajlarPanel=new HocaMesajlarPanel(hoca); hocaMesajlarPanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); hocaMesajlarPanel.setVisible(true); } }); } }); add(panel1); setSize(800, 600); setTitle("Gelen Mesajlar"); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> let obj={ name:'dingding', age:23, id:3000 } // json第二个参数传入数组 let json1=JSON.stringify(obj,['name','age']); console.log(json1);//只有name和age,没有id // stringify第二个参数函数 function filter(keys,val){ switch (keys) { case 'name': return val+'过滤啦'; case 'id': return undefined;//利用json特性忽略这个值 default: return val; } } // 第三个参数控制缩进空格数量,可以用任意字符替代 let json2=JSON.stringify(obj,filter,'--'); console.log(json2); </script> </body> </html>
import { MutableRefObject, useEffect, useRef } from "react"; import { useSelector } from "react-redux"; import { selectPage } from "store/pagination/selectors/selectPage/selectPage"; export interface UseInfiniteScrollOptions { callback?: () => void; triggerRef: MutableRefObject<HTMLElement>; wrapperRef: MutableRefObject<HTMLElement>; } export function useInfiniteScroll({ callback, triggerRef, wrapperRef }: UseInfiniteScrollOptions) { useEffect(() => { let observer: IntersectionObserver | null = null; // const scrollElement = wrapperRef.current; // document.querySelector("html"); const triggerElement = triggerRef.current; // triggerRef.current; if (callback && triggerElement) { /* const options = { root: null, // scrollElement, // элемент со скролом root: document.querySelector("#scrollArea"), rootMargin: "20px", threshold: 1.0, }; */ observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { callback(); } }, {}); observer.observe(triggerElement); } return () => { if (observer && triggerElement) { // eslint-disable-next-line react-hooks/exhaustive-deps observer.unobserve(triggerElement); } }; }, [callback, triggerRef, wrapperRef]); }
export const relativeTime = (date: string): string => { const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }) const pastDate = new Date(date) const userTimezoneOffset = pastDate.getTimezoneOffset() * 60000 const UTCTimeRightNow = new Date(pastDate.getTime() - userTimezoneOffset) const currentDateUTC = new Date( Date.UTC( new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate(), new Date().getUTCHours(), new Date().getUTCMinutes(), new Date().getUTCSeconds() ) ) const timeDifferenceInSeconds = Math.floor( (currentDateUTC.getTime() - UTCTimeRightNow.getTime()) / 1000 ) if (timeDifferenceInSeconds < 60) { return rtf.format(Math.round(-timeDifferenceInSeconds), 'second') } else if (timeDifferenceInSeconds < 3600) { return rtf.format(Math.round(-timeDifferenceInSeconds / 60), 'minute') } else if (timeDifferenceInSeconds < 86400) { return rtf.format(Math.round(-timeDifferenceInSeconds / 3600), 'hour') } else if (timeDifferenceInSeconds < 604800) { return rtf.format(Math.round(-timeDifferenceInSeconds / 86400), 'day') } else if (timeDifferenceInSeconds < 2419200) { return rtf.format(Math.round(-timeDifferenceInSeconds / 604800), 'week') } else { return rtf.format(Math.round(-timeDifferenceInSeconds / 2419200), 'month') } }
import { Avatar, Card, Select, Space } from "antd"; import React from "react"; import { useRecoilState } from "recoil"; import { loadingAtom } from "../../atoms/atom"; import RenderIf from "../../utils/RenderIf"; import { handleLoad, handleUserSelection } from "./UserPermissionAnalysisView.util"; import UserPermissionView from "./UserPermissionView"; interface IUserPermissionAnalysisViewProps { children?: React.ReactNode; } const UserPermissionAnalysisView: React.FC<IUserPermissionAnalysisViewProps> = (props) => { const [, setLoading] = useRecoilState(loadingAtom); const [userOptions, setUserOptions] = React.useState([]); const [selectedUser, setSelectedUser] = React.useState<any>({}); const [permissionMap, setPermissionMap] = React.useState({}); const [profileMap, setProfileMap] = React.useState({}); const [permissionList, setPermissionList] = React.useState<any>({}); const [fetchCompleted, setFetchCompleted] = React.useState(false); React.useEffect(() => { const onload = async () => { let response = await handleLoad(); setUserOptions(response); }; onload(); }, []); const onUserChange = async (option: any) => { setFetchCompleted(false); setLoading(true); setSelectedUser(option); let response = await handleUserSelection(option); setPermissionMap(response.permissionMap); setPermissionList(response.permissionList); setProfileMap(response.profileMap); setLoading(false); setFetchCompleted(true); }; return ( <> <Card size="small" title={ <Select placeholder="Select User" style={{ width: 300 }} onChange={(value, valueOption) => { onUserChange(valueOption); }} showSearch options={userOptions} size="small" bordered={false} filterOption={(inputValue, option: any) => { return option?.label.toUpperCase().includes(inputValue.toUpperCase()); }} /> } extra={ <Space> <Avatar src={selectedUser?.FullPhotoUrl} size="small" /> {selectedUser.Username} </Space> } > <RenderIf renderIf={fetchCompleted}> <UserPermissionView permissionList={permissionList} permissionMap={permissionMap} profileMap={profileMap} /> </RenderIf> </Card> </> ); }; export default UserPermissionAnalysisView;
function FFT_NNLS_result = FFT_NNLS(DAS_result, PSF, maxIter) % % This code implements the FFT-NNLS algorithm % % More information about FFT-NNLS can be found in the paper: % Ehrenfried, Klaus and Koop, Lars, % "Comparison of iterative deconvolution algorithms for the mapping of acoustic sources", % AIAA journal, 2007. % % % Inputs: % DAS_result: beamforming map, obtained by DAS % PSF: point spread function (PSF) % maxIter: the maximum allowable iterations % % Outputs: % FFT_NNLS_result: beamforming map, obtained by FFT-NNLS % % Author: Hao Liang % Last modified by: 21/09/08 % % To avoid wraparound effects, zero padding is used DAS_zeropad = real(zeropad(DAS_result)); PSF_zeropad = zeropad(PSF); FFT_NNLS_result_zeropad = zeropad(zeros(size(DAS_result,1))); % Precompute fft of PSF fft_PSF = fft2(PSF_zeropad); n = 0; while n < maxIter n = n + 1; % Calculate the residual vector and gradient [r, grad] = nnls(DAS_zeropad,FFT_NNLS_result_zeropad,fft_PSF); % Compute the vector w w = grad; w(FFT_NNLS_result_zeropad == 0 & w > 0) = 0; % Obtain the auxiliary vector g g = fftshift(ifft2(fft2(w).*fft_PSF)); % Estimate an optimal step factor step = dot(g(:),r(:))/dot(g(:),g(:)); % Update the beamforming map FFT_NNLS_result_zeropad = max(0,FFT_NNLS_result_zeropad - step*w); end % Remove zero padding FFT_NNLS_result = remove_zeropad(FFT_NNLS_result_zeropad); end function Map_zeropad = zeropad(Map) % To avoid wraparound effects, zero padding is used [M,N] = size(Map); Map_zeropad = zeros(M+N); Map_zeropad(int64(M/2)+1:int64(M/2 + M),int64(M/2)+1:int64(M/2 + M)) = Map; end function Map = remove_zeropad(Map_zeropad) % remove zeropadding M = size(Map_zeropad,1)/2; Map = Map_zeropad(int64(M/2)+1:int64(M/2+M),int64(M/2)+1:int64(M/2+M)); end function [r,g] = nnls(b,x,fft_PSF) % Nonnegative least squares objective function % % Input: % b : beamforming map % x: beamforming map after deconvolution % fft_PSF: point spread function (PSF) after Fourier transform % % Output: % r: residual % g: gradient % % Calculate residual r = fftshift(ifft2(fft2(x).*fft_PSF)) - b; % Calculate gradient g = fftshift(ifft2(fft2(r).*fft_PSF)); end
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import Header from './components/Header'; import Footer from './components/Footer'; import DrinkCard from './components/DrinkCard'; import { cocktailsAPIOnLoad } from '../services/APIsOnLoad'; import { categoryCocktailAPI, recipesOfCocktailsByCategory } from '../services/categorysAPI'; import { recipeDrinksOnLoad, recipesFiltered } from '../store/actions'; import '../styles/foods.css'; class Drinks extends Component { constructor() { super(); this.state = { recipesOnLoad: [], categorys: [], filteredCategory: '', }; } async componentDidMount() { await this.requestAPIOnLoad(); } requestAPIOnLoad = async () => { const { saveFilteredRecipes, filterByIngredient } = this.props; const allRecipes = await cocktailsAPIOnLoad(); const categorys = await categoryCocktailAPI(); if (filterByIngredient.length > 0) { this.setState({ recipesOnLoad: filterByIngredient, }); } else { this.setState({ recipesOnLoad: allRecipes, categorys, }); } saveFilteredRecipes(allRecipes); } sendToRecipePage = (recipes) => { const { filteredCategory } = this.state; if (recipes.length === 1 && filteredCategory === '') { return ( <div> <Redirect to={ `/drinks/${recipes[0].idDrink}` } /> </div> ); } } onClickCategory = async (category) => { const { searchDrink, saveFilteredRecipes } = this.props; const { filteredCategory } = this.state; const recipesByCategory = await recipesOfCocktailsByCategory(category); if (filteredCategory === category) { searchDrink(false); this.setState({ filteredCategory: '', }); } else { searchDrink(true); this.setState({ filteredCategory: category, }); saveFilteredRecipes(recipesByCategory); } } render() { const { recipesOnLoad, categorys } = this.state; const { history, search, searchDrink, filteredRecipes } = this.props; return ( <div> <Header history={ history } name="Drinks" hideSearch={ false } drinkPage /> <div className="bg-purple-200 px-5 grid grid-cols-2 flex items-center" > <button className="bg-violet-500 hover:bg-violet-800 rounded flex-col flex items-center w-36 ml-2 active:bg-violet-700 focus:outline-none text-white font-serif focus:ring focus:ring-violet-300 hover:shadow-lg disabled:bg-slate-500" type="button" data-testid="All-category-filter" onClick={ () => searchDrink(false) } > All </button> {categorys.map(({ strCategory }) => ( <button className="bg-violet-500 hover:bg-violet-800 rounded flex-col w-38 flex items-center m-2 active:bg-violet-700 focus:outline-none text-white font-serif focus:ring focus:ring-violet-300 hover:shadow-lg disabled:bg-slate-500" type="button" key={ strCategory } data-testid={ `${strCategory}-category-filter` } onClick={ () => this.onClickCategory(strCategory) } > {strCategory} </button> ))} </div> {search && filteredRecipes ? <DrinkCard allRecipes={ filteredRecipes } /> : <DrinkCard allRecipes={ recipesOnLoad } />} { filteredRecipes && this.sendToRecipePage(filteredRecipes) } <Footer /> </div> ); } } Drinks.propTypes = { history: PropTypes.shape({ push: PropTypes.func, }), recipes: PropTypes.arrayOf, search: PropTypes.bool, filterByIngredient: PropTypes.arrayOf, }.isRequired; const mapStateToProps = (state) => ({ recipes: state.getRecipesReducer.recipes, search: state.getRecipesReducer.searchDrink, filteredRecipes: state.getRecipesReducer.filteredRecipes, filterByIngredient: state.getRecipesReducer.ingredientsFilter, }); const mapDispatchToProps = (dispatch) => ({ searchDrink: (state) => dispatch(recipeDrinksOnLoad(state)), saveFilteredRecipes: (state) => dispatch(recipesFiltered(state)), }); export default connect(mapStateToProps, mapDispatchToProps)(Drinks);
import 'package:flutter/material.dart'; import '../data/product.dart'; class Cart extends ChangeNotifier { Map<Product, int> cartMap = {}; int itemsInCart = 0; void addToCart(Product product) { if (cartMap.containsKey(product)) { cartMap[product] = cartMap[product]! + 1; } else { cartMap[product] = 1; } itemsInCart++; notifyListeners(); } void removeFromCart(Product product) { if (cartMap.containsKey(product)) { if (cartMap[product] == 1) { cartMap.remove(product); } else { cartMap[product] = cartMap[product]! - 1; } } itemsInCart--; notifyListeners(); } void clearCart() { cartMap.clear(); itemsInCart = 0; notifyListeners(); } int get cartCount { return itemsInCart; } bool get isCartEmpty { return cartMap.isEmpty; } double get cartTotal { double total = 0; cartMap.forEach((key, value) { total += key.price * value; }); return total; } Map<Product, int> get cart { return cartMap; } }
// DetailsViewModel.swift // Copyright © DmitrievSY. All rights reserved. import RealmSwift import UIKit protocol DetailsViewModelProtocol { var filmDescription: FilmDescription? { get set } var reloadData: (() -> ())? { get set } var repository: RealmRepository? { get set } } final class DetailsViewModel: DetailsViewModelProtocol { // MARK: - Internal property var repository: RealmRepository? var reloadData: VoidHandler? var filmDescription: FilmDescription? let movieAPIService: MovieAPIServiceProtocol // MARK: - Private property private let filmNumber: Int // MARK: - Init init(filmNumber: Int, repository: RealmRepository) { self.repository = repository self.filmNumber = filmNumber movieAPIService = MovieAPIService() setRequest() } // MARK: - Private method private func setRequest() { requestFromDB() if filmDescription == nil { requestFromNet() } } private func requestFromDB() { let filmDescriptionRealm = repository?.get( type: FilmDescription.self, column: "filmNumber", filmNumber: filmNumber ) var detail: FilmDescription? filmDescriptionRealm?.forEach { details in detail = details } filmDescription = detail } private func requestFromNet() { movieAPIService.parsingDescription(filmNumber: filmNumber, completion: { [weak self] result in switch result { case let .failure(error): print(error.localizedDescription) case let .success(filmDescription): filmDescription.filmNumber = String(self?.filmNumber ?? 0) DispatchQueue.main.async { self?.repository?.save(object: [filmDescription]) self?.requestFromDB() self?.reloadData?() } } }) } }
# frozen_string_literal: true require 'faraday' require 'git' module LCSP # Cache that applies a Language # and download solutions from GitHub # if repository exists. class LCSPCache # @param {String} user # @param {String} lang def initialize(user, lang) @user = user @lang = lang return if exists? ::Git.clone( URI("https://github.com/#{@user}/leetcode-#{@lang.downcase}"), "#{@user}-leetcode-#{@lang.downcase}" ) end # Path of cache for @lang # @return {String} def path "#{::Dir.pwd}/#{@user}-leetcode-#{@lang.downcase}" end private # Check cache existing. # Recommend to run it before # all other operations. # @return {Boolean} def exists? ::File.exist?("#{::Dir.pwd}/#{@user}-leetcode-#{@lang.downcase}") end end end
import { db } from "."; import { Product } from "../models"; import { IProduct } from "../interfaces/products"; export const getProductBySlug = async ( slug: string ): Promise<IProduct | null> => { await db.connect(); const product = await Product.findOne({ slug }).lean(); await db.disconnect(); if (!product) return null; return JSON.parse(JSON.stringify(product)); }; interface ProductSlug { slug: string; } export const getAllPRoductsSlugs = async (): Promise<ProductSlug[]> => { await db.connect(); const slugs = await Product.find().select("slug -_id").lean(); await db.disconnect(); return slugs; }; export const getProductsByTerm = async (term: string): Promise<IProduct[]> => { term = term.toString().toLowerCase(); await db.connect(); const products = await Product.find({ $text: { $search: term }, }) .select("title images price inStock slug -_id") .lean(); await db.disconnect(); return products; }; export const getAllPRoducts = async (): Promise<IProduct[]> => { await db.connect(); const products = await Product.find().lean(); await db.disconnect(); return JSON.parse(JSON.stringify(products)); };
import 'package:flutter/material.dart'; import 'package:flutter_pdf_library/presentation/ui_component/app_colors.dart'; class BookListCard extends StatelessWidget { final String bookName; final String bookAuthorName; final String imageUrl; const BookListCard({ super.key, required this.bookName, required this.bookAuthorName, required this.imageUrl, }); @override Widget build(BuildContext context) { return Card( color: AppColors.orange, shadowColor: AppColors.purpleLight, elevation: 4, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), child: FittedBox( child: Column( children: [ const SizedBox( height: 16, ), Container( height: 140, width: 160, decoration: BoxDecoration( color: AppColors.purpleDark, borderRadius: const BorderRadius.only( topLeft: Radius.circular(8), topRight: Radius.circular(8), ), image: DecorationImage( image: NetworkImage(imageUrl), ), ), ), Padding( padding: const EdgeInsets.all(2.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( bookName, maxLines: 1, style: const TextStyle( overflow: TextOverflow.ellipsis, fontSize: 14, fontWeight: FontWeight.w500, color: Colors.black, ), ), const SizedBox( height: 2, ), Text( bookAuthorName, maxLines: 1, style: const TextStyle( overflow: TextOverflow.ellipsis, fontSize: 14, fontWeight: FontWeight.w500, color: Colors.black, ), ), ], ), ) ], ), ), ); } }
import { Button, Dialog, Input, TLShapePartial, TLUiDialogProps, uniqueId, useEditor, } from "@tldraw/tldraw"; import React, { useMemo, useState } from "react"; import { flexColumnStyle, flexRowStyle, shuffleArray } from "../common"; import { FaAlignRight, FaArrowLeft, FaArrowRight, FaBackspace, FaTrashAlt, } from "react-icons/fa"; import { AssetDesc, useAssets } from "../hooks"; import { assetListStyle } from "../component/AssetList/style.css"; import { AssetItem } from "../component/AssetList/AssetItem"; import { RpgCardStackShape } from "./RpgCardStackShape"; type Props = TLUiDialogProps & { shape: RpgCardStackShape; }; export const CardStackPool = ({ shape, onClose }: Props) => { const editor = useEditor(); const [filter, setFilter] = useState(""); const [pool, setPool] = useState(shape.props._pool); const { imageAssets } = useAssets(editor, ""); const [sel, setSel] = useState<AssetDesc[]>([]); const [poolSel, setPoolSel] = useState<AssetDesc[]>([]); const update = () => { const items = [...pool]; const shapeUpdate: TLShapePartial<RpgCardStackShape> = { id: shape.id, type: "rpg-card-stack", props: { _pool: pool, _current: shuffleArray(items), }, }; editor.updateShapes([shapeUpdate]); onClose(); }; const addAssets = () => { if (sel.length === 0) return; const newPool = [...pool]; sel.forEach((a) => { newPool.push({ ...a, id: uniqueId() }); }); setPool(newPool); setSel([]); }; const addAll = () => { const its = items.map((asset) => ({ ...asset, id: uniqueId() })); setPool((prev) => [...prev, ...its]); }; const removeAssets = () => { if (poolSel.length === 0) return; const ids = poolSel.map((it) => it.id); const newState = pool.filter((it) => !ids.includes(it.id)); setPool(newState); setPoolSel([]); }; const select = (it: AssetDesc) => { if (sel.includes(it)) { setSel(sel.filter((x) => x.filename !== it.filename)); return; } setSel([...sel, it]); }; const selectPool = (it: AssetDesc) => { if (poolSel.includes(it)) { setPoolSel(poolSel.filter((x) => x.id !== it.id)); return; } setPoolSel([...poolSel, it]); }; const items = useMemo(() => { return imageAssets .filter((it) => filter.trim() === "" || it.filename.includes(filter)) .sort((a, b) => a.filename.localeCompare(b.filename)); }, [imageAssets, filter]); return ( <> <Dialog.Header> <Dialog.Title>Card stack pool</Dialog.Title> <Dialog.CloseButton /> </Dialog.Header> <Dialog.Body> <div className={flexRowStyle({})} style={{ alignItems: "start" }}> <div className={flexColumnStyle({})} style={{ minWidth: 250 }}> <div>Assets</div> <div className={assetListStyle}> {items.map((it, idx) => ( <AssetItem key={`${it.filename}-${idx}`} filename={it.filename} onClick={() => select(it)} selected={sel.includes(it)} /> ))} </div> <div className={flexRowStyle({})}> <Input className="tlui-embed-dialog__input" placeholder="Filter..." defaultValue={filter} onValueChange={(value) => setFilter(value)} /> <Button type="icon" onPointerDown={() => setFilter("")}> <FaBackspace size={16} /> </Button> </div> <div className={flexRowStyle({ justify: "center" })}> <Button type="icon" onPointerDown={addAssets} title="Add assets to pool" > <FaArrowRight size={16} /> </Button> <Button type="icon" onPointerDown={addAll} title="Add all"> <FaAlignRight size={16} /> </Button> </div> </div> <div className={flexColumnStyle({})}> <div>Pool ({pool.length})</div> <div className={assetListStyle} style={{ minWidth: 250 }}> {pool.map((it, idx) => ( <AssetItem key={it.id ? it.id : `${it.filename}-${idx}`} filename={it.filename} onClick={() => selectPool(it)} selected={poolSel.includes(it)} /> ))} </div> <div className={flexRowStyle({ justify: "center" })}> <Button type="icon" onPointerDown={removeAssets} title="Remove item" > <FaArrowLeft size={16} /> </Button> <Button type="icon" onPointerDown={() => setPool([])} title="Clear pool" > <FaTrashAlt size={16} /> </Button> </div> </div> </div> </Dialog.Body> <Dialog.Footer> <div style={{ display: "flex", justifyContent: "end" }}> <Button type="normal" onClick={update}> Save </Button> </div> </Dialog.Footer> </> ); };
/* eslint-disable react-hooks/rules-of-hooks */ import { useMutation } from '@apollo/client' import { useRouter } from 'next/router' import React, { useContext, useEffect } from 'react' import HeaderComponent from '../components/HeadComponent' import LoginRegister from '../components/LoginRegister' import { Context } from '../context/context' import useError from '../hook/useError' import useInput from '../hook/useInput' import { getTokenCookie } from '../utils/getTokenCookie' import { setTokenCookie } from '../utils/setTokenCookie' const login = () => { const router = useRouter() const [email, validateEmail, setValidateEmail] = useInput() const [password, validatePassword, setValidatePassword] = useInput() const {error, setErrorFn} = useError() const context = useContext(Context)! const [loginUser] = useMutation(context.LOGIN_USER) const submitLogin = async (e: any) => { e.preventDefault() if (validateEmail && validatePassword) { const token = await loginUser({ variables: { email: email.current.value, password: password.current.value, }, }) const {user,token:tokenSet,error} = token.data.loginUser setErrorFn(error) if(error) return setTokenCookie(tokenSet) context.setUser(user) document.location.href = '/personalInfo' } } useEffect(() => { if(getTokenCookie()) router.push('/personalInfo') },[router]) return ( <> <HeaderComponent title='Login' /> <LoginRegister handleSubmit={submitLogin} title="Login" text="Don't have an account yet?" linkText="register" link="register" vlEmail={validateEmail} vlPassword={validatePassword} email={email} error={error} password={password} setValidateEmail={setValidateEmail} setValidatePassword={setValidatePassword} buttonText="Login" /> </> ) } export default login
import clsx from "clsx"; import data from "@/schemas/footer-menu.json"; import Link from "next/link"; export type FooterMenuItemType = { title: string; link: string; is_link: boolean; rel?: string; target?: string; }; type FooterMenuColumnType = { main_title: string; item: FooterMenuItemType[]; }; export default async function FooterMenu() { return ( <ul className={clsx( "grid grid-cols-2 gap-x-4 gap-y-8 py-8", "sm:grid-cols-3 sm:gap-x-8 sm:gap-y-16", "lg:grid-cols-5" )} > {data?.map((column: FooterMenuColumnType) => ( <li key={column.main_title}> <div className="text-primaryfont-medium mb-5">{column.main_title}</div> <ul className="flex flex-col gap-3"> {column?.item?.map((item: FooterMenuItemType) => ( <li key={item.title} className=" cursor-pointer"> {item?.is_link ? ( <Link href={item.link} rel="noreferrer" target="target" className="hover:text-primary" > {item.title} </Link> ) : ( item.title )} </li> ))} </ul> </li> ))} </ul> ); }
class UserInterface { constructor() { //element selectors this.gameDisplay = document.querySelector(".maingame-display"); this.nameDisplay = document.querySelector(".player-name"); this.errorDisplay = document.querySelector(".error-display"); this.timeDisplay = document.querySelector(".game-timer"); this.inputErrorDisplay = document.querySelector(".input-error-display"); this.quoteDisplay = document.querySelector(".quote-display"); this.usedCharDisplay = document.querySelector(".used-chars"); this.highscoreDisplay = document.querySelector(".highscore-table"); this.highscoreTable = document.querySelector("#HStable-rows"); this.gameReset = document.querySelector("#reset-game"); this.nameForm = document.querySelector(".name-input"); this.guessInput = document.querySelector(".guess-input"); this.displayCanvas = document.querySelector("#hangmanCanvas"); this.gameOver = document.querySelector(".game-over"); this.errorNum = document.querySelector(".errornum") } initGameUI() { //hide name form, display char name and game display this.nameDisplay.innerHTML = `<span>Name: ${gameMechanics.initPlayerName()}</span>`; this.nameForm.style.display = "none"; this.gameDisplay.style.display = "flex"; } resetGameUI() { //reset UI this.gameOver.style.display = "none"; this.guessInput.style.display = "flex"; this.inputErrorDisplay.innerHTML = ""; this.highscoreDisplay.style.display = "none"; this.displayNumError(0) this.usedCharDisplay.innerHTML = ""; } displayGameOver() { //hide guess input and show game over instead this.guessInput.style.display = "none"; this.gameOver.style.display = "block" } displayTime(time) { //display elapsed time in sec this.timeDisplay.innerHTML = `Time elapsed: ${time} sec`; } displayErrColor(errColor) { this.errorNum.id = errColor; } displayUsedChar(usedChar) { //display used chars this.usedCharDisplay.innerHTML = `Used letters: ${usedChar}`; } displayQuoteStr(guessQuote) { //display guess quote this.quoteDisplay.innerHTML = `<p>Guess a saying!</p><br><p>${guessQuote}</p>`; } showAnswer(answer) { //show answer (data.content) this.guessInput.style.display = "none"; this.quoteDisplay.innerHTML = `<p>The answer is: </p><p>${answer}</p>`; } displayInputError(err) { //errors for guess char input this.inputErrorDisplay.innerHTML = err; } displayNumError(num) { //display num of errors this.errorNum.innerHTML = `${num}`; switch (true) { case (num >= 6): this.displayErrColor("GOerror") break; case (num >= 4): this.displayErrColor("dangererror") break; case (num >= 2): this.displayErrColor("mederror") break; default: this.displayErrColor("lilerror") break; } } displayHighscores() { //fetch highscores, sort and display hangmanData.getHighscoreData() .then(highscore => sortHighscores(highscore)) .catch(err => console.log(err)); const sortHighscores = data => { //sorts fetched highscores let highScores; const calculateScore = (player) => { return (100 / (1 + player.errors)).toFixed(2); //score is calculated as 100 / (1 + num of errs) }; highScores = data.map(player => ({ username: player.userName, score: calculateScore(player) })); highScores.sort((a, b) => b.score - a.score); //sorts from higher score to lower let tables = highScores.map(item => { //renders table return ` <tr> <td>${item.username}</td> <td>${item.score}</td> </tr> `; }).join(""); //displays table this.highscoreTable.innerHTML = tables; this.highscoreDisplay.style.display = "flex"; this.highscoreDisplay.scrollIntoView({behavior: "smooth"}); } } }
package org.example; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); List<String> questions = generateQuestions(); Collections.shuffle(questions); int totalQuestions = random.nextInt(questions.size()) + 1; int correctAnswers = 0; for (int i = 0; i < totalQuestions; i++) { String question = questions.get(i); int num1 = Integer.parseInt(question.split(" x ")[0]); int num2 = Integer.parseInt(question.split(" x ")[1]); System.out.print("Питання " + (i + 1) + ": " + num1 + " x " + num2 + " = "); int userAnswer = scanner.nextInt(); if (userAnswer == (num1 * num2)) { System.out.println("Правильно!"); correctAnswers++; } else { System.out.println("Неправильно. Правильна відповідь: " + (num1 * num2)); } } double percentageCorrect = (double) correctAnswers / totalQuestions * 100; int grade = calculateGrade(percentageCorrect); System.out.println("Ви відповіли правильно на " + correctAnswers + " з " + totalQuestions + " питань."); System.out.println("Ваша оцінка: " + grade + " балів з 12."); } private static List<String> generateQuestions() { List<String> questions = new ArrayList<>(); for (int i = 2; i <= 9; i++) { for (int j = 2; j <= 9; j++) { questions.add(i + " x " + j); } } return questions; } private static int calculateGrade(double percentageCorrect) { if (percentageCorrect >= 90) { return 12; } else if (percentageCorrect >= 80) { return 11; } else if (percentageCorrect >= 70) { return 10; } else if (percentageCorrect >= 60) { return 9; } else if (percentageCorrect >= 50) { return 8; } else if (percentageCorrect >= 40) { return 7; } else if (percentageCorrect >= 30) { return 6; } else if (percentageCorrect >= 20) { return 5; } else if (percentageCorrect >= 10) { return 4; } else { return 3; } } }
<mat-toolbar color="primary" class="mat-elevation-z8"> <span class="span">Réserver une salle pour une réunion </span> </mat-toolbar> <mat-card class="example-card"> <mat-progress-bar mode="indeterminate"></mat-progress-bar> <br> <form [formGroup]="meetingForm" (ngSubmit)="meetingForm.valid && onSubmitForm()" class="form-container"> <div class="parent"> <h2>Veuillez choisir une réunion pour réserver sa salle</h2> </div> <mat-form-field appearance="fill"> <mat-label>Réunion</mat-label> <mat-select matTooltip="Choisir une réunion pour laquelle il faut réserver une salle" (selectionChange)="selectedReunion($event)" formControlName="reunion"> <mat-option *ngFor="let meeting of notReservedMeetings" [value]="meeting.id"> Réunion {{meeting.id}} - Nombre de Personnes {{meeting.numberOfPersons}} </mat-option> </mat-select> </mat-form-field> <mat-divider inset></mat-divider> <br> <div class="parent"> <h2>Salles avec capacité à 70% suffisante et leurs équipements</h2> </div> <mat-form-field appearance="fill"> <mat-label>Salle</mat-label> <mat-select #matRef matTooltip="Choisir d'abord la réunion puis choisir une salle appropriée, les équipements en noir sont ceux déjà présents dans la salle. Le trèfle indique que la salle a déjà une autre réservation dans la matinée. Pour rappel, une salle ne peut pas être réservée 1h avant votre réunion. Elle ne peut donc avoir que 2 réservations dans la matinée." (selectionChange)="selectedSalle($event)" formControlName="salle"> <mat-option *ngFor="let room of roomsForSelectedMeeting" [value]="room.id"> Salle {{room.id}} - Capacité à 70% : {{room.capacity70}} <span *ngIf="room.meetingsIds.length>0">- &#9827;</span> </mat-option> </mat-select> <mat-list role="list"> <mat-list-item role="listitem" *ngFor="let roomTool of presentToolTypesInRoom">{{roomTool}}</mat-list-item> </mat-list> <mat-divider></mat-divider> <mat-list role="list" matTooltip="Les équipements en vert sont ceux dont il y a besoin pour la réunion"> <mat-list-item role="listitem" *ngFor="let neededTool of neededToolsInRoom" style="color: green;">{{neededTool}} </mat-list-item> </mat-list> <mat-divider></mat-divider> <mat-list role="list" matTooltip="Les équipements en rouge sont ceux qui manquent pour le type de la réunion"> <mat-list-item role="listitem" *ngFor="let tool of missingToolTypesInRoom" style="color: crimson;">{{tool}} </mat-list-item> </mat-list> </mat-form-field> <mat-divider inset></mat-divider> <br> <div class="parent"> <h2>Équipements Libres pour la réunion si besoin</h2> </div> <mat-form-field appearance="fill"> <mat-label>Webcam</mat-label> <mat-select matTooltip="Si la salle n'a pas de webcam nécessaire à la réunion, veuillez choisir une webcam. Pensez à la rendre à la fin de votre réunion ! Le trèfle indique qu'un équipement a déjà un nombre donné de réservations." formControlName="camera"> <mat-option *ngFor="let webcam of webcams" [value]="webcam.freeToolId"> Équipement Libre {{webcam.freeToolId}} - Type : {{webcam.type}} <span *ngIf="webcam.meetingsIds.length>0">- &#9827; {{webcam.meetingsIds.length}}</span> </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Tableau</mat-label> <mat-select matTooltip="Si la salle n'a pas de tableau nécessaire à la réunion, veuillez choisir un tableau. Pensez à le rendre à la fin de votre réunion ! Le trèfle indique qu'un équipement a déjà un nombre donné de réservations." formControlName="board"> <mat-option *ngFor="let tableau of tableaux" [value]="tableau.freeToolId"> Équipement Libre {{tableau.freeToolId}} - Type : {{tableau.type}} <span *ngIf="tableau.meetingsIds.length>0">- &#9827; {{tableau.meetingsIds.length}}</span> </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Pieuvre</mat-label> <mat-select matTooltip="Si la salle n'a pas de pieuvre nécessaire à la réunion, veuillez choisir une pieuvre. Pensez à la rendre à la fin de votre réunion ! Le trèfle indique qu'un équipement a déjà un nombre donné de réservations." formControlName="octopus"> <mat-option *ngFor="let pieuvre of pieuvres" [value]="pieuvre.freeToolId"> Pieuvre {{pieuvre.freeToolId}} - Type : {{pieuvre.type}} <span *ngIf="pieuvre.meetingsIds.length>0">- &#9827; {{pieuvre.meetingsIds.length}}</span> </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Ecran</mat-label> <mat-select matTooltip="Si la salle n'a pas d'écran nécessaire à la réunion, veuillez choisir un écran. Pensez à le rendre à la fin de votre réunion ! Le trèfle indique qu'un équipement a déjà un nombre donné de réservations." formControlName="screen"> <mat-option *ngFor="let ecran of ecrans" [value]="ecran.freeToolId"> Ecran {{ecran.freeToolId}} - Type : {{ecran.type}} <span *ngIf="ecran.meetingsIds.length>0">- &#9827; {{ecran.meetingsIds.length}}</span> </mat-option> </mat-select> </mat-form-field> <mat-divider inset></mat-divider> <br> <div class="parent"> <button mat-raised-button color="primary" type="submit" [disabled]="meetingForm.invalid"> Soumettre</button> </div> <br> </form> <mat-progress-bar mode="indeterminate"></mat-progress-bar> </mat-card>
# Iris Keyboard Layout This is an example for the Iris keyboard. - The core layout is 2x(3x5 + 3) = 36 ```options layoutFn = LAYOUT ``` ```aliases lock = c+g+q ``` ```combos q+w = esc ``` ## Keyboard Structure ```structure 37 38 39 40 41 42 || 43 44 45 46 47 48 49 1 2 3 4 5 || 6 7 8 9 10 50 51 11 12 13 14 15 || 16 17 18 19 20 52 53 21 22 23 24 25 54 || 55 26 27 28 29 30 56 31 32 33 || 34 35 36 ``` ## Base layer ```layer:base esc 1 2 3 4 5 || 6 7 8 9 0 bs tab q w e r t || y u i o p \ lgui lctl/a lsft/s lgui/d l(f)/f g || h l(j)/j rgui/k rsft/l rctl/; ' osm(lsft) z x lalt/c l(v)/v b home || end n l(m)/m lalt/, . / osm(rsft) lctl osm(lgui) spc || ent bs ralt ``` ## Layer: F (when F is held) ```layer:f __ ! @ # $ boot || ^ & * - = __ __ esc __ __ __ __ || ~ pgdn s+tab tab pgup __ __ __ __ __ __ to(game) || left down up right __ __ __ __ __ __ __ __ __ || boot bs ent home end / __ __ __ __ || __ __ __ ``` ## Layer: J (when J is held) ```layer:j lock ! @ # $ 5 || __ __ __ __ __ __ * ` : ( ) ~ || __ __ __ __ __ __ = _ - [ ] $ || __ __ __ __ __ __ __ | < { } > f12 || __ __ __ __ __ __ __ __ __ __ || __ __ __ ``` ## Layer: V (when V is held) ```layer:v __ __ __ __ __ __ || __ __ __ __ __ __ __ __ vol+ __ __ __ || + 7 8 9 * __ __ __ play __ __ __ || - 4 5 6 = __ __ __ vol- __ __ __ __ || __ 0 1 2 3 . __ __ __ __ || __ __ , ``` ## Layer: M (when M is held) ```layer:m __ __ __ __ __ __ || __ __ __ __ __ __ __ __ __ __ __ __ || __ __ __ vol+ __ __ __ __ __ __ __ __ || __ __ __ play __ __ __ __ __ __ __ __ __ || __ __ __ __ vol- __ __ __ __ __ || __ __ __ ``` ## Layer: Gaming ```layer:game esc 1 2 3 4 5 || 6 7 8 9 0 bs tab q w e r t || y u i o p \ lgui a s d f g || h j k l ; ' lsft z x c v b to(base) || end n m , . / rsft lctl osm(lgui) spc || ent bs ralt ``` ## Layer template ```disabled:layer __ __ __ __ __ __ || __ __ __ __ __ __ __ __ __ __ __ __ || __ __ __ __ __ __ __ __ __ __ __ __ || __ __ __ __ __ __ __ __ __ __ __ __ __ || __ __ __ __ __ __ __ __ __ __ || __ __ __ ```
--- x: Lua title: Try Lua in Y minutes image: /try/cover.png lastmod: 2024-05-12 original: https://learnxinyminutes.com/docs/lua/ license: CC-BY-SA-3.0 contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] - ["Sameer Srivastava", "https://github.com/s-m33r"] --- [Lua](https://www.lua.org/) is designed to be a lightweight embeddable scripting language that is easy to learn and use and to embed into your application. This guide has been adapted from the [learnxinyminutes page on Lua](https://learnxinyminutes.com/docs/lua/) and [the Lua reference manual](https://lua.org/manual/5.4/). [Introduction](#introduction) · [Variables and flow control](#variables-and-flow-control) · [Functions](#functions) · [Tables](#tables) · [Metatables and metamethods](#metatables-and-metamethods) · [Class-like tables and inheritance](#class-like-tables-and-inheritance) · [Modules](#modules) · [Further Reading](#further-reading) <div class="tryx__panel"> <p>✨ This is an open source guide. Feel free to <a href="https://github.com/nalgeon/tryxinyminutes/blob/main/try/lua/index.md">improve it</a>!</p> </div> ## Introduction Lua has no notion of a "main" program: it works embedded in a host client, called the embedding program or simply the host. (Frequently, this host is the stand-alone lua program.) The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. Let's begin: Two dashes start a one-line comment. ```lua -- Two dashes start a one-line comment. ``` <codapi-snippet sandbox="lua" editor="basic" output-mode="hidden"> </codapi-snippet> Multi-line comments. ```lua --[[ Adding two ['s and ]'s makes it a multi-line comment. --]] ``` <codapi-snippet sandbox="lua" editor="basic" output-mode="hidden"> </codapi-snippet> ## Variables and flow control Lua is dynamically typed, with **global variables by default**. There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table. ```lua num = 42 -- Numbers can be integer or floating point. someFloat = 1.23 bool = false s = 'walternate' -- Immutable strings like Python. t = "double-quotes are also fine" u = [[ Double brackets start and end multi-line strings.]] t = nil -- Undefines t; Lua has garbage collection. -- Undefined variables return nil. -- This is not an error: foo = anUnknownVariable -- Now foo = nil. ``` <codapi-snippet id="vars" sandbox="lua" editor="basic" output-mode="hidden"> </codapi-snippet> Blocks are denoted with keywords like do/end. All whitespace is ignored. Looping constructs: ```lua while num < 50 do num = num + 1 -- No ++ or += type operators. print(num) end karlSum = 0 for i = 1, 100 do -- The range includes both ends. karlSum = karlSum + i end repeat num = num - 1 until num > 10 ``` <codapi-snippet sandbox="lua" depends-on="vars" editor="basic"> </codapi-snippet> If/Else clauses: ```lua if num > 40 then print('over 40') elseif s ~= 'walternate' then -- ~= is not equals. -- Equality check is == like Python; ok for strs. io.write('not over 40\n') -- Defaults to stdout. else -- Variables are global by default. thisIsGlobal = 5 -- Camel case is common. -- How to make a variable local: local line = io.read() -- Reads next stdin line. -- String concatenation uses the .. operator: print('Winter is coming, ' .. line) end ``` <codapi-snippet sandbox="lua" depends-on="vars" editor="basic"> </codapi-snippet> Only nil and false are falsy; 0 and '' are true! ```lua if not nonexistentVariable then print('it was false') end -- 'or' and 'and' are short-circuited. -- This is similar to the a?b:c operator in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> More on ranges: ```lua -- Use "100, 1, -1" as the range to count down: fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j; if j % 2 == 0 then print(j) end -- use ; to put multiple statements in one line end -- In general, the range is begin, end[, step]. ``` <codapi-snippet sandbox="lua" depends-on="vars" editor="basic"> </codapi-snippet> ## Functions Functions are defined using the keyword 'function' and follow the format `function name(argslist) [block] end`. No `do` required. ```lua function fib(n) if n < 2 then return 1 end return fib(n - 2) + fib(n - 1) end print(fib(5)) ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> Closures and anonymous functions are ok: ```lua function adder(x) -- The returned function is created when adder is -- called, and remembers the value of x: return function (y) return x + y end end a1 = adder(9) a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> Lua supports multiple single-line assignments and returns. ```lua -- Returns, func calls, and assignments all work -- with lists that may be mismatched in length. -- Unmatched receivers are nil; -- unmatched senders are discarded. x, y, z = 1, 2, 3, 4 -- Now x = 1, y = 2, z = 3, and 4 is thrown away. function bar(a, b, c) print(a, b, c) return 4, 8, 15, 16, 23, 42 end x, y = bar('zaphod') --> prints "zaphod nil nil" -- Now x = 4, y = 8, values 15...42 are discarded. ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> Functions are first-class, global by default like variables. ```lua -- Functions are first-class, may be local/global. -- These are the same: function f(x) return x * x end f = function (x) return x * x end print(f(11)) -- And so are these: local function g(x) return math.sin(x) end local g; g = function (x) return math.sin(x) end -- the 'local g' decl makes g-self-references ok. -- Trig funcs work in radians, by the way. print(g(math.pi/2)) ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> Calls with one string param don't need parens. ```lua print 'hello' -- Works fine. ``` <codapi-snippet sandbox="lua" editor="basic"> </codapi-snippet> ## Tables Tables are Lua's only compound data structure. Under the hood, they are associative arrays. Similar to JS objects, they are hash-lookup dicts that can also be used as lists. Using tables as dictionaries/maps: ```lua t = {key1 = 'value1', key2 = false} u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} ``` <codapi-snippet id="tabledecl" sandbox="lua" output-mode="hidden" editor="basic"> </codapi-snippet> ```lua -- string keys can use JS-like dot notation print(t.key1) t.newKey = {} -- Adds a new key/value pair. t.key2 = nil -- Removes key2 from the table. -- Literal notation for any (non-nil) value as key: print(u[6.28]) -- prints "tau" ``` <codapi-snippet sandbox="lua" depends-on="tabledecl" editor="basic"> </codapi-snippet> Key matching is basically by value for numbers and strings, but by identity for tables. ```lua a = u['@!#'] -- Now a = 'qbert'. b = u[{}] -- We might expect 1729, but it's nil: -- b = nil since the lookup fails. It fails -- because the key we used is not the same object -- as the one used to store the original value. So -- strings & numbers are more portable keys. print(a) ``` <codapi-snippet sandbox="lua" depends-on="tabledecl" editor="basic" > </codapi-snippet> Similar to strings, a one-table function call needs no parens: ```lua function h(x) print(x.key) end h{key = 'Sonmi~451'} -- Prints 'Sonmi~451'. ``` <codapi-snippet sandbox="lua" editor="basic" > </codapi-snippet> Tables can be iterated over: ```lua for key, val in pairs(u) do -- Table iteration. print(key, val) end -- Notice that printing out the `table` key's value prints the memory address for that table. ``` <codapi-snippet sandbox="lua" depends-on="tabledecl" editor="basic" > </codapi-snippet> `_G` is a special table of all globals. ```lua print(_G['_G'] == _G) -- true ``` <codapi-snippet sandbox="lua" editor="basic" > </codapi-snippet> Using tables as lists / arrays. **Indices start at 1**. ```lua -- List literals implicitly set up int keys: v = {'value1', 'value2', 1.21, 'gigawatts'} for i = 1, #v do -- #v is the size of v for lists. print(v[i]) -- Indices start at 1 !! SO CRAZY! end -- A 'list' is not a real type. v is just a table -- with consecutive integer keys, treated as a list. ``` <codapi-snippet sandbox="lua" editor="basic" > </codapi-snippet> ## Metatables and metamethods A table can have a metatable that gives the table operator-overloadish behavior. Later we'll see how metatables support js-prototype behavior. ```lua f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} -- This would fail: -- s = f1 + f2 ``` <codapi-snippet id="metatable1" sandbox="lua" editor="basic" > </codapi-snippet> ```lua metafraction = {} function metafraction.__add(f1, f2) sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum end setmetatable(f1, metafraction) setmetatable(f2, metafraction) s = f1 + f2 -- call __add(f1, f2) on f1's metatable print(s.a, s.b) -- This would fail since s has no metatable: -- z = s + s ``` <codapi-snippet sandbox="lua" editor="basic" depends-on="metatable1" > </codapi-snippet> f1, f2 have no key for their metatable, unlike prototypes in js, so you must retrieve it as in `getmetatable(f1)`. The metatable is a normal table with keys that Lua knows about, like `__add`. An `__index` on a metatable overloads dot lookups. From the Lua reference manual: > The indexing access operation table[key]. This event happens when table is not a table or when key is not present in table. The metavalue is looked up in the metatable of table. ```lua defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) eatenBy = myFavs.animal -- works! thanks, metatable print(eatenBy) ``` <codapi-snippet sandbox="lua" editor="basic" > </codapi-snippet> Direct table lookups that fail will retry using the metatable's `__index` value, and this recurses. An `__index` value can also be a function(tbl, key) for more customized lookups. Values of index, add, .. are called metamethods. Here is a list: (not runnable) ```lua -- __add(a, b) for a + b -- __sub(a, b) for a - b -- __mul(a, b) for a * b -- __div(a, b) for a / b -- __mod(a, b) for a % b -- __pow(a, b) for a ^ b -- __unm(a) for -a -- __concat(a, b) for a .. b -- __len(a) for #a -- __eq(a, b) for a == b -- __lt(a, b) for a < b -- __le(a, b) for a <= b -- __index(a, b) <fn or a table> for a.b -- __newindex(a, b, c) for a.b = c -- __call(a, ...) for a(...) ``` ## Class-like tables and inheritance Classes aren't built in; there are different ways to make them using tables and metatables. Explanation below: ```lua Dog = {} -- 1. function Dog:new() -- 2. newObj = {sound = 'woof'} -- 3. self.__index = self -- 4. return setmetatable(newObj, self) -- 5. end function Dog:makeSound() -- 6. print('I say ' .. self.sound) end mrDog = Dog:new() -- 7. ``` <codapi-snippet id="Dog" sandbox="lua" editor="basic" > </codapi-snippet> ```lua mrDog:makeSound() -- 'I say woof' -- 8. ``` <codapi-snippet id="Dog-makeSound" sandbox="lua" depends-on="Dog" editor="basic" > </codapi-snippet> 1. Dog acts like a class; it's really a table. 2. function tablename:fn(...) is the same as function tablename.fn(self, ...) The : just adds a first arg called self. Read 7 & 8 below for how self gets its value. 3. newObj will be an instance of class Dog. 4. self = the class being instantiated. Often self = Dog, but inheritance can change it. newObj gets self's functions when we set both newObj's metatable and self's \_\_index to self. 5. Reminder: setmetatable returns its first arg. 6. The : works as in 2, but this time we expect self to be an instance instead of a class. 7. Same as Dog.new(Dog), so self = Dog in new(). 8. Same as mrDog.makeSound(mrDog); self = mrDog. **Inheritance Example:** ```lua LoudDog = Dog:new() -- 1. function LoudDog:makeSound() s = self.sound .. ' ' -- 2. print(s .. s .. s) end seymour = LoudDog:new() -- 3. ``` <codapi-snippet sandbox="lua" id="LoudDog" depends-on="Dog" editor="basic" > </codapi-snippet> ```lua seymour:makeSound() -- 'woof woof woof' -- 4. ``` <codapi-snippet sandbox="lua" id="LoudDog-makeSound" depends-on="LoudDog" editor="basic" > </codapi-snippet> 1. LoudDog gets Dog's methods and variables. 2. self has a 'sound' key from new(), see 3. 3. Same as LoudDog.new(LoudDog), and converted to Dog.new(LoudDog) as LoudDog has no 'new' key, but does have \_\_index = Dog on its metatable. Result: seymour's metatable is LoudDog, and LoudDog.\_\_index = LoudDog. So seymour.key will = seymour.key, LoudDog.key, Dog.key, whichever table is the first with the given key. 4. The 'makeSound' key is found in LoudDog; this is the same as LoudDog.makeSound(seymour). ```lua -- If needed, a subclass's new() is like the base's: function LoudDog:new() newObj = {} -- set up newObj self.__index = self return setmetatable(newObj, self) end ``` <codapi-snippet sandbox="lua" depends-on="LoudDog" editor="basic" > </codapi-snippet> ## Modules Suppose the file mod.lua looks like this: ```lua -- mod.lua local M = {} local function sayMyName() print('Hrunkner') end function M.sayHello() print('Why hello there') sayMyName() end return M ``` Another file can use mod.lua's functionality: ```lua local mod = require('mod') -- Run the file mod.lua. -- This works because mod here = M in mod.lua: mod.sayHello() -- Prints: Why hello there Hrunkner ``` <codapi-snippet id="mod" sandbox="lua" files="mod.lua" editor="basic" > </codapi-snippet> ```lua -- This is wrong; sayMyName only exists in mod.lua: mod.sayMyName() -- error ``` <codapi-snippet sandbox="lua" depends-on="mod" files="mod.lua" editor="basic" > </codapi-snippet> `require`'s return values are cached so a file is run at most once, even when require'd many times. Example: ```lua -- mod2.lua print('Hi') ``` ```lua local a = require('mod2') -- Prints Hi! local b = require('mod2') -- Doesn't print; a=b. ``` <codapi-snippet sandbox="lua" files="mod2.lua" editor="basic" > </codapi-snippet> `dofile` is like require without caching: ```lua dofile('mod2.lua') --> Hi! dofile('mod2.lua') --> Hi! (runs it again) ``` <codapi-snippet sandbox="lua" files="mod2.lua" editor="basic" > </codapi-snippet> ```lua -- loadfile loads a lua file but doesn't run it yet. f = loadfile('mod2.lua') -- Call f() to run it. -- load is loadfile for strings. -- (loadstring is deprecated, use load instead) g = load('print(343)') -- Returns a function. g() -- Prints out 343; nothing printed before now. ``` <codapi-snippet sandbox="lua" files="mod2.lua" editor="basic" > </codapi-snippet> ## Further Reading Books and references: - The official [Programming in Lua](https://www.lua.org/pil/contents.html) book - [BlackBulletIV’s Lua for programmers](https://ebens.me/posts/lua-for-programmers-part-1/) - [Lua Short Reference](http://lua-users.org/wiki/LuaShortReference) In the wild: - [Love2D](https://love2d.org/) is a very popular Lua game engine - Fantasy consoles like [TIC-80](https://tic80.com/) use Lua as the main programming language for games Standard library: - [string library](http://lua-users.org/wiki/StringLibraryTutorial) - [table library](http://lua-users.org/wiki/TableLibraryTutorial) - [math library](http://lua-users.org/wiki/MathLibraryTutorial) - [io library](http://lua-users.org/wiki/IoLibraryTutorial) - [os library](http://lua-users.org/wiki/OsLibraryTutorial) Have fun with Lua!
import 'package:ecom_ass/server/api_handler.dart'; import 'package:ecom_ass/server/models/my_course.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; class MyCoursesScreen extends StatefulWidget { const MyCoursesScreen( {super.key, required this.studentId, required this.studentName}); final String studentId; final String studentName; @override State<MyCoursesScreen> createState() => _MyCoursesScreenState(); } class _MyCoursesScreenState extends State<MyCoursesScreen> { List<MyCourseModel> myCourses = []; var currRating = 3.0; var reviewController = TextEditingController(); @override void initState() { super.initState(); getMycourses(); } Future<void> getMycourses() async { myCourses = await ApiHandler.getMyCourses(widget.studentId, widget.studentName); setState(() {}); } Future<void> cancelCourse(var index) async { await showDialog( context: context, builder: (context) => AlertDialog( actions: [ TextButton( onPressed: () async { var response = await ApiHandler.cancelCourse( myCourses[index].id, widget.studentName, widget.studentId, ); if (response.statusCode == 200) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Course cancelled successfully!'), ), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(response.body)), ); } getMycourses(); Navigator.pop(context); }, child: const Text('Yes')), TextButton( onPressed: () async { Navigator.pop(context); }, child: const Text('No')) ], title: const Text('Cancel course'), contentPadding: const EdgeInsets.all(15.0), content: const Text('Are you sure you want to cancel this course?'), ), ); } Future<void> reviewCourse(var index) async { await showDialog( context: context, builder: (context) => AlertDialog( actions: [ TextButton( onPressed: () async { var response = await ApiHandler.reviewCourse( myCourses[index].id, widget.studentName, widget.studentId, reviewController.text, currRating, ); if (response.statusCode == 200) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Review submitted successfully!'), ), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(response.body)), ); } Navigator.pop(context); }, child: const Text('Submit')), TextButton( onPressed: () async { Navigator.pop(context); }, child: const Text('Cancel')) ], title: const Text('Review Course'), contentPadding: const EdgeInsets.all(15.0), content: SizedBox( height: MediaQuery.of(context).size.height * 0.35, child: Column( children: [ RatingBar.builder( initialRating: 3, minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemPadding: const EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => const Icon( Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { currRating = rating; }, ), const SizedBox(height: 30), TextField( decoration: const InputDecoration( hintText: 'Write Your Review', border: OutlineInputBorder()), minLines: 5, maxLines: 10, controller: reviewController, ), ], ), ), ), ); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: SizedBox( width: MediaQuery.of(context).size.width * 0.5, height: MediaQuery.of(context).size.height * 0.8, child: Card( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 16), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ IconButton( icon: const Icon(Icons.arrow_back_rounded), onPressed: () { Navigator.pop(context); }), const Text( "My myCourses", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 40, width: 40), ], ), const SizedBox(height: 10), const Divider(), const SizedBox(height: 10), const Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ SizedBox( width: 130, child: Center( child: Text('Name', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), SizedBox( width: 70, child: Center( child: Text('Duration', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), SizedBox( width: 220, child: Center( child: Text('Category', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), SizedBox( width: 55, child: Center( child: Text('Rating', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), SizedBox( width: 100, child: Center( child: Text('Status', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), SizedBox( width: 120, child: Center( child: Text('', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), )), ]), Visibility( visible: myCourses.isNotEmpty, child: Expanded( child: ListView.builder( itemCount: myCourses.length, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.all(8.0), child: Padding( padding: const EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ SizedBox( width: 130, child: Center( child: Text( myCourses[index].name, style: const TextStyle( fontSize: 18, ), ), ), ), SizedBox( width: 70, child: Center( child: Text( myCourses[index].duration.toString(), style: const TextStyle( fontSize: 18, ), ), ), ), SizedBox( width: 220, child: Center( child: Text( myCourses[index].category, style: const TextStyle( fontSize: 18, ), ), ), ), SizedBox( width: 55, child: Center( child: Text( myCourses[index].rating.toString(), style: const TextStyle( fontSize: 18, ), ), ), ), SizedBox( width: 100, child: Center( child: Text( myCourses[index].status, style: const TextStyle( fontSize: 18, ), ), ), ), SizedBox( width: 120, child: Center( child: Column(children: [ Visibility( visible: myCourses[index].status == 'current', child: TextButton( onPressed: () { cancelCourse(index); }, child: const Text( 'Cancel course', style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold), ), ), ), Visibility( visible: myCourses[index].status == 'done', child: TextButton( onPressed: () { reviewCourse(index); }, child: const Text( 'Review course', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold), )), ), ]), ), ), ], ), ), ); }, ), ), ), Visibility( visible: myCourses.isEmpty, child: const Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text('You have not enrolled any courses yet'), ], ))), ], ), ), ), ), ), ); } }
# grunt-csproj-integrity > Grunt plugin of [csproj-integrity](https://github.com/mantovanig/csproj-integrity) ## Getting Started This plugin requires Grunt `~0.4.5` If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command: ```shell npm install grunt-csproj-integrity --save-dev ``` Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: ```js grunt.loadNpmTasks('grunt-csproj-integrity'); ``` ## The "csproj_integrity" task ### Options #### options.checkFiles Type: `Boolean` Default value: `false` With this option you can turn on the checkFiles task of csproj-integrity #### options.checkIntegrity Type: `Boolean` Default value: `false` With this option you can turn on the checkIntegrity task of csproj-integrity ### Usage Examples #### Default Options ```js grunt.initConfig({ csproj_integrity: { cwd: '', src: ['test/**/*.cs', 'test/**/*.cshtml'], options: { checkFiles: true, checkIntegrity: true } }, }); ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). ## Release History _(Nothing yet)_
import PropTypes from "prop-types"; import { useState, useRef } from "react"; import ReactDom from "react-dom"; import CloseTimer from "../UI/CloseTimer"; import ErrorModal from "./ErrorModal"; const AddFormItemRequestInfoModal = ({ isShowModal, setIsShowModal, newItemRequest, formStructureList, setFormStructureList, }) => { if (!isShowModal) { return; } let errorMessage = "All fields must be filled and free of blank characters."; ("Limit of input you can add to the form: 6 There is an excess at the limit"); const [isShowError, setIsShowError] = useState(false); let newItemRequestRevize = { type: newItemRequest.type }; const inputRefs = newItemRequest.options.map(() => useRef()); const closeMessage = "After 35 seconds, your transactions will be closed without being recorded.Remaining Time:"; function aa() { inputRefs.map((item) => { let name2 = item.current.name; if (name2 === "label") { newItemRequestRevize = { ...newItemRequestRevize, [name2]: item.current.value, options: [], }; } else { newItemRequestRevize = { ...newItemRequestRevize, options: [...newItemRequestRevize.options, item.current.value], }; } }); const isFormValid = Object.values(newItemRequestRevize.options).every( (value) => value.trim() !== "" ); if (!isFormValid) { setIsShowError(true); return; } setFormStructureList([...formStructureList, newItemRequestRevize]); newItemRequestRevize = {}; setIsShowModal(false); } return ReactDom.createPortal( <div className="error-modal"> <div className="flex justify-center items-center h-screen absolute"> <div> <div className="fixed inset-0 px-2 z-10 overflow-hidden flex items-center justify-center"> <div className="absolute inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={() => setIsShowModal(false)} ></div> <div className="bg-white rounded-md shadow-xl overflow-hidden max-w-md w-full sm:w-96 md:w-1/2 lg:w-2/3 xl:w-1/3 z-50"> <div className="bg-indigo-500 text-white px-4 py-2 flex justify-between"> <h2 className="text-lg font-semibold">Item Add Modal</h2> </div> <form action=""> {newItemRequest.options.map((item, index) => ( <div key={index} className="flex p-2 mb-4 item-center w-full mx-auto rounded-lg" > <label className="block w-1/4 text-sm font-medium leading-6 text-gray-900 text-end pr-4"> {item} : </label> <input type="text" name={item} className="pl-3 rounded-md border border-sky-500" ref={inputRefs[index]} /> </div> ))} </form> <CloseTimer closeTime={35} isShow={setIsShowModal} closeMessage={closeMessage} /> <div className="border-t px-4 py-2 flex justify-end"> <button className="px-3 py-1 bg-indigo-500 text-white rounded-md w-full sm:w-auto mr-4" onClick={aa} > save{" "} </button> <button className="px-3 py-1 bg-indigo-500 text-white rounded-md w-full sm:w-auto" onClick={() => setIsShowModal(false)} > Kapat{" "} </button> </div> </div> </div> </div> </div> <ErrorModal isShowError={isShowError} setIsShowError={setIsShowError} message={errorMessage} /> </div>, document.getElementById("modal") ); }; export default AddFormItemRequestInfoModal; AddFormItemRequestInfoModal.propTypes = { isShowModal: PropTypes.bool, setIsShowModal: PropTypes.func, message: PropTypes.string, formStructureList: PropTypes.array, setFormStructureList: PropTypes.func, };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" /> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet" /> <style> * { color: white; } body { min-height: 100vh; background-color: black; display: flex; align-items: center; justify-content: center; } .background { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: url('https://images.unsplash.com/photo-1511447333015-45b65e60f6d5?q=80&w=2155&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D') center/cover no-repeat fixed; opacity: 0.3; z-index: -1; } input[type='text'], input[type='password'], input[type='text']:focus, input[type='password']:focus, input[type='text']:hover, input[type='password']:hover { background-color: transparent; border: none; border-bottom: 1px solid #ced4da; outline: none; border-radius: 0; color: white; box-shadow: none; } input[type='text']::placeholder, input[type='password']::placeholder { color: lightgray; } form { display: flex; flex-direction: column; gap: 30px; } .btn{ background-color: transparent; border: 1px solid white; align-self: center; padding-left: 20px; padding-right:20px; } .popup { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid #ccc; background-color: rgba(0,0,0,0.9); z-index: 9999; color: white; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 60px 60px; } .popup > p{ color: white; } #close-btn{ position: absolute; top: 0; right: 0; color: white; border: none; background-color: transparent; } .hidden{ display: none; } .price{ width: 100%; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="background"></div> <div class="container-fluid" id="container" style=" background-color: rgba(10, 10, 10, 0.95); width: 700px; height: 100%; border-radius: 15px; display: flex; align-items: center; justify-content: center; flex-direction: column; " > <a class="btn btn-primary align-self-start m-4" id="back-btn" th:href="${referer != null ? referer : '/'}">Go Back</a> <h1 class="text-center" th:text="${movie.title}"></h1> <div class="container my-5"> <div class="row justify-content-center "> <div class="col-md-6 mb-5 row justify-content-center"> <img th:src="@{'/getImage/' + ${movie.id}}" th:alt="${movie.title}"/> </div> <p class="mb-5" th:text="${movie.description}"></p> <p class="price" th:text="'Ticket price: $'+${movie.ticket_price}"></p> <form th:action="@{/movie-details/buy/{id}(id=${id})}" method="post"> <button type="submit" class="btn btn-primary" id="buy-btn">Buy Tickets</button> </form> </div> </div> <div id="popup" class="popup" th:if="${showPopup}"> <button id="close-btn">X</button> <h3 th:text="${message}">erhzhrt</h3> <img th:if="${isBought}" th:src="'data:image/png;base64,' + ${barcode}" alt="barcode"/> <p th:if="${isBought}">scan this barcode at any Cinema</p> </div> </div> <script> const buyBtn = document.getElementById("buy-btn"); const closeBtn = document.getElementById("close-btn"); const popup = document.getElementById("popup"); closeBtn.addEventListener("click",()=>{ popup.classList.add("hidden"); buyBtn.disabled = true; }) </script> </body> </html>
import React, { useEffect } from "react"; import "./hs.css"; // Importing the HubSpot CSS globally import HubSpotConfig from "@site/hubspot.config"; const ContactFormHS = () => { useEffect(() => { // Create a script element const script = document.createElement('script'); script.src = 'https://js.hsforms.net/forms/shell.js'; document.body.appendChild(script); // Append the script to the body // Load event listener for the script script.addEventListener('load', () => { // Check if the HubSpot forms namespace exists if (window.hbspt) { window.hbspt.forms.create({ region: HubSpotConfig.contactForm.region, portalId: HubSpotConfig.contactForm.portalId, formId: HubSpotConfig.contactForm.formId, target: HubSpotConfig.contactForm.target, }); } }); // Cleanup function to remove the script element return () => { // To keep things clean this will remove the script from the body when the component unmounts document.body.removeChild(script); }; }, []); // The empty array ensures this effect runs once on mount and cleanup runs on unmount // Render the div that will hold the HubSpot form return ( <div> <div id='hubspotForm'> {/* This is where the HubSpot form will be injected */} </div> </div> ); } export default ContactFormHS;
/** * 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 pdccourse.hw3; import java.io.BufferedReader; import java.io.IOException; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.FileReader; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.LinkedHashMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.StringUtils; public class BuildInvertedIndex { public static class MPair implements WritableComparable<MPair> { private String word; private Integer tf; public void set(String word, Integer tf) { this.word = word; this.tf = tf; } public String getWord() { return word; } public Integer getTf() { return tf; } @Override public void readFields(DataInput in) throws IOException { word = Text.readString(in); tf = Integer.parseInt(Text.readString(in)); } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, word); Text.writeString(out, tf.toString()); } @Override public int hashCode() { return word.hashCode(); } @Override public String toString() { return word.toString(); } @Override public int compareTo(MPair o) { //String[] wr = word.split(" "); //String[] owr = o.word.split(" "); if (!word.equals(o.word)) { return word.compareTo(o.word); } else { //if (!wr[1].equals(owr[1])) { return (o.tf > tf ? 1 : -1); //} //return 0; } } } public static class MPartitioner extends Partitioner<MPair, Text> { @Override public int getPartition(MPair pair, Text docid, int numOfPartitions) { return ( pair.getWord().hashCode() & Integer.MAX_VALUE ) % numOfPartitions; } } public static class MGroupComparator extends WritableComparator { //private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator(); //private static final IntWritable.Comparator INTWRITABLE_COMPARATOR = new IntWritable.Comparator(); public MGroupComparator() { super(MPair.class, true); } /*@Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { try { int firstL1 = WritableUtils.decodeVIntSize(b1[s1]) + readVInt(b1, s1); int firstL2 = WritableUtils.decodeVIntSize(b2[s2]) + readVInt(b2, s2); int cmp1 = TEXT_COMPARATOR.compare(b1, s1, firstL1, b2, s2, firstL2); if (cmp1 != 0) { return cmp1; } else { int secondL1 = WritableUtils.decodeVIntSize(b1[s1+firstL1]) + readVInt(b1, s1+firstL1); int secondL2 = WritableUtils.decodeVIntSize(b2[s2+firstL2]) + readVInt(b2, s2+firstL2); return (-1) * INTWRITABLE_COMPARATOR.compare(b1, s1+firstL1, secondL1, b2, s2+firstL2, secondL2); } } catch (IOException e) { throw new IllegalArgumentException(e); } }*/ @Override public int compare(WritableComparable w1, WritableComparable w2) { if (w1 instanceof MPair && w2 instanceof MPair) { return ((MPair)w1).compareTo((MPair)w2); } return super.compare(w1, w2); } } public static class TokenizerMapper extends Mapper<Text, Text, MPair, Text> { private List<String> skipList = new ArrayList<String>(); private long numRecords = 0; private Map<String, Map<String, Integer> > results = new HashMap<String, Map<String, Integer> >(); private final MPair pair = new MPair(); private final Text docid = new Text(); @Override protected void setup(Context context) { String skipListFile = context.getConfiguration().get("buildinvertedindex.skip-list"); if (skipListFile != null) { loadSkipListFile(skipListFile); } } public void map(Text key, Text value, Context context) throws IOException, InterruptedException { String doc_id = key.toString(); String text = value.toString(); for (String pattern : skipList) { text = text.replaceAll(pattern, " "); } StringTokenizer itr = new StringTokenizer(text); String word; while (itr.hasMoreTokens()) { word = itr.nextToken(); addResult(word, doc_id); } if ((++numRecords % 1000) == 0) { context.setStatus("Finished processing " + numRecords + " records"); emitResults(context); } } private void loadSkipListFile(String skipListFile) { BufferedReader fis = null; try { fis = new BufferedReader(new FileReader(skipListFile)); String pattern = null; while ((pattern = fis.readLine()) != null) { skipList.add(pattern); } } catch (IOException ioe) { System.err.println("Caught exception while loading skip file '" + skipListFile + "' : " + StringUtils.stringifyException(ioe)); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { System.err.println("Caught exception while closing skip file '" + skipListFile + "' : " + StringUtils.stringifyException(ioe)); } } } } private void addResult(String word, String docid) { Map<String, Integer> counts = results.get(word); if (counts == null) { counts = new HashMap<String, Integer>(); results.put(word, counts); } Integer count = counts.get(docid); if (count == null) { counts.put(docid, 1); } else { counts.put(docid, ++count); } } private void emitResults(Context context) throws IOException, InterruptedException { for (Entry<String, Map<String, Integer> > counts : results.entrySet()) { String word = counts.getKey(); for (Entry<String, Integer> count : counts.getValue().entrySet()) { pair.set(word, count.getValue()); docid.set(count.getKey()); context.write(pair, docid); } } results.clear(); } @Override public void cleanup(Context context) throws IOException, InterruptedException { emitResults(context); } } public static class IntSumReducer extends Reducer<MPair, Text, Text, Text> { //private IntWritable result = new IntWritable(); private Map<String, Map<String, Integer> > results = new HashMap<String, Map<String, Integer> >(); private Map<String, Long> DD = new HashMap<String, Long>(); //private final MPair pair = new MPair(); private final Text word = new Text(); private final Text docid = new Text(); private long numRecords = 0; static double D; @Override public void setup(Context context) throws IOException, InterruptedException { D = Double.parseDouble(context.getConfiguration().get("buildinvertedindex.D")); } public void reduce(MPair key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { String docid = ""; for (Text val : values) { docid = val.toString(); } addResult(key.getWord(), docid, key.getTf()); //context.write(new Text(key.getWord() + " " + key.getTf()), new Text(docid)); if ((numRecords % 1000) == 0) { context.setStatus("Reduce: Finished processing " + numRecords + " records"); emitResults(context); } } private void addResult(String word, String docid, Integer tf) { Map<String, Integer> counts = results.get(word); if (counts == null) { counts = new LinkedHashMap<String, Integer>(); results.put(word, counts); ++numRecords; } Integer count = counts.get(docid); if (count == null) { if (counts.size() < 20) { counts.put(docid, tf); } } else { counts.put(docid, count + tf); } Long dd = DD.get(word); if (dd == null) { DD.put(word, (long)tf); } else { DD.put(word, dd + tf); } } private void emitResults(Context context) throws IOException, InterruptedException { for (Entry<String, Map<String, Integer> > counts : results.entrySet()) { String wr = counts.getKey(); word.set(wr); Long dd = DD.get(wr); Double idf = Math.abs(Math.log(D/dd)); String text = /*dd.toString() + " : " + idf.toString() +*/ " ["; for (Entry<String, Integer> count : counts.getValue().entrySet()) { text += "<" + count.getKey() + ", " + Double.valueOf(count.getValue() * idf).toString() + ">, "; } text = text.substring(0, text.length() - 2); text += "]"; docid.set(text); context.write(word, docid); } results.clear(); DD.clear(); } @Override protected void cleanup(Context context) throws IOException, InterruptedException { emitResults(context); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 4) { System.err.println("Usage: buildinvertedindex <in> <out> <skip_list> <d>"); System.exit(2); } File skipFile = new File(otherArgs[2]); conf.set("buildinvertedindex.skip-list", skipFile.getName()); conf.set("tmpfiles", "file://" + skipFile.getAbsolutePath()); conf.set("buildinvertedindex.D", otherArgs[3]); conf.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator", " "); conf.setBoolean("exact.match.only", true); conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization," + "org.apache.hadoop.io.serializer.WritableSerialization"); Job job = new Job(conf, "build inverted index"); job.setInputFormatClass(XmlInputFormat.class); job.setJarByClass(BuildInvertedIndex.class); job.setMapperClass(TokenizerMapper.class); job.setMapOutputKeyClass(MPair.class); job.setMapOutputValueClass(Text.class); //job.setCombinerClass(IntSumReducer.class); job.setPartitionerClass(MPartitioner.class); job.setSortComparatorClass(MGroupComparator.class); //job.setGroupingComparatorClass(MGroupComparator.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
package managers; import tasks.*; import java.util.*; public class InMemoryTaskManager implements TaskManager { // Добавляем счетчик-идентификатор задач private static int idCounter = 1; // хэш-мап с задачами для внешнего использования public static HashMap<Integer, Task> tasks = new HashMap<>(); // хэш-мап с подзадачами для промежуточного накопления их, перед присваиванием их эпикам public static HashMap<Integer, SubTask> subTaskHashMap = new HashMap<>(); // Хэш-мапа эпиков для внешнего использования уже с подзадачами public static HashMap<Integer, Epic> epics = new HashMap<>(); public static int getIdCounter() { return idCounter; } public static void setIdCounter(int idCounter) { InMemoryTaskManager.idCounter = idCounter; } public void setEpicTime(Epic epic){ epic.setStartTime(getAllSubTasksByEpic(epic.getId()).stream() .map(SubTask::getStartTime) .filter(Objects::nonNull) .min(Comparator.naturalOrder()) .orElse(null)); epic.setDuration(getAllSubTasksByEpic(epic.getId()).stream() .filter(duration -> !(duration.getDuration() == null)) .mapToLong(SubTask::getDuration) .sum()); } @Override public Collection<Task> getAllTasks() { return tasks.values(); } @Override public Collection<Epic> getAllEpic() { return epics.values(); } @Override public ArrayList<SubTask> getAllSubTask() { // Создаем лист для выдачи подзадач со всех эпиков ArrayList<SubTask> subTaskList = new ArrayList<>(); // Вытаскиваем из "внешней" хэш-мапы for (Integer subTask : subTaskHashMap.keySet()) { subTaskList.add(subTaskHashMap.get(subTask)); } return subTaskList; } @Override public void removeAllTasks() throws ManagerSaveException { tasks.clear(); } @Override public void removeAllSubTasks() throws ManagerSaveException { for (Integer id : epics.keySet()) { Epic epic = epics.get(id); for (int i = 0; i < epic.getSubTasks().size(); i++) { epic.getSubTasks().remove(i); } // Этот метод будет проверять статус Эпика каждый раз, когда происходит изменение числа сабтасков или их удаление updateEpicStatus(epic.getId()); } subTaskHashMap.clear(); } @Override public void removeAllEpics() throws ManagerSaveException { epics.clear(); subTaskHashMap.clear(); } @Override public Task getTaskById(int id) throws ManagerSaveException { if (tasks.getOrDefault(id, null) != null) Managers.getDefaultHistory().add(tasks.getOrDefault(id,null)); return tasks.getOrDefault(id, null); } @Override public SubTask getSubTaskById(int id) throws ManagerSaveException { if (subTaskHashMap.getOrDefault(id,null) != null) Managers.getDefaultHistory().add(subTaskHashMap.getOrDefault(id,null)); return subTaskHashMap.getOrDefault(id, null); } @Override public Epic getEpicById(int id) throws ManagerSaveException { if(epics.containsKey(id)){ Managers.getDefaultHistory().add(epics.getOrDefault(id,null)); return epics.get(id); } return null; } @Override public Task createTask(Task task) throws ManagerSaveException { task.setId(idCounter++); tasks.put(task.getId(), task); return task; } @Override public void updateTask(Task task,int id) throws ManagerSaveException { task.setId(id); if (tasks.containsKey(id)) { tasks.put(task.getId(), task); }else System.out.println("Задачи с ID: '"+id+"' не существует"); } @Override public Epic createEpic(Epic epic) throws ManagerSaveException { epic.setId(idCounter++); // Делаем статус Эпика "NЕW" так как он только создан и при отсутствии сабтасков должен быть NEW epic.setStatus(StatusTask.NEW); epics.put(epic.getId(), epic); return epic; } @Override public void updateEpic(Epic epic, int id) throws ManagerSaveException { epic.setId(id); // Так как мы меняем эпик, то из таблицы удалим все подзадачи, Эпик же другой! if (epics.containsKey(id)) { epics.put(id,epic); updateEpicStatus(id); }else { System.out.println("Эпика с ID: '" + id + "' не существует"); } } @Override public SubTask createSubTasks(SubTask subTask) throws ManagerSaveException { if (epics.containsKey(subTask.getEpicsID())) { subTask.setId(idCounter++); subTaskHashMap.put(subTask.getId(), subTask); epics.get(subTask.getEpicsID()).getSubTasks().add(subTask.getId()); updateEpicStatus(subTask.getEpicsID()); }else { System.out.println("Эпика с ID: '" + subTask.getEpicsID() + "' не существует"); } return subTask; } @Override public void updateSubTasks(SubTask subTask, int id) throws ManagerSaveException { subTask.setId(id); // Проверяем мапу сабтасков на нужный ключ if (subTaskHashMap.containsKey(id)) { // Присваиваем новому экземпляру нужный эпик subTask.setEpicsID(subTaskHashMap.get(id).getEpicsID()); subTaskHashMap.put(id, subTask); // Идем по мапе эпиков и удаляем нужный нам сабтаск for (int i = 0; i < epics.get(subTask.getEpicsID()).getSubTasks().size(); i++) { if(epics.get(subTask.getEpicsID()).getSubTasks().get(i).equals(id)){ epics.get(subTask.getEpicsID()).getSubTasks().remove(i); } } epics.get(subTask.getEpicsID()).getSubTasks().add(subTask.getId()); updateEpicStatus(subTask.getEpicsID()); }else { System.out.println("Подзадачи с ID: '" + id + "' не существует"); } } @Override public void removeTaskById(int id) throws ManagerSaveException { if (tasks.containsKey(id)) { Managers.getDefaultHistory().remove(tasks.getOrDefault(id,null).getId()); tasks.remove(id); }else{ System.out.println( "Задачи с ID: '"+id+"' не существует"); } } @Override public void removeEpicById(int id) throws ManagerSaveException { if (epics.containsKey(id)) { Managers.getDefaultHistory().remove(epics.get(id).getId()); for (Integer subTask : epics.get(id).getSubTasks()) { removeSubTaskById(subTask); } epics.remove(id); }else{ System.out.println( "Эпика с ID: '"+id+"' не существует"); } } @Override public void removeSubTaskById(int id) throws ManagerSaveException { if (subTaskHashMap.containsKey(id)) { Managers.getDefaultHistory().remove(subTaskHashMap.getOrDefault(id,null).getId()); subTaskHashMap.remove(id); }else{ System.out.println( "Подзадачи с ID: '"+id+"' не существует"); } for (Epic epic : epics.values()) { if ((epics.getOrDefault(epic,null) == null)||(epics.get(epic).equals(0))) { continue; } epics.get(epic).getSubTasks().remove(id); updateEpicStatus(id); } } @Override public ArrayList<SubTask> getAllSubTasksByEpic(int epicId) { Epic epic = epics.get(epicId); if(epic == null){ return null; } ArrayList<SubTask> subTasks = new ArrayList<>(); for (int subTaskId : epic.getSubTasks()) { if (epic.getSubTasks().isEmpty()){ continue; } subTasks.add(subTaskHashMap.get(subTaskId)); } return subTasks; } @Override public void updateEpicStatus(int id) throws ManagerSaveException { // Создадим две переменные для проверки статусов у сабтасков boolean allSubTasksDone = true; boolean allSubTasksNew = true; Epic epic = epics.get(id); // Если Эпик пустой, то сразу делаем его NEW if(epic.getSubTasks().size() == 0){ epic.setStatus(StatusTask.NEW); return; } // Цикл проходит по всем сабтаскам эпика и делает ложными булевые значения, если они отличаются от DONE или NEW for (Integer subTask : epic.getSubTasks()) { if (!subTaskHashMap.get(subTask).getStatus().equals(StatusTask.DONE)) { allSubTasksDone = false; } if (!subTaskHashMap.get(subTask).getStatus().equals(StatusTask.NEW)) { allSubTasksNew = false; } } if(allSubTasksDone) { epic.setStatus(StatusTask.DONE); } if(allSubTasksNew) { epic.setStatus(StatusTask.NEW); } // Если оба булевы значение ложь, то Эпик будет со статусом "В_РАБОТЕ" if((!allSubTasksDone)&&(!allSubTasksNew)){ epic.setStatus(StatusTask.IN_PROGRESS); } } @Override public String toString() { return "TaskManager{" + "tasks=" + tasks + ", epics=" + epics + ", subTaskHashMap=" + subTaskHashMap + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InMemoryTaskManager that = (InMemoryTaskManager) o; return tasks.equals(that.tasks) && subTaskHashMap.equals(that.subTaskHashMap) && epics.equals(that.epics); } @Override public int hashCode() { return Objects.hash(tasks, subTaskHashMap, epics); } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SignInComponent } from './sign-in/sign-in.component'; import { ImpedimentsComponent } from './impediments/impediments.component'; import { CreateImpedimentsComponent } from './create-impediments/create-impediments.component'; import { IssueComponent } from './issue/issue.component'; // Angular material imports import { MatCardModule } from '@angular/material/card' import { MatButtonModule } from '@angular/material/button'; import { MatInputModule } from '@angular/material/input'; import { ReactiveFormsModule } from '@angular/forms'; import { MatIconModule } from '@angular/material/icon'; import { SignUpComponent } from './sign-up/sign-up.component'; import { MatSelectModule } from '@angular/material/select'; import { SelectProjectComponent } from './select-project/select-project.component'; import { CreateProjectComponent } from './create-project/create-project.component'; import { MatTooltipModule } from '@angular/material/tooltip'; import { NavigationComponent } from './navigation/navigation.component'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatRadioModule } from '@angular/material/radio'; import { FormsModule } from '@angular/forms'; import { MatTreeModule } from '@angular/material/tree'; import { EpicComponent } from './epic/epic.component'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { StoryComponent } from './story/story.component'; import { TaskComponent } from './task/task.component'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatTabsModule } from '@angular/material/tabs'; import { MatMenuModule } from '@angular/material/menu'; import { MatDialogModule } from '@angular/material/dialog'; import { FormComponent } from './form/form.component'; import { HttpClientModule } from '@angular/common/http'; import { MatTableModule } from '@angular/material/table'; import { CreateIssueComponent } from './create-issue/create-issue.component'; @NgModule({ declarations: [ AppComponent, SignInComponent, SignUpComponent, SelectProjectComponent, CreateProjectComponent, NavigationComponent, EpicComponent, StoryComponent, TaskComponent, FormComponent, ImpedimentsComponent, CreateImpedimentsComponent, IssueComponent, CreateIssueComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, MatInputModule, ReactiveFormsModule, MatIconModule, MatSelectModule, MatTooltipModule, MatToolbarModule, MatSidenavModule, MatRadioModule, FormsModule, MatTreeModule, MatSnackBarModule, MatButtonToggleModule, MatTabsModule, MatMenuModule, MatDialogModule, HttpClientModule, MatTableModule ], providers: [], bootstrap: [AppComponent], exports: [ MatButtonModule, MatDialogModule ] }) export class AppModule { }
package com.mateuszmedon.app.mobileappws.ui.controller; import com.mateuszmedon.app.mobileappws.exceptions.UserServiceException; import com.mateuszmedon.app.mobileappws.service.AddressService; import com.mateuszmedon.app.mobileappws.service.UserService; import com.mateuszmedon.app.mobileappws.shared.dto.AddressDto; import com.mateuszmedon.app.mobileappws.shared.dto.UserDto; import com.mateuszmedon.app.mobileappws.ui.model.request.PasswordResetModel; import com.mateuszmedon.app.mobileappws.ui.model.request.PasswordResetRequestModel; import com.mateuszmedon.app.mobileappws.ui.model.request.UserDetailsRequestModel; import com.mateuszmedon.app.mobileappws.ui.model.response.*; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*; @RestController @RequestMapping("/users") public class UserController { @Autowired UserService userService; @Autowired AddressService addressService; @GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public UserRest getUser(@PathVariable String id) { UserRest returnValue = new UserRest(); UserDto userDto = userService.getUserByUserId(id); ModelMapper modelMapper = new ModelMapper(); returnValue = modelMapper.map(userDto, UserRest.class); return returnValue; } @PostMapping( consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public UserRest createUser(@RequestBody UserDetailsRequestModel userDetails) { UserRest returnValue = new UserRest(); // if(userDetails.getFirstName().isEmpty()) throw new NullPointerException("Hej joe"); // UserDto userDto = new UserDto(); // BeanUtils.copyProperties(userDetails, userDto); // Use a ModelMapper to create object instance of conversion class ModelMapper modelMapper = new ModelMapper(); UserDto userDto = modelMapper.map(userDetails, UserDto.class); UserDto createdUser = userService.createUser(userDto); returnValue = modelMapper.map(createdUser, UserRest.class); return returnValue; } @PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public UserRest updateUser(@PathVariable String id, @RequestBody UserDetailsRequestModel userDetails) { UserRest returnValue = new UserRest(); ModelMapper modelMapper = new ModelMapper(); UserDto userDto = modelMapper.map(userDetails, UserDto.class); UserDto updateUser = userService.updateUser(id, userDto); returnValue = modelMapper.map(updateUser, UserRest.class); return returnValue; } @DeleteMapping(path = "/{id}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public OperationStatusModel deleteUser(@PathVariable String id) { OperationStatusModel returnValue = new OperationStatusModel(); returnValue.setOperationName(RequestOperationName.DELETE.name()); userService.deleteUser(id); returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); return returnValue; } @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public List<UserRest> getUsers(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit) { List<UserRest> returnValue = new ArrayList<>(); // TODO: refactor by modelMapper if (page > 0) page -= 1; List<UserDto> users = userService.getUsers(page, limit); for (UserDto userDto : users) { UserRest userModel = new UserRest(); BeanUtils.copyProperties(userDto, userModel); returnValue.add(userModel); } return returnValue; } // http://localhost:8080/mobile-app-ws/users/fgfdgdf/addresses @GetMapping(path = "/{id}/addresses", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "application/hal+json"}) public CollectionModel<AddressesRest> getUserAddresses(@PathVariable String id) { List<AddressesRest> addressesListRestModel = new ArrayList<>(); List<AddressDto> addressDto = addressService.getAddresses(id); if (addressDto != null && !addressDto.isEmpty()) { Type listType = new TypeToken<List<AddressesRest>>() { }.getType(); addressesListRestModel = new ModelMapper().map(addressDto, listType); for (AddressesRest addressRest : addressesListRestModel) { Link addressLink = linkTo(methodOn(UserController.class).getUserAddress(id, addressRest.getAddressId())) .withSelfRel(); addressRest.add(addressLink); Link userLink = linkTo(methodOn(UserController.class).getUser(id)).withRel("user"); addressRest.add(userLink); } } return new CollectionModel<>(addressesListRestModel); } @GetMapping(path = "/{userId}/addresses/{addressId}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "application/hal+json"}) public EntityModel getUserAddress(@PathVariable String addressId, @PathVariable String userId) { AddressDto addressDto = addressService.getAddress(addressId); ModelMapper modelMapper = new ModelMapper(); Link addressLink = linkTo(methodOn(UserController.class).getUserAddress(addressId, userId)).withSelfRel(); Link userLink = linkTo(UserController.class).slash(userId).withRel("user"); Link addressesLink = linkTo(methodOn(UserController.class).getUserAddresses(userId)).withRel("addresses"); AddressesRest addressesRestModel = modelMapper.map(addressDto, AddressesRest.class); addressesRestModel.add(addressLink); addressesRestModel.add(userLink); addressesRestModel.add(addressesLink); return new EntityModel(addressesRestModel); } /* * http://localhost:8080/mobile-app-ws/users/email-verification?token=sdfsdf * */ @GetMapping(path = "/email-verification", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public OperationStatusModel verifyEmailToken(@RequestParam(value = "token") String token) { OperationStatusModel returnValue = new OperationStatusModel(); returnValue.setOperationName(RequestOperationName.VERIFY_EMAIL.name()); boolean isVerified = userService.verifyEmailToken(token); if (isVerified) { returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); } else { returnValue.setOperationResult(RequestOperationStatus.ERROR.name()); } return returnValue; } /* * http://localhost:8080/mobile-app-ws/users/password-reset-request * */ @PostMapping(path = "/password-reset-request", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} ) public OperationStatusModel requestReset(@RequestBody PasswordResetRequestModel passwordResetRequestModel) { OperationStatusModel returnValue = new OperationStatusModel(); boolean operationResult = userService.requestPasswordReset(passwordResetRequestModel.getEmail()); returnValue.setOperationName(RequestOperationName.REQUEST_PASSWORD_RESET.name()); returnValue.setOperationResult(RequestOperationStatus.ERROR.name()); if(operationResult) { returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); } return returnValue; } @PostMapping(path = "/password-reset", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} ) public OperationStatusModel resetPassword(@RequestBody PasswordResetModel passwordResetModel) { OperationStatusModel returnValue = new OperationStatusModel(); boolean operationResult = userService.resetPassword( passwordResetModel.getToken(), passwordResetModel.getPassword()); returnValue.setOperationName(RequestOperationName.PASSWORD_RESET.name()); returnValue.setOperationResult(RequestOperationStatus.ERROR.name()); if(operationResult) { returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); } return returnValue; } }
package com.paya.paragon import android.annotation.SuppressLint import android.app.Application import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.iid.FirebaseInstanceId import com.paya.paragon.di.networkModule import com.paya.paragon.di.viewModelModule import com.paya.paragon.utilities.SessionManager import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level import timber.log.Timber class PayaAppClass : Application() { @SuppressLint("HardwareIds") override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } payaAppInstance = this try { FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult -> val token = instanceIdResult.token SessionManager.setDeviceTokenForFCM(payaAppInstance, token) } } catch (e: Exception) { FirebaseCrashlytics.getInstance().recordException(e) } startKoin { androidContext(this@PayaAppClass) androidLogger(Level.DEBUG) modules( listOf( networkModule, viewModelModule, ) ) } } companion object { var payaAppInstance: PayaAppClass? = null @JvmStatic fun getAppInstance(): PayaAppClass? { if (payaAppInstance == null) { payaAppInstance = PayaAppClass() } return payaAppInstance } } }
import { Button, Checkbox, Form, Input, Modal, Space, Table, message, } from "antd"; import { Fragment, useEffect, useState } from "react"; import { request } from "../server"; import { Link } from "react-router-dom"; const TeachersPage = () => { const columns = [ { title: "FirstName", dataIndex: "firstName", key: "firstName", render: (text) => <a>{text}</a>, }, { title: "LastName", dataIndex: "lastName", key: "lastName", }, { title: "Image", dataIndex: "avatar", key: "avatar", render: (data) => <img height={50} src={data} />, }, { title: "IsMarried", key: "isMarried", dataIndex: "isMarried", render: (data) => (data ? "Yes" : "No"), }, { title: "Action", key: "action", render: (_, record) => { // console.log(record); // console.log(); return ( <Space size="middle" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", }} > <Button type="primary" onClick={() => editData(record.id)}> Edit </Button> <Button danger type="primary" onClick={() => deleteData(record.id)}> Delete </Button> <Link type="primary" to={`/categories/${record.id}`}> New students ({record.id}) </Link> </Space> ); }, }, ]; const [form] = Form.useForm(); const [data, setData] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); const [selected, setSelected] = useState(null); const [loading, setLoading] = useState(false); const [loadingBtn, setLoadingBtn] = useState(false); useEffect(() => { getData(); }, []); async function getData() { try { setLoading(true); let { data } = await request.get("/categories"); setData(data); } catch (err) { message.error(err); } finally { setLoading(false); } } const showModal = () => { setSelected(null); setIsModalOpen(true); form.resetFields(); }; const handleOk = async () => { try { setLoadingBtn(true); const values = await form.validateFields(); if (selected === null) { await request.post("/categories", values); } else { await request.put(`/categories/${selected}`, values); } getData(); setIsModalOpen(false); } catch (error) { console.log(error); } finally { setLoadingBtn(false); } }; const handleCancel = () => { setIsModalOpen(false); }; const editData = async (id) => { setSelected(id); setIsModalOpen(true); let { data } = await request.get(`/categories/${id}`); form.setFieldsValue(data); }; const deleteData = async (id) => { const con = confirm("Delete"); if (con) { await request.delete(`/categories/${id}`); getData(); } }; return ( <Fragment> <Table loading={loading} bordered title={() => ( <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", }} > <h1>Teachers ({data.length})</h1> <Button onClick={showModal} type="primary"> Add </Button> </div> )} dataSource={data} columns={columns} /> <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText={selected === null ? "Add teacher" : "Save teacher"} confirmLoading={loadingBtn} > <Form form={form} name="login" labelCol={{ span: 24, }} wrapperCol={{ span: 24, }} style={{ maxWidth: 600, }} // onFinish={onFinish} // onFinishFailed={onFinishFailed} autoComplete="off" > <Form.Item label="FirstName" name="firstName" rules={[ { required: true, message: "Please fill!", }, ]} > <Input /> </Form.Item> <Form.Item label="LastName" name="lastName" rules={[ { required: true, message: "Please fill!", }, ]} > <Input /> </Form.Item> <Form.Item label="Image" name="avatar" rules={[ { required: true, message: "Please fill!", }, ]} > <Input /> </Form.Item> <Form.Item name="isMarried" wrapperCol={{ span: 24, }} valuePropName="checked" > <Checkbox>IsMarried</Checkbox> </Form.Item> </Form> </Modal> </Fragment> ); }; export default TeachersPage;
'use client'; import { useEffect, useState } from 'react'; import Link from 'next/link' export default function QueryTxSetTokenConfig() { const [queryFunctionResults, setQFR] = useState<any[]>([]); useEffect(() => { queryFunction('0x3c5a6e35'); }, []); const queryFunction = async (req: String) => { const res = ((await fetch(`/api/queryTransactions?method=${req}`)).json()); setQFR(await res || []); } if (queryFunctionResults.length > 0) { return ( <main className="container mx-auto px-4 py-8"> <h2 className="text-2xl font-semibold mb-4">setTokenConfig() Logs</h2> <h2 className="text-2xl mb-4">This is querying through Transaction History of the vault contract (0x489ee077994B6658eAfA855C308275EAd8097C4A)</h2> <ul className="space-y-4"> {queryFunctionResults.map((transaction, index) => ( <li key={index} className="bg-white p-4 shadow-md"> <div> <strong>Transaction Hash: </strong><Link className="text-blue-500 underline" target="_blank" rel="noopener noreferrer" href={`https://arbiscan.io/tx/${transaction[0].hash}`}>{transaction[0].hash}</Link> </div> <div> <strong>From:</strong> {transaction[0].from} </div> <div> <strong>To:</strong> {transaction[0].to} </div> <div> <strong >Encoded Data:</strong> <pre style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}> {transaction[0].data} </pre> </div> <div> <strong>Decoded Raw JSON:</strong>{transaction[1]} </div> <div> <strong className='text-xl'>Parsed Decoded Data</strong> </div> <div> {transaction[2].method} ( {transaction[2].types[0] + transaction[2].names[0]}, {transaction[2].types[1] + transaction[2].names[1]}, {transaction[2].types[2] + transaction[2].names[2]}, {transaction[2].types[3] + transaction[2].names[3]}, {transaction[2].types[4] + transaction[2].names[4]}, {transaction[2].types[5] + transaction[2].names[5]}, {transaction[2].types[6] + transaction[2].names[6]} ) </div> <div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Data</th> </tr> </thead> <tbody> <tr> <td>{transaction[2].names[0]}</td> <td>{transaction[2].types[0]}</td> <td><Link className="text-blue-500 underline" target="_blank" rel="noopener noreferrer" href={`https://arbiscan.io/address/0x${transaction[2].inputs[0]}`}>0x{transaction[2].inputs[0]}</Link></td> </tr> <tr> <td>{transaction[2].names[1]}</td> <td>{transaction[2].types[1]}</td> <td>{parseInt(transaction[2].inputs[1].hex, 16)}</td> </tr> <tr> <td>{transaction[2].names[2]}</td> <td>{transaction[2].types[2]}</td> <td>{parseInt(transaction[2].inputs[2].hex, 16)}</td> </tr> <tr> <td>{transaction[2].names[3]}</td> <td>{transaction[2].types[3]}</td> <td>{parseInt(transaction[2].inputs[3].hex, 16)}</td> </tr> <tr> <td>{transaction[2].names[4]}</td> <td>{transaction[2].types[4]}</td> <td>{parseInt(transaction[2].inputs[4].hex, 16)}</td> </tr> <tr> <td>{transaction[2].names[5]}</td> <td>{transaction[2].types[5]}</td> <td>{transaction[2].inputs[5].toString()}</td> </tr> <tr> <td>{transaction[2].names[6]}</td> <td>{transaction[2].types[6]}</td> <td>{transaction[2].inputs[6].toString()}</td> </tr> </tbody> </table> </div> </li> ))} </ul> </main> ) } else if (!queryFunctionResults) { return ( <main className="container mx-auto px-4 py-8"> <h2 className="text-2xl font-semibold mb-4">Loading Queries</h2> </main> ) } }
import { useContext, useEffect, useState } from 'react' import { View, Text, ActivityIndicator } from 'react-native' import ChatList from '../../components/ChatList' import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen' import { AuthContext } from '../../context/authContext' import { getDocs, query, where } from 'firebase/firestore' import { usersRef } from '../../firebaseConfig' export default function Home() { const [users, setUsers] = useState([1, 2, 3]) const { values } = useContext(AuthContext) useEffect(() => { if (values?.user?.userId) { getUsers() } }, [values?.user?.userId]) const getUsers = async () => { const q = query(usersRef, where("userId", "!=", values?.user?.userId)) const querySnapShot = await getDocs(q) let data = [] querySnapShot.forEach(doc => { data.push({ ...doc.data() }) }) setUsers(data) } return ( <View className="flex-1 bg-white"> { users.length > 0 ? <ChatList data={users} /> : <View className="flex justify-center items-center" style={{ top: hp(40) }}> <ActivityIndicator size={"large"} /> </View> } </View> ) }
// Copyright 2024 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VISITED_URL_RANKING_PUBLIC_URL_VISIT_H_ #define COMPONENTS_VISITED_URL_RANKING_PUBLIC_URL_VISIT_H_ #include <memory> #include <optional> #include <set> #include <string> #include <variant> #include <vector> #include "base/functional/callback.h" #include "base/time/time.h" #include "components/history/core/browser/history_types.h" #include "components/history/core/browser/url_row.h" #include "components/segmentation_platform/public/trigger.h" #include "components/sync_device_info/device_info.h" #include "url/gurl.h" namespace visited_url_ranking { // The currently supported URL visit data fetchers that may participate in a // fetch request. enum class Fetcher { kTabModel = 0, kSession = 1, kHistory = 2, }; // URL visit associated data. struct URLVisit { // If applicable, whether the visit data was sourced from a specific origin // (local or remote). enum class Source { kNotApplicable = 0, kLocal = 1, kForeign = 2 }; URLVisit(const GURL& url_arg, const std::u16string& title_arg, const base::Time& last_modified_arg, syncer::DeviceInfo::FormFactor device_type_arg, Source source_arg); URLVisit(const URLVisit&); ~URLVisit(); // The page URL associated with the data. GURL url; // The page title of the URL. std::u16string title; // Timestamp for when the URL was last modified (e.g.: When a page reloads // or there is a favicon change). base::Time last_modified; // The device form factor in which the visit took place. syncer::DeviceInfo::FormFactor device_type = syncer::DeviceInfo::FormFactor::kUnknown; // The source from which the visit originated (i.e. local or remote). Source source = Source::kNotApplicable; }; /** * A wrapper data type that encompasses URL visit related data from various * sources. */ struct URLVisitAggregate { // Captures tab data associated with a given URL visit. struct Tab { Tab(int32_t id_arg, URLVisit visit_arg, std::optional<std::string> session_tag_arg = std::nullopt, std::optional<std::string> session_name_arg = std::nullopt); Tab(const Tab&); ~Tab(); // A unique tab identifier. int32_t id = -1; // Associated URL visit data. URLVisit visit; // The tab's unique session tag, if applicable. std::optional<std::string> session_tag; // The tab's user visible session name, if applicable. std::optional<std::string> session_name; }; // Captures aggregate tab data associated with a URL visit for a given time // period. struct TabData { explicit TabData(Tab last_active_tab_arg); TabData(const TabData&); ~TabData(); // The last active tab associated with a given URL visit. Tab last_active_tab; // Timestamp for when a tab associated with the given URL visit was last // activated. base::Time last_active; // Whether there is a tab for the given URL visit that is pinned. bool pinned = false; // Whether there is a tab for the given URL visit that is part of a group. bool in_group = false; // The number of opened tabs for the given URL visit aggregate in a time // period. size_t tab_count = 1; }; struct HistoryData { explicit HistoryData(history::AnnotatedVisit annotated_visit); HistoryData(const HistoryData&) = delete; HistoryData(HistoryData&& other); HistoryData& operator=(HistoryData&& other); ~HistoryData(); // The last annotated visit associated with the given URL visit in a given // time period. history::AnnotatedVisit last_visited; // The last `app_id` value if any for any of the visits associated with the // URL visit aggregate. std::optional<std::string> last_app_id = std::nullopt; // Whether any of the annotated visits for the given URL visit aggregate are // part of a cluster. bool in_cluster = false; // The total duration in the foreground for all visits associated with the // aggregate in a time period. base::TimeDelta total_foreground_duration = base::Seconds(0); // The number of history visits associated with the URL visit aggregate in a // time period. size_t visit_count = 1; }; explicit URLVisitAggregate(std::string key_arg); URLVisitAggregate(const URLVisitAggregate&) = delete; URLVisitAggregate(URLVisitAggregate&& other); URLVisitAggregate& operator=(URLVisitAggregate&& other); ~URLVisitAggregate(); // A unique identifier that maps to a collection of associated URL visits. // Computed via a merging and deduplication strategy and used to record events // associated with the URL visit aggregate. std::string url_key; // An ID used to collect metrics associated with the aggregate visit for model // training purposes. See `VisitedURLRankingService::RecordAction` for more // details. segmentation_platform::TrainingRequestId request_id; // Returns a set of associated visit URLs present in the data provided by the // various fetchers that participated in constructing the aggregate object. std::set<const GURL*> GetAssociatedURLs() const; // A map of aggregate tab related characteristics associated with the visit as // provided by a given source. using URLVisitVariant = std::variant<URLVisitAggregate::TabData, URLVisitAggregate::HistoryData>; std::map<Fetcher, URLVisitVariant> fetcher_data_map; // Whether the visit is bookmarked or not. bool bookmarked = false; // The number of times the visits associated with the aggregate where on the // foreground. size_t num_times_active = 0; // A score associated with the aggregate, if any. std::optional<float> score = std::nullopt; }; // Helper to visit each variant of URLVisitVariant. // Usage: // std::visit(URLVisitVariantHelper{ // [](Variant1& variant1) {}, // [](Variant2& variant1) {}, // [](Variant3& variant1) {}, // variant_data); template <class... Ts> struct URLVisitVariantHelper : Ts... { using Ts::operator()...; }; } // namespace visited_url_ranking #endif // COMPONENTS_VISITED_URL_RANKING_PUBLIC_URL_VISIT_H_
import React, { Component } from 'react'; import { Text, View, ScrollView, StyleSheet, Picker, Switch, Button, Alert } from 'react-native'; import { Card } from 'react-native-elements'; import DatePicker from 'react-native-datepicker'; import * as Animatable from 'react-native-animatable'; import { Notifications } from 'expo'; import * as Permissions from 'expo-permissions'; import * as Calendar from 'expo-calendar'; class Reservation extends Component { constructor(props) { super(props); this.state = { guests: 1, smoking: false, date: '', } } static navigationOptions = { title: 'Reserve Table' } handleReservation() { Alert.alert( 'Your Reservation OK?', 'Number of Guests: ' + this.state.guests + '\n' + 'Smoking? ' + this.state.smoking + '\n' + 'Date and Time: ' + this.state.date , [ { text: 'Cancel', onPress: () => this.resetForm(), style: ' cancel' }, { text: 'Ok', onPress: () => { this.addReservationToCalendar(this.state.date); this.presentLocalNotification(this.state.date); this.resetForm(); } }, { cancelable: false } ] ); } async obtainCalendarPermission() { let permission = await Permissions.getAsync(Permissions.CALENDAR); if (permission.status !== 'granted') { permission = await Permissions.askAsync(Permissions.CALENDAR); if (permission.status !== 'granted') { Alert.alert('Permission not granted to use calendar'); } } return permission; } async getDefaultCalendarId() { const calendars = await Calendar.getCalendarsAsync(); const defaultCalendars = calendars.filter(each => each.source.name === 'Default'); return defaultCalendars[0].id; } async addReservationToCalendar(date) { await this.obtainCalendarPermission(); console.log("Date: " + date); const calendars = await Calendar.getCalendarsAsync(); console.log('Here are all your calendars:'); console.log({ calendars }); const defaultCalendarId = await this.getDefaultCalendarId(); console.log("Calendar Id: " + defaultCalendarId); Calendar.createEventAsync(defaultCalendarId, { title: 'Con Fusion Table Reservation', startDate: new Date(Date.parse(date)), endDate: new Date(Date.parse(date) + (2*60*60*1000)), timeZone: 'Asia/Hong_Kong', location: '121, Clear Water Bay Road, Clear Water Bay, Kowloon, Hong Kong' }); } resetForm() { this.setState({ guests: 1, smoking: false, date: '' }); } async obtainNotificationPermission() { let permission = await Permissions.getAsync(Permissions.USER_FACING_NOTIFICATIONS); if (permission.status !== 'granted') { permission = await Permissions.askAsync(Permissions.USER_FACING_NOTIFICATIONS); if (permission.status !== 'granted') { Alert.alert('Permission not granted to show notifications'); } } return permission; } async presentLocalNotification(date) { await this.obtainNotificationPermission(); Notifications.presentLocalNotificationAsync({ title: 'Your Reservation', body: 'Reservation for '+ date + ' requested', ios: { sound: true, _displayInForeground: true }, android: { sound: true, vibrate: true, color: '#512DA8', sticky: true } }); } render() { return( <ScrollView> <Animatable.View animation="zoomIn" duration={2000}> <View style={styles.formRow}> <Text style={styles.formLabel}>Number of Guests</Text> <Picker style={styles.formItem} selectedValue={this.state.guests} onValueChange={(itemValue, itemIndex) => this.setState({ guests: itemValue })} > <Picker.Item label='1' value='1' /> <Picker.Item label='2' value='2' /> <Picker.Item label='3' value='3' /> <Picker.Item label='4' value='4' /> <Picker.Item label='5' value='5' /> <Picker.Item label='6' value='6' /> </Picker> </View> <View style={styles.formRow}> <Text style={styles.formLabel}>Smoking/Non-Smoking?</Text> <Switch style={styles.formItem} value={this.state.smoking} trackColor='#512DA8' onValueChange={(value) => this.setState({ smoking: value })} > </Switch> </View> <View style={styles.formRow}> <Text style={styles.formLabel}>Date and Time</Text> <DatePicker style={{flex: 2, marginRight: 20 }} date={this.state.date} format='' mode='datetime' placeholder='select date and time' minDate='2017-01-01' confirmBtnText='Confirm' cancelBtnText='Cancel' customStyles={{ dateIcon: { position: 'absolute', left: 0, top: 4, marginLeft: 0 }, dateInput: { marginLeft: 36 } }} onDateChange={(date) => {this.setState({ date: date })}} /> </View> <View style={styles.formRow}> <Button title='Reserve' color='#512DA8' onPress={() => this.handleReservation()} accessibilityLabel='Learn more about this purple button' /> </View> </Animatable.View> </ScrollView> ); } } const styles = StyleSheet.create({ formRow: { alignItems: 'center', justifyContent: 'center', flex: 1, flexDirection: 'row', margin: 20 }, formLabel: { fontSize: 18, flex: 2 }, formItem: { flex: 1 } }); export default Reservation;
package gitlet; import java.io.File; import java.util.ArrayList; import java.util.Set; import java.util.Collections; import java.util.List; public class DoCommands { public static void doInit() { Stage theStage = new Stage(); Remove theRemoval = new Remove(); File gitletDir = new File(".gitlet"); File stagingDir = new File(".gitlet/staging"); File objectsDir = new File(".gitlet/objects"); File branchesDir = new File(".gitlet/branches"); gitletDir.mkdir(); stagingDir.mkdir(); objectsDir.mkdir(); branchesDir.mkdir(); Commit firstCommit = new Commit("initial commit", "", true); String commitId = "c" + Utils.sha1(Utils.serialize(firstCommit)); String branchPath = ".gitlet/branches"; Utils.writeObject(Utils.join(".gitlet/objects", commitId), firstCommit); Utils.writeContents(Utils.join(branchPath, "master"), commitId); String masterPath = ".gitlet/branches/master"; Utils.writeContents(Utils.join(".gitlet", "HEAD"), masterPath); Utils.writeObject(Utils.join(stagingDir, "stages"), theStage); Utils.writeObject(Utils.join(stagingDir, "removal"), theRemoval); } /** Replacement for the add command which was buggy. * Takes in a file, checks to see if that file is in the * current commit, if it is then we cannot add it in. * If it isnt then we add it into the staging area so that * in the commit class it is added to the next commit permananetly. * @param fileName --represents the name of the file being passed * in that we have to add. */ public static void theOtherAdd(String fileName) { Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging/stages"), Stage.class); Remove theRemoval = Utils.readObject(Utils.join( ".gitlet/staging/removal"), Remove.class); String currCommitPath = Utils.readContentsAsString(Utils.join( ".gitlet/HEAD")); String currCommitId = Utils.readContentsAsString(Utils.join( currCommitPath)); Commit currCommit = Utils.readObject(Utils.join( ".gitlet/objects", currCommitId), Commit.class); if (!Utils.join(fileName).exists()) { System.out.println("File does not exist."); return; } File potentialAdd = new File(fileName); Blob fileBlobbed = new Blob(potentialAdd); if (theStage.containsKey(fileName)) { String blobSha = theStage.get(fileName); if (!blobSha.equals(fileBlobbed.getBlobCode())) { theStage.replace(fileName, fileBlobbed.getBlobCode()); Utils.writeObject(Utils.join( ".gitlet/objects", fileBlobbed.getBlobCode()), fileBlobbed); } } else { theStage.put(fileName, fileBlobbed.getBlobCode()); Utils.writeObject(Utils.join( ".gitlet/objects", fileBlobbed.getBlobCode()), fileBlobbed); } if (theRemoval.containsValue(fileName)) { if (theStage.containsKey(fileName)) { theRemoval.remove(fileName); } } if (currCommit.containsKey(fileName)) { String commitsBlobSha = currCommit.get(fileName); if (commitsBlobSha.equals(fileBlobbed.getBlobCode())) { if (theStage.containsValue(commitsBlobSha)) { theStage.remove(fileName); } } } Utils.writeObject(Utils.join( ".gitlet/staging/stages"), theStage); Utils.writeObject(Utils.join( ".gitlet/staging", "removal"), theRemoval); } /** Add method which takes in a string file name to * add, then it puts it in the staging area to * be added in the next commit. * @param addFile - file name to add into the next commit. */ public static void doAdd(String addFile) { Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging/stages"), Stage.class); Remove theRemoval = Utils.readObject(Utils.join( ".gitlet/staging", "removal"), Remove.class); if (theRemoval.containsValue(addFile)) { theRemoval.remove(addFile); } String filePassed = addFile; File file = new File(filePassed); if (file.exists()) { Blob fileBlobbed = new Blob(file); String blobFileName = fileBlobbed.getFileName(); String newSha1 = fileBlobbed.getBlobCode(); if (theStage.containsKey(blobFileName)) { String stagedBlobSha = theStage.get(blobFileName); if (!stagedBlobSha.equals(newSha1)) { theStage.replace(blobFileName, newSha1); if (!Utils.join(".gitlet/objects", newSha1).exists()) { Utils.writeObject(Utils.join( ".gitlet/objects", newSha1), fileBlobbed); } } } else { theStage.put(blobFileName, newSha1); if (!Utils.join(".gitlet/objects", newSha1).exists()) { Utils.writeObject(Utils.join( ".gitlet/objects", newSha1), fileBlobbed); } } String currCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currCommitCode = Utils.readContentsAsString( Utils.join(currCommitCodePath)); Commit currCommit = Utils.readObject( Utils.join(".gitlet/objects", currCommitCode), Commit.class); if (currCommit.containsValue(newSha1)) { if (theStage.containsKey(blobFileName)) { theStage.remove(blobFileName); } } Utils.writeObject(Utils.join( ".gitlet/staging", "stages"), theStage); Utils.writeObject(Utils.join( ".gitlet/staging", "removal"), theRemoval); } else { System.out.print("File does not exist."); return; } } /** Commit method that takes in an argument args * where the first element is the message that * is passed in by the user and that is all there * is inside of it. * @param args - message passed in by the user. */ public static void doCommit(String... args) { String message = args[0]; String commitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String parentCode = Utils.readContentsAsString( Utils.join(commitCodePath)); Commit parent = Utils.readObject(Utils.join( ".gitlet/objects", parentCode), Commit.class); Commit current = new Commit(message, parentCode, ""); Remove theRemoval = Utils.readObject( Utils.join(".gitlet/staging", "removal"), Remove.class); Stage theStage = Utils.readObject( Utils.join(".gitlet/staging", "stages"), Stage.class); if (theStage.getStage().size() == 0 && theRemoval.getList().size() == 0) { System.out.println("No changes added to the commit."); return; } Set<String> parentBlobs = parent.getSavedBlobs().keySet(); for (String blobName : parentBlobs) { String blobSha1 = parent.getValue(blobName); current.put(blobName, blobSha1); } Set<String> stageFileNames = theStage.getStage().keySet(); for (String stagedFile : stageFileNames) { if (current.containsKey(stagedFile)) { String stagedFileSha1 = theStage.get(stagedFile); if (!current.get(stagedFile).equals(stagedFileSha1)) { current.remove(stagedFile); current.put(stagedFile, theStage.get(stagedFile)); } } else { current.put(stagedFile, theStage.get(stagedFile)); } } theStage.clear(); for (String toBeRemoved : theRemoval.getList()) { if (current.containsKey(toBeRemoved)) { current.remove(toBeRemoved); } } theRemoval.clear(); String newCommitCode = "c" + Utils.sha1(Utils.serialize(current)); Utils.writeObject(Utils.join( ".gitlet/staging", "removal"), theRemoval); Utils.writeObject(Utils.join( ".gitlet/staging/stages"), theStage); Utils.writeObject(Utils.join( ".gitlet/objects", newCommitCode), current); Utils.writeContents(Utils.join( commitCodePath), newCommitCode); Utils.writeContents(Utils.join( ".gitlet/HEAD"), commitCodePath); } /** Method that is used to remove files from the current working * direcotry. Also removes them from the staging area if need be * @param args */ public static void doRemove(String... args) { String theFileName = args[1]; Remove theRemoval = Utils.readObject(Utils.join( ".gitlet/staging/removal"), Remove.class); String currCommitPath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currCommitCode = Utils.readContentsAsString( Utils.join(currCommitPath)); Commit currentCommit = Utils.readObject(Utils.join( ".gitlet/objects", currCommitCode), Commit.class); Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging/stages"), Stage.class); boolean anythingRemoved; anythingRemoved = false; File tempFile = new File(theFileName); if (theStage.containsKey(theFileName) || currentCommit.containsKey(theFileName)) { if (theStage.containsKey(theFileName)) { theStage.remove(theFileName); anythingRemoved = true; } if (isTracked(theFileName)) { theRemoval.add(theFileName); Utils.restrictedDelete(Utils.join(theFileName)); } else { if (!anythingRemoved) { System.out.println("No reason to remove the file."); } } } else { System.out.println("No reason to remove the file."); } Utils.writeObject(Utils.join( ".gitlet/staging", "stages"), theStage); Utils.writeObject(Utils.join( ".gitlet/staging", "removal"), theRemoval); } /** Helper method to see if a paramater file is tracked. * Built off of the idea that a file that is slightly changed * is not tracked anymore, that when its contents are changed, * it is no longer tracked. If that idea is wrong then this * method is wrong. * @param name - the name of the file being passed in as a String * @return true if the file is being currently being tracked. */ public static boolean isTracked(String name) { String currCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currCommitCode = Utils.readContentsAsString( Utils.join(currCommitCodePath)); Commit currentCommit = Utils.readObject(Utils.join( ".gitlet/objects", currCommitCode), Commit.class); if (currentCommit.containsKey(name)) { return true; } return false; } /** Method that starts off by printing the current commit, and continues * to print all of the parents in this branch. * First commit will be the closest to the bottom while our most * recent commit will be at the top because it was the first printed. * Calls on the print method from our Commit class. */ public static void log() { String currCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currCommitCode = Utils.readContentsAsString( Utils.join(currCommitCodePath)); String commitPath = ".gitlet/objects"; while (Utils.join(commitPath, currCommitCode).exists()) { File testPath = Utils.join(commitPath, currCommitCode); Commit temp = Utils.readObject(testPath, Commit.class); System.out.println("==="); System.out.println("commit " + currCommitCode); System.out.println("Date: " + temp.getTimeTester()); System.out.println(temp.getMessage()); System.out.println(); currCommitCode = temp.getParent(); if (currCommitCode.equals("")) { return; } } } /** Resets all of the files in one commit to the files * in the given commit. It is quite dangerous, * almost acts as the checkout branch. * @param args */ public static void reset(String... args) { String commitId = args[1]; String objectPath = ".gitlet/objects"; if (!Utils.join(objectPath, commitId).exists()) { System.out.println("No commit with that id exists."); return; } File cwd = new File(System.getProperty("user.dir")); List<String> currentWorkingFiles = Utils.plainFilenamesIn(cwd); for (String file : currentWorkingFiles) { if (!isTracked(file)) { System.out.println( "There is an untracked file in the way; " + "delete it, or add and commit it first."); } } Commit givenCommit = Utils.readObject( Utils.join(objectPath, commitId), Commit.class); for (String file : currentWorkingFiles) { if (!givenCommit.containsKey(file)) { Utils.restrictedDelete(file); } else { String[] arguments = {"checkout", commitId, "--", file}; checkOut(arguments); } } Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging", "stages"), Stage.class); theStage.clear(); Utils.writeObject(Utils.join(".gitlet/staging/stages"), theStage); String otherIdea = ".gitlet/branches/" + commitId + "/"; Utils.writeContents(Utils.join(otherIdea), commitId); Utils.writeContents(Utils.join(".gitlet", "HEAD"), ".gitlet/branches/" + commitId); } /** Method that checks out to either the givnen file of the * current commit, the file of a previous commit, * or checks out all of the files to a given branch. * @param args - a set of either commits, files, or branches. */ public static void checkOut(String... args) { if (args.length == 3) { if (args[1].equals("--")) { String fileName = args[2]; File cwdFile = new File(fileName); Blob fileBlobbed = new Blob(cwdFile); String currentCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currentCommitCode = Utils.readContentsAsString( Utils.join(currentCommitCodePath)); Commit currCommit = Utils.readObject( Utils.join(".gitlet/objects", currentCommitCode), Commit.class); if (currCommit.containsKey(fileName)) { String currBlobId = currCommit.get(fileName); if (!currBlobId.equals(fileBlobbed.getBlobCode())) { Blob b = Utils.readObject(Utils.join( ".gitlet/objects", currBlobId), Blob.class); Utils.writeContents(cwdFile, b.getBlobContents()); } } else { System.out.println("File does not exist in that commit."); return; } } else { System.out.println("Incorrect Operands."); return; } } else if (args.length == 4) { if (args[2].equals("--")) { String commitId = args[1]; String fileName = args[3]; if (!Utils.join(".gitlet/objects", commitId).exists()) { System.out.println("No commit with that id exists."); return; } Commit prevCommit = Utils.readObject(Utils.join( ".gitlet/objects", commitId), Commit.class); if (!prevCommit.containsKey(fileName)) { System.out.println("File does not exist in that commit."); return; } String prevBlobSha = prevCommit.get(fileName); Blob prevBlob = Utils.readObject(Utils.join(".gitlet/objects", prevBlobSha), Blob.class); Utils.writeContents(Utils.join(fileName), prevBlob.getBlobContents()); } else { System.out.println("Incorrect Operands."); } } else if (args.length == 2) { if (args[0].equals("checkout")) { bigCheckout(args); return; } } else { System.out.println("Incorrect Operands"); } } /** Second checkout that checks out to an entire branch * with its paramaters being a branch name. * @param args a branch name. */ public static void bigCheckout(String... args) { String loneBranch = args[1]; String givenBranch = ".gitlet/branches/" + loneBranch; String currBranch = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); if (!Utils.join(givenBranch).exists()) { System.out.println("No such branch exists."); return; } if (givenBranch.equals(currBranch)) { System.out.println("No need to checkout the current branch."); return; } String givenCommitCode = Utils.readContentsAsString( Utils.join(givenBranch)); Commit givenCommit = Utils.readObject(Utils.join( ".gitlet/objects", givenCommitCode), Commit.class); for (String cwdFileName : Utils.plainFilenamesIn( System.getProperty("user.dir"))) { if (!isTracked(cwdFileName)) { System.out.println("There is an untracked file in the way; " + "delete it, or add and commit it first."); return; } else if (!givenCommit.containsKey(cwdFileName)) { Utils.restrictedDelete(Utils.join( System.getProperty("user.dir"), cwdFileName)); } else { String givenBlobCode = givenCommit.get(cwdFileName); Blob prevBlob = Utils.readObject(Utils.join( ".gitlet/objects", givenBlobCode), Blob.class); Utils.writeContents(Utils.join( System.getProperty("user.dir"), cwdFileName), prevBlob.getBlobContents()); } } Utils.writeContents(Utils.join( ".gitlet", "HEAD"), givenBranch); Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging", "stages"), Stage.class); theStage.clear(); Utils.writeObject(Utils.join( ".gitlet/staging", "stages"), theStage); } /** Creates a new branch at the current branches location * and does not automaticall switch them. * @param args - branch name. */ public static void branch(String... args) { String newBranch = args[1]; String branchPath = ".gitlet/branches"; if (Utils.join(branchPath, newBranch).exists()) { System.out.println( "A branch with that name already exists"); return; } else { String currentCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet/HEAD")); String currentCommitId = Utils.readContentsAsString( Utils.join(currentCommitCodePath)); Utils.writeContents(Utils.join(branchPath, newBranch), currentCommitId); } } /** Method that removes a given branch without * removing the commit that it holds. * @param args - the branch name that we are trying to remove. */ public static void rmBranch(String... args) { String branchToRemove = args[1]; String branchPath = ".gitlet/branches"; String headPath = Utils.readContentsAsString(Utils.join( ".gitlet", "HEAD")); String givenPath = ".gitlet/branches/" + branchToRemove; if (Utils.join(branchPath, branchToRemove).exists()) { if (givenPath.equals(headPath)) { System.out.println("Cannot remove the current branch."); } else { Utils.join(branchPath, branchToRemove).delete(); } } else { System.out.println( "A branch with that name does not exist."); } } /** Method that gives the status of our * current directory and takes in no paramaters. */ public static void status() { String currCommitCodePath = Utils.readContentsAsString( Utils.join(".gitlet", "HEAD")); String currCommitCode = Utils.readContentsAsString( Utils.join(currCommitCodePath)); List<String> allBranches = Utils.plainFilenamesIn( ".gitlet/branches"); System.out.println("=== Branches ==="); Collections.sort(allBranches); for (String branch : allBranches) { String branchPath = ".gitlet/branches/" + branch; if (branchPath.equals(currCommitCodePath)) { System.out.println("*" + branch); System.out.println(); } else { System.out.println(branch); System.out.println(); } } System.out.println("=== Staged Files ==="); Stage theStage = Utils.readObject(Utils.join( ".gitlet/staging", "stages"), Stage.class); List<String> files = new ArrayList<String>( theStage.getStage().keySet()); Collections.sort(files); for (String fileName : files) { System.out.println(fileName); } System.out.println(); System.out.println("=== Removed Files ==="); Remove theRemoval = Utils.readObject(Utils.join( ".gitlet/staging", "removal"), Remove.class); for (String removedFile : theRemoval.getList()) { System.out.println(removedFile); } System.out.println(); System.out.println( "=== Modifications Not Staged For Commit ==="); System.out.println(); System.out.println("=== Untracked Files ==="); } /** Same thing as log but only for all of the commits. */ public static void globalLog() { String objectPath = ".gitlet/objects"; List<String> allObjectsFile = Utils.plainFilenamesIn( objectPath); for (String objectSha : allObjectsFile) { if (objectSha.charAt(0) == ('c')) { Commit tempCommit = Utils.readObject( Utils.join(objectPath, objectSha), Commit.class); System.out.println("==="); System.out.println("commit " + objectSha); System.out.println("Date: " + tempCommit.getTimeTester()); System.out.println(tempCommit.getMessage()); System.out.println(); } } } /** finds all of the commits with whose message is the inputted message. * * @param args */ public static void find(String... args) { String message = args[1]; String objectsPath = ".gitlet/objects"; int counter = 0; List<String> allObjects = Utils.plainFilenamesIn(objectsPath); for (String objectShas : allObjects) { if (Utils.join(objectsPath, objectShas).exists()) { if (objectShas.charAt(0) == 'c') { Commit temp = Utils.readObject(Utils.join( objectsPath, objectShas), Commit.class); if (temp.getMessage().equals(message)) { System.out.println(objectShas); counter += 1; } } } } if (counter == 0) { System.out.println("Found no commit with that message."); } } }
from django.test import TestCase from django.core.urlresolvers import resolve from lists.views import home_page from django.test import Client from lists.forms import TaskForm from lists.models import Task class SimpleAdditionTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) class ModelMethodTest(TestCase): def setUp(self): self.task = Task.objects.create(Title = 'MyTask', Description = 'tasdescription', due_time = '2012-06-08 10:29:47') def test_method(self): t = Task.objects.get(Title = 'MyTask') self.assertEqual('June 08, 2012 10:29:47', t.get_readable_due_date()) class HomePageTest(TestCase): def test_root_url_to_home_page(self): home = resolve('/') self.assertEqual(home.func, home_page) class UrlTests(TestCase): def test_index_html_page(self): self.client = Client() response = self.client.get('/index/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response,'index.html') self.assertIn('MicroPyramid', response.content) # self.assertTrue(response.content.endswith(b'</html>')) class TaskFromTest(TestCase): def test_form_invalidate_with_dateformat(self): form = TaskForm(data = {'Title':'Build ToDo aplication','Description':'Create Read Update Delete', 'due_time':'2012/06/08 10:29:47'}) #self.assertFalse(form.is_valid()) def test_form_invalide(self): form = TaskForm(data = {'Title':'','Description':'', 'due_time':''}) self.assertFalse(form.is_valid()) def test_form_valid(self): form = TaskForm(data = {'Title':'Build ToDo aplication','Description':'Create Read Update Delete', 'due_time':'2012-06-08 10:29:47'}) self.assertTrue(form.is_valid()) class AddTaskViewsTest(TestCase): def setUp(self): self.client = Client() def test_add_task_html_page(self): response = self.client.get('/add-task/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed('addtask.html') self.assertIn('Title', response.content) self.assertIn('Description', response.content) self.assertIn('due_time', response.content) def test_add_task_with_empty_data(self): task_data = {} response = self.client.post('/add-task/', task_data) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'Title', 'This field is required.') self.assertFormError(response, 'form', 'Description', 'This field is required.') def test_add_task_with_incorect_data(self): task_data = {'Title':'My first task','Description':'My first task description', 'due_time':'2012/06/08 10:29:47'} response = self.client.post('/add-task/', task_data) #self.assertFormError(response, 'form', 'due_time', 'Enter a valid date/time.') def test_add_task_with_valid_data(self): tasks_count = Task.objects.count() self.assertEqual(tasks_count, 0) task_data = {'Title':'My first task','Description':'My first task description', 'due_time':'2012-06-08 10:29:47'} response = self.client.post('/add-task/', task_data) tasks_count = Task.objects.count() self.assertEqual(tasks_count, 1) self.assertEqual(response.status_code, 200) class ListEditTaskTest(TestCase): def setUp(self): self.client = Client() task = Task.objects.create(Title = 'My first task', Description = 'My first task description', due_time = '2012-06-08 10:29:47')
"use strict"; const inquirer = require("inquirer"); const cmLogger = require("@coremedia/cm-logger"); const themeImporter = require("@coremedia/theme-importer"); const { workspace: { Env, getEnv, setEnv }, } = require("@coremedia/tool-utils"); const { isValidURL, isValidStringValue } = require("../../lib/validators"); const args = require("../../lib/args"); const { PKG_NAME } = require("../../lib/constants"); const command = "login [options]"; const desc = "Authenticate user and create API key"; const builder = (yargs) => { let defaults = {}; try { const env = getEnv(); defaults = Object.assign(defaults, env); } catch (e) { // env file does not exist yet. } return yargs .options({ studioUrl: { demandOption: false, default: defaults.studioUrl, describe: "Studio URL", type: "string", }, openBrowser: { demandOption: false, default: defaults.openBrowser, describe: "Open Browser", type: "boolean", }, previewUrl: { demandOption: false, default: defaults.previewUrl, describe: "Preview URL", type: "string", }, proxyUrl: { demandOption: false, default: defaults.proxy, describe: "Proxy URL", type: "string", }, username: { alias: "u", demandOption: false, describe: "Username", type: "string", }, password: { alias: "p", demandOption: false, describe: "Password", type: "string", }, }) .check((argv) => { const checks = [ { key: "Studio URL", value: typeof argv.studioUrl === "undefined" || isValidURL(argv.studioUrl), }, { key: "Open Browser", value: ["undefined", "boolean"].includes(typeof argv.openBrowser), }, { key: "Preview URL", value: typeof argv.previewUrl === "undefined" || isValidURL(argv.previewUrl), }, { key: "Proxy URL", value: typeof argv.proxyUrl === "undefined" || isValidURL(argv.proxyUrl), }, { key: "Username", value: typeof argv.username === "undefined" || isValidStringValue(argv.username), }, { key: "Password", value: typeof argv.password === "undefined" || isValidStringValue(argv.password), }, ]; const errors = checks.filter((check) => typeof check.value === "string"); if (errors.length > 0) { return errors.map((error) => `${error.key}: ${error.value}`).join(", "); } return true; }) .epilogue(args.docs); }; const handler = (argv) => { const log = cmLogger.getLogger({ name: PKG_NAME, level: "info", }); const args = Object.assign({}, argv); if (!args.studioUrl || !args.username || !args.password) { inquirer .prompt([ { type: "input", name: "studioUrl", message: "Studio URL:", default: args.studioUrl, validate: (input) => isValidURL(input), }, // Ask if browser should be opened after the theme was build // As soon as https://github.com/SBoudrias/Inquirer.js/issues/590 is integrated, we can discuss if it makes // sense to replace this explicit confirmation with an editable default of the "previewUrl" config. { type: "confirm", name: "openBrowser", message: "Open browser after initial build?", default: args.openBrowser, when: () => !args.deploy, }, { type: "input", name: "previewUrl", message: "Preview URL:", default: args.previewUrl, validate: (input) => !input || isValidURL(input), when: ({ openBrowser }) => !!openBrowser, }, { type: "input", name: "proxyUrl", message: "Proxy URL:", default: args.proxyUrl, validate: (input) => !input || isValidURL(input), }, { type: "input", name: "username", message: "Username:", default: args.username, validate: (input) => isValidStringValue(input), }, { type: "password", name: "password", message: "Password:", validate: (input) => isValidStringValue(input), }, ]) .then((args) => { themeImporter .login(args.studioUrl, args.previewUrl, args.proxyUrl, args.username, args.password) .then(getSuccessfulLoginHandler(log, args.openBrowser, args.studioUrl, args.proxyUrl)) .catch((e) => { log.error(e.message); process.exit(1); }); }); } else { themeImporter .login(args.studioUrl, args.previewUrl, args.proxyUrl, args.username, args.password) .then(getSuccessfulLoginHandler(log, args.openBrowser, args.studioUrl, args.proxyUrl)) .catch((e) => { log.error(e.message); process.exit(1); }); } }; const getSuccessfulLoginHandler = (log, openBrowser, studioClientUrl, proxyUrl) => ({ studioApiUrl, previewUrl }) => { setEnv( new Env({ openBrowser, studioClientUrl, studioUrl: studioApiUrl, previewUrl, proxyUrl, }), ); log.success("API key has successfully been generated."); }; module.exports = { command, desc, builder, handler, };
import { useEffect, useMemo, useState } from "react"; import { toast } from "react-hot-toast"; import { useSupabaseClient } from "@supabase/auth-helpers-react"; import { Song } from "../../types_incl_stripe"; const useSongById = (id: string) => { const [isLoading, setIsLoading] = useState(false); const [song, setSong] = useState<Song | null>(null); const supabaseClient = useSupabaseClient(); useEffect(() => { if (!id) { return; } setIsLoading(true); const usefetchSong = async () => { const { data: song, error } = await supabaseClient .from("songs") .select("*") .eq("id", id) .single(); if (error) { setIsLoading(false); return toast.error(error.message); } setSong(song as Song); setIsLoading(false); }; usefetchSong(); }, [id]); return { isLoading, song }; /* useMemo( () => ({ isLoading, song, }), [isLoading, song] ) */ }; export default useSongById;
from playwright.sync_api import sync_playwright import json MAX_RETRIES = 3 def crawl_website(url, retry_count=0): try: with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.goto(url) # Find all the paper elements paper_elements = page.query_selector_all('p.list-title.is-inline-block') # Find all the abstract elements abstract_elements = page.query_selector_all('.abstract-full') authors_elements = page.query_selector_all('.authors') titles_elements = page.query_selector_all('p.title ') papers = [] for i, paper_element in enumerate(paper_elements): # Extract the paper ID and URL paper_link = paper_element.query_selector('a') paper_url = paper_link.get_attribute('href') paper_id = paper_url.split('/')[-1] # Extract the submitted date submitted_date_element = page.query_selector('p.is-size-7') submitted_date = '' if submitted_date_element: submitted_date_text = submitted_date_element.inner_text() submitted_date = submitted_date_text.split(';')[0].replace('Submitted', '').strip() if i < len(abstract_elements): abstract_text = abstract_elements[i].inner_text() paper_authors = authors_elements[i].inner_text()[9:] # change the string to list paper_authors = paper_authors.split(',') title = titles_elements[i].inner_text() else: abstract_text = '' paper_data = { 'url': paper_url, 'paper_id': paper_id, 'abstract': abstract_text, 'title': title, 'date': submitted_date, 'authors': paper_authors } papers.append(paper_data) browser.close() return papers except Exception as e: print(f"Error occurred during crawling: {str(e)}") if retry_count < MAX_RETRIES: print(f"Retrying (attempt {retry_count + 1})...") return crawl_website(url, retry_count + 1) else: print("Max retries exceeded. Returning empty list.") return [] def main(): base_url = 'https://arxiv.org/search/advanced?advanced=&terms-0-term=artificial+intelligence&terms-0-operator=AND&terms-0-field=all&classification-computer_science=y&classification-physics_archives=all&classification-include_cross_list=include&date-filter_by=date_range&date-year=&date-from_date=2023-09-28&date-to_date=2024-03-10&date-date_type=submitted_date&abstracts=show&size=100&order=submitted_date' start_index = 0 all_papers = [] while True: url = base_url + f'&start={start_index}' page_papers = crawl_website(url) if not page_papers: break all_papers.extend(page_papers) start_index += 100 # Dump the papers data into a JSON file with open('badcase-full-41-s.json', 'w') as file: json.dump(all_papers, file, indent=2) print(f'Scraped {len(all_papers)} papers and saved to papers.json') if __name__ == '__main__': main()
package io.efdezpolo import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import kotlin.test.assertFalse import kotlin.test.assertTrue class ValidParenthesesTest { @ParameterizedTest(name = "{index} \"{0}\" should be valid") @ValueSource(strings = ["(((((((((())))))))))", "", "{[]}", "()[]{}"]) fun `test all valid strings`(validStringToCheck: String) { val isValid = ValidParentheses(validStringToCheck).check() assertTrue(isValid, "the all parentheses string should be valid") } @ParameterizedTest(name = "{index} \"{0}\" should be invalid") @ValueSource(strings = [")(", "([)])", ")", "("]) fun `test all invalid strings`(invalidStringToCheck: String) { val isValid = ValidParentheses(invalidStringToCheck).check() assertFalse(isValid, "the all parentheses string should be valid") } }
package controller.usuario; import java.io.IOException; import java.util.List; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import model.Tipo; import model.Usuario; import services.TipoService; import services.UsuarioService; @WebServlet("/crearUsuario.adm") public class CrearUsuarioServlet extends HttpServlet implements Servlet { private static final long serialVersionUID = -1047363622015119142L; private UsuarioService usuarioService; private TipoService tipoService; @Override public void init() throws ServletException { super.init(); this.usuarioService = new UsuarioService(); this.tipoService = new TipoService(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Tipo> tipos = tipoService.list(); req.setAttribute("tipos", tipos); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/createU.jsp"); dispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String nombre = req.getParameter("nombre"); String password = req.getParameter("password"); Boolean admin = Boolean.parseBoolean(req.getParameter("admin")); Integer presupuesto = Integer.parseInt(req.getParameter("presupuesto")); Double tiempo = Double.parseDouble(req.getParameter("tiempo")); String preferencia = req.getParameter("preferencia"); Usuario usuario = usuarioService.create(nombre, password, admin, presupuesto, tiempo, preferencia); if (usuario.isValid()) { resp.sendRedirect("listar.adm"); } else { req.setAttribute("usuario", usuario); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/createU.jsp"); dispatcher.forward(req, resp); } } }
/* - - - - - - - - */ class fetchForecastApi { constructor() { this.baseApiUrl = 'https://www.metaweather.com/api/location'; this.searchApiUrl = `${this.baseApiUrl}/search`; this.addCorsHeader(); } addCorsHeader() { $.ajaxPrefilter(options => { if (options.crossDomain && $.support.cors) { options.url = 'https://the-ultimate-api-challenge.herokuapp.com/' + options.url; } }); } getLocation(query, callback) { // callback $.getJSON(this.searchApiUrl, {query}) .done(data => callback(data)) .fail(() => callback(null)) //data will be passed to fetchWeather(data) || if fails, pass to callback } getWeatherData(location, callback) { $.getJSON(`${this.baseApiUrl}/${location}`) .done(data => callback(data)) .fail(() => callback(null)); } } class coreDomElements { constructor() { this.searchForm = $('#search-form'); this.errorBox = $('#error-box'); this.searchBox = $('#search-box'); this.loaderBox = $('#loader-box'); this.forecastBox = $('#forecast-box'); } showForecast() { this.hideError(); this.forecastBox.removeClass('d-none'); this.forecastBox.addClass('d-flex'); } showLoader() { this.loaderBox.removeClass('d-none'); } hideLoader() { this.loaderBox.addClass('d-none'); } showSearch() { this.searchBox.removeClass('d-none'); this.searchBox.addClass('d-flex'); } hideSearchBox() { this.searchBox.removeClass('d-flex'); this.searchBox.addClass('d-none'); } showError(message) { this.hideLoader(); this.showSearch(); this.errorBox.removeClass('d-none'); this.errorBox.addClass('d-block'); this.errorBox.html(`<p class="mb-0">${message}</p>`); } hideError() { this.errorBox.addClass('d-none'); } } class displayForecast { constructor() { this.imageURL = 'https://www.metaweather.com/static/img/weather'; document.body.style.backgroundImage = "url('https://source.unsplash.com/1600x900?" + name + "')" } showTodaysForecastDetails({name, value, unit}) { $(`#forecast-details`).append(` <div class="d-flex justify-content-between"> <span class="font-weight-bolder">${name}</span><span>${value} ${unit}</span> </div> `); } showUpcomingDaysForecast({dayImgUrl, weekDay, maxTemp}) { $('#forecast-details-week').append(` <li class="forecastBox__week-day d-flex flex-column justify-content-center align-items-center p-2 weather-day"> <img class="mb-2" width="30" src="${this.imageURL}/${dayImgUrl}.svg" /> <span class="mb-2">${weekDay}</span> <span class="font-weight-bold">${maxTemp}&deg</span> </li> `); } showTodaysForecast(forecast) { $('#forecast-card-weekday').html(forecast.currentWeekday); $('#forecast-card-date').html(forecast.todaysFullDate); $('#forecast-card-location').html(forecast.locationName); $('#forecast-card-img').attr('src', `${this.imageURL}/${forecast.todaysImgUrl}.svg`); $('#forecast-card-temp').html(forecast.todaysTemp); $('#forecast-card-description').html(forecast.weatherState); } } class dataMiddleware { // right hand side of taskbar constructor() { this.displayForecast = new displayForecast(); this.coreDomElements = new coreDomElements(); } gatherTodaysForecastDetails(data) { return { predictability: { value: data.predictability, unit: '%', }, humidity: { value: data.humidity, unit: '%', }, wind: { value: Math.round(data.wind_speed), unit: 'km/h', }, 'air pressure': { value: data.air_pressure, unit: 'mb', }, 'max temp': { value: Math.round(data.max_temp), unit: '°C', }, 'min temp': { value: Math.round(data.min_temp), unit: '°C', }, }; } gatherTodaysForecastGeneral(data) { return { currentWeekday: moment(data.applicable_date).format('dddd'), todaysFullDate: moment(data.applicable_date).format('MMMM Do'), locationName: data.title, todaysImgUrl: data.weather_state_abbr, todaysTemp: Math.round(data.the_temp), weatherState: data.weather_state_name, }; } prepareDataForDom(data) { const {predictability, humidity, wind_speed, air_pressure, max_temp, min_temp, applicable_date, the_temp, weather_state_abbr, weather_state_name } = data.consolidated_weather[0] //first element of array const todaysForecastGeneral = this.gatherTodaysForecastGeneral({ applicable_date, weather_state_abbr, weather_state_name,the_temp, title: data.title, }); const todaysForecastDetails = this.gatherTodaysForecastDetails({ predictability, humidity, wind_speed, air_pressure, max_temp, min_temp, }); this.displayForecast.showTodaysForecast(todaysForecastGeneral); this.prepareTodaysForecastDetails(todaysForecastDetails); // call method this.prepareUpcomingDaysForecast(data.consolidated_weather); this.coreDomElements.hideLoader(); this.coreDomElements.showForecast(); } prepareTodaysForecastDetails(forecast) { $.each(forecast, (key, value) => { this.displayForecast.showTodaysForecastDetails({ name: key.toUpperCase(), value: value.value, unit: value.unit, }); }); } prepareUpcomingDaysForecast(forecast) { $.each(forecast, (index, value) => { if (index < 1) return; const dayImgUrl = value.weather_state_abbr; const maxTemp = Math.round(value.max_temp); const weekDay = moment(value.applicable_date).format('dddd').substring(0,3); //moment.js //pass in data to method this.displayForecast.showUpcomingDaysForecast({dayImgUrl, maxTemp, weekDay}); }); } } class requestController { constructor() { this.fetchForecastApi = new fetchForecastApi(); this.coreDomElements = new coreDomElements(); this.dataMiddleware = new dataMiddleware(); this.registerEventListener(); } showRequestInProgress() { this.coreDomElements.showLoader(); this.coreDomElements.hideSearchBox(); } getQuery() { return $('#search-query').val().trim(); } fetchWeather(query) { this.fetchForecastApi.getLocation(query, location => { if(!location || location.length === 0) { this.coreDomElements.showError('Could not find this location, please try again!'); return; } this.fetchForecastApi.getWeatherData(location[0].woeid, data => { //where on earth id, check if data we need is there if (!data) { this.coreDomElements.showError('Could not proceed with your request, please try again later !'); return; } this.dataMiddleware.prepareDataForDom(data) // if response is successful }) }); } onSubmit() { const query = this.getQuery(); if (!query) return; this.showRequestInProgress(); // loading screen when press submit method this.fetchWeather(query); } registerEventListener(){ this.coreDomElements.searchForm.on('submit', (e) => { e.preventDefault(); // prevent reloading wp this.onSubmit(); }); } } const request = new requestController(); // request.getLocation();
<!DOCTYPE html> <html lang="pt-br"> <head> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Formulário Intermediário</title> <link rel="stylesheet" href="style.css"> <link href="https://fonts.googleapis.com/css2?family=Poppins&family=Staatliches&display=swap" rel="stylesheet"> </head> <body> <header> <div class="header-wrapper"> <h1> Mentoria </h1> <p> Preencha o formulário abaixo para <br/> agendar a sua mentoria </p> </div> <div class="page"> <form class="my-form"> <fieldset> <div class="fieldset-wrapper"> <legend class="tittle"> Informações pessoais </legend> <div class="name-lastname"> <div class="input-wrapper"> <label for="name">Nome</label> <input type="text" id="name"> </div> <div class="input-wrapper"> <label for="last-name">Sobrenome</label> <input type="text" id="last-name"> </div> </div> <div class="input-wrapper"> <label for="email">Email <span>(Digite um email válido)</span></label> <input type="email" id="email"> </div> <div class="input-wrapper"> <label for="Senha">Senha <span>(mínimo 6 caracteres)</span></label> <input type="password" maxlength="6" id="Senha"> </div> </div> </fieldset> <fieldset> <div class="fieldset-wrapper"> <legend class="tittle"> Informações do mentor </legend> <div class="input-wrapper"> <label for="mentor-name">Nome do seu mentor <span>(só o primeiro nome)</span></label> <input type="text" id="mentor-name"> </div> </div> </fieldset> <fieldset> <div class="fieldset-wrapper"> <legend class="tittle"> Seus horários disponíveis </legend> <legend class="date-time"> Primeira mentoria </legend> <div class="col-3"> <div class="input-wrapper"> <label for="first-date">Data <span>(DD/MM/AAAA)</span></label> <input type="date" id="first-date"> </div> <div class="input-wrapper"> <label for="start-first-mentorship">Das</label> <input type="time" id="start-first-mentorship"> </div> <div class="input-wrapper"> <label for="end-first-mentorship">Até</label> <input type="time" id="end-first-mentorship"> </div> </div> <legend class="date-time"> Segunda mentoria </legend> <div class="col-3"> <div class="input-wrapper"> <label for="second-date">Data <span>(DD/MM/AAAA)</span></label> <input type="date" id="second-date"> </div> <div class="input-wrapper"> <label for="start-second-mentorship">Das</label> <input type="time" id="start-second-mentorship"> </div> <div class="input-wrapper"> <label for="end-second-mentorship">Até</label> <input type="time" id="end-second-mentorship"> </div> </div> </div> </fieldset> </form> <footer> <input class="button" form="my-form" type="submit" value="SALVAR"/> </footer> </div> </header> </body> </html>
import React, { useState } from "react"; import PropTypes from "prop-types"; import Box from "@mui/material/Box"; import { AiOutlineEye, AiOutlineEyeInvisible } from "react-icons/ai"; import IconButton from "@mui/material/IconButton"; import { Typography } from "@mui/material"; import { StyledFormGroup } from "../styled"; const CustomInput = ({ label, type = "text", endAdornment, startAdornment, sx, name, error, keepErrMounted = true, hidePwdEye, withBorderErr, inputEl, loading, readOnly, id = `${name || type}-input`, ...rest }) => { loading = loading === true ? "loading" : ""; readOnly = !!(loading || readOnly); const [showPwd, setShowPwd] = useState(false); const togglePwdVisibility = () => setShowPwd(!showPwd); endAdornment = { password: hidePwdEye ? ( undefined ) : ( <IconButton onClick={readOnly ? undefined : togglePwdVisibility}> {!readOnly && showPwd ? <AiOutlineEye /> : <AiOutlineEyeInvisible />} </IconButton> ) }[type]; return ( <StyledFormGroup type={type} error={error} withBorderErr={withBorderErr} noAdornment={!endAdornment && !startAdornment} className={`custom-input ${loading}`} sx={sx} > <label htmlFor={id}>{label}</label> <div className="custom-input-container"> {startAdornment ? ( <div className="adornment">{startAdornment}</div> ) : null} <Box className="custom-input-wrapper"> {inputEl || ( <input {...rest} id={id} type={readOnly || !showPwd ? type : "text"} name={name || type} readOnly={readOnly} validator={undefined} nullify={undefined} info={undefined} handleChange={undefined} key={1} /> )} {loading ? ( <input id={id + "-loading"} value={rest.value} type={type} placeholder={rest.placeholder} className="loading" readOnly key={2} /> ) : null} </Box> {endAdornment ? <div className="adornment">{endAdornment}</div> : null} </div> {error || keepErrMounted ? ( <Typography className="custom-input-error" color={ error ? (error === "Medium" ? "success.main" : "error") : "red" } sx={{ "&::first-letter": { textTransform: "uppercase" }, opacity: error ? 1 : 0, m: 0 }} > {{ Medium: "Password strength is medium", Weak: "Password strength is weak" }[error] || error || "custom-error"} </Typography> ) : null} </StyledFormGroup> ); }; CustomInput.propTypes = {}; export default CustomInput;
import "./globals.css"; import type { Metadata } from "next"; import Link from "next/link"; import { Control } from "./Control"; import Header from "./Header"; import { fetchPostsList } from "@/api/posts/PostsListApi"; export const metadata: Metadata = { title: "Nextjs 13", description: "Generated by hjy", }; export default async function RootLayout({ children, }: { children: React.ReactNode; }) { const posts = await fetchPostsList(); return ( <html> <body> <Header /> {children} {/* server component 내에서는 현재 동적 라우팅의 값([id])을 layout 안에서는 알 수 없다. useParams를 사용해야 하는데 useParams는 client component다. app/layout.js 전체를 client component로 전환해도 됩니다만, server component의 이점을 포기하기는 싫기 때문에 client component의 기능이 필요한 부분만 별도의 컴포넌트로 분리했다. */} <Control /> <div className="min-w-[1200px] px-[10px]"> {posts?.map((el: { id: string; title: string }, idx: number) => { return ( <div className={`border-x ${idx === 0 ? "border-t" : ""}`} key={el.id} > <Link className="flex items-center border-b h-[50px] px-[10px]" href={`/read/${el.id}`} > {el.title} </Link> </div> ); })} </div> <div className="flex justify-center items-center cursor-pointer w-[60px] h-[40px] text-white bg-orange-500 rounded ml-[10px] mt-[10px]"> <Link href={"/create"}>글쓰기</Link> </div> </body> </html> ); }