text
stringlengths
184
4.48M
from random import choice import re import json # import json import requests # import requests class Bank: # two lines need(PEP8: E302) colours = ['red', 'blue'] # Missing space after ',' animals = ['dog', 'cat'] # Missing space after ',' topic_names = ['Colours', 'Animals'] # Missing space after ',' topics = {'Colours': colours, 'Animals': animals} # Missing space after ':' and ',' api = 'https://api.api-ninjas.com/v1/randomword' api_key = 'FRkfTIwrgLLk+4TIMd+NMA==m6isKOfXzCLPgdGz' def __init__(self): self.current_topic = '' self.current_word = '' self.current_word_display = [] self.letters_guessed_counter = 0 self.not_solved = True self.letters_already_guessed = [] self.api_response_status = True def pick_topic(self): self.current_topic = choice(self.topic_names) print(f'Topic: {self.current_topic}') def get_word(self): response = requests.get(f"{self.api}", headers={'X-Api-Key': f"{self.api_key}"}, params={type: 'noun'}) # ": " if response.status_code == 200: word = json.loads(response.text) self.api_response_status = True self.current_word = word['word'] for _ in self.current_word: # changing 'i' with '_' self.current_word_display.append('_') else: self.current_word = choice(self.topics[self.current_topic]) self.api_response_status = False def pick_word(self): self.current_word = choice(self.topics[self.current_topic]) for _ in self.current_word: # changing 'i' with '_' self.current_word_display.append('_') print(f'Word is {len(self.current_word)} letters long.') # adding len method for this print(self.current_word_display) def check_solve(self): self.not_solved = self.letters_guessed_counter < len(self.current_word) class Player: # two lines need(PEP8: E302) def __init__(self): self.lives = 10 self.answer = '' self.guess_validation_incomplete = True def guess(self): self.answer = input('Guess a letter: ') class Processes: def __init__(self): pass @staticmethod # making def static def validate_user_input(player): # regex changed & match changed to findall & if condition changed expression = re.findall('(?i)[a-z]', player.answer) # missing space around operator & after ',' if len(expression) == 0 or len(expression) > 2: # missing space around operator print('\nPlease guess a single alphabet') else: player.guess_validation_incomplete = False @staticmethod # def seems to be static def check_answer_update_lives(bank, player): # missing space after ',' if player.answer in bank.letters_already_guessed: print('\nLetter already guessed.') # changing elif condition elif player.answer not in bank.current_word and not player.guess_validation_incomplete: player.lives -= 1 print('\nNope!') print('Lives remaining: {}'.format(player.lives)) bank.letters_already_guessed.append(player.answer) else: for i in range(len(bank.current_word)): if player.answer == bank.current_word[i]: bank.current_word_display[i] = player.answer bank.letters_guessed_counter += 1 bank.letters_already_guessed.append(player.answer) print('\nNice!') class Main: # two lines need(PEP8: E302) def __init__(self): pass while True: word_bank = Bank() player1 = Player() game = Processes() word_bank.get_word() if not word_bank.api_response_status: word_bank.pick_topic() word_bank.pick_word() player1.lives = 3 * len(word_bank.current_word) while word_bank.not_solved and player1.lives > 0: while player1.guess_validation_incomplete: player1.guess() game.validate_user_input(player1) game.check_answer_update_lives(word_bank, player1) # missing space after ',' print(word_bank.current_word_display) player1.guess_validation_incomplete = True word_bank.check_solve() if not word_bank.not_solved: print('\nYou win!') else: print('\nYou lose') print('Word was {}'.format(word_bank.current_word)) replay = input('Press any key to play again, x to quit: ') print('\n') if replay.upper() == 'X': break Play = Main() # two lines need(PEP8: E302) del Play # new line at the end of file
// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.apache.royale.html.beads { import org.apache.royale.collections.IArrayList; import org.apache.royale.core.IBead; import org.apache.royale.core.IDataProviderItemRendererMapper; import org.apache.royale.core.IItemRendererClassFactory; import org.apache.royale.core.IItemRendererOwnerView; import org.apache.royale.core.IListPresentationModel; import org.apache.royale.core.IIndexedItemRenderer; import org.apache.royale.core.IDataProviderModel; import org.apache.royale.core.IStrand; import org.apache.royale.core.IStrandWithModelView; import org.apache.royale.core.SimpleCSSStyles; import org.apache.royale.core.UIBase; import org.apache.royale.events.Event; import org.apache.royale.events.IEventDispatcher; import org.apache.royale.events.EventDispatcher; import org.apache.royale.events.ItemRendererEvent; import org.apache.royale.html.supportClasses.DataItemRenderer; import org.apache.royale.utils.loadBeadFromValuesManager; import org.apache.royale.html.beads.IListView; import org.apache.royale.utils.sendEvent; import org.apache.royale.utils.sendStrandEvent; /** * The DataItemRendererFactoryForArrayList class uses an ArrayList * and creates an item renderer for every * item in the collection. Other implementations of * IDataProviderItemRendererMapper map different data * structures or manage a virtual set of renderers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public class DataItemRendererFactoryForArrayList extends DataItemRendererFactoryBase { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function DataItemRendererFactoryForArrayList(target:Object=null) { super(target); } private var dp:IArrayList; /** * @private * @royaleignorecoercion org.apache.royale.collections.IArrayList */ override protected function dataProviderChangeHandler(event:Event):void { dp = dataProviderModel.dataProvider as IArrayList; if (!dp) return; super.dataProviderChangeHandler(event); } override protected function get dataProviderLength():int { return dp.length; } override protected function getItemAt(i:int):Object { return dp.getItemAt(i); } } }
import TextField from "@mui/material/TextField"; import { GitHub } from "@mui/icons-material"; import FormControl from "@mui/material/FormControl"; import { useState } from "react"; import Box from "@mui/material/Box"; import GitHubTable from "./GitHubTable"; import { LoadingButton } from "@mui/lab"; import { Typography } from "@mui/material"; function AppForm() { const [username, setUsername] = useState(""); const [userInfo, setUserinfo] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(false); const hadnleUserInput = (user) => { setUsername(user); }; const handleFetchUser = async () => { setError(false); setIsLoading(true); const response = await fetch( `https://api.github.com/users/${username}/repos` ); if (!response.ok) { setIsLoading(false); setError("Couldn't fetch user from GitHub repo."); } const res = await response.json(); if (res.length == 0) { setError("No repos finded."); } setUserinfo(res); setUsername(""); setIsLoading(false); }; return ( <> <Box sx={{ "& > :not(style)": { m: 1 } }} style={{ display: "flex", justifyContent: "center", marginTop: "50px", marginLeft: "120px", }} > <FormControl variant="standard"> <Box> <GitHub sx={{ color: "black", mr: 1, my: 0.9 }} /> <TextField id="input-with-sx" label="Username" variant="outlined" size="small" value={username} onChange={(event) => hadnleUserInput(event.target.value)} /> </Box> </FormControl> <LoadingButton size="small" onClick={handleFetchUser} loading={isLoading} variant="outlined" style={{ marginBottom: "10px" }} > <span>Fetch Info</span> </LoadingButton> </Box> {userInfo.length > 0 && ( <GitHubTable user={userInfo} username={username} public_repos={userInfo.length} name={userInfo.name} desc={userInfo.description} url={userInfo.url} id={userInfo.id} created={userInfo.created_at} /> )} {error && ( <Typography variant="h5" style={{ textAlign: "center", color: "red", fontWeight: "bold", marginLeft: "100px", marginTop: "20px", }} > {error} </Typography> )} </> ); } export default AppForm;
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddOwnerIdToVenuesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('venues', function (Blueprint $table) { $table->integer('owner_id')->unsigned()->index()->nullable()->after('id'); $table->foreign('owner_id') ->references('id') ->on('owners') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('venues', function (Blueprint $table) { $table->dropColumn('owner_id'); }); } }
Script started on Mon 06 Mar 2017 03:04:25 PM EST liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ gcc -o lab7 lab7.c liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ ./lab7 5 8 keyboard event CTRL-C and CTRL-Z were ignored. I am the parent with pid 14035, start to wait the child 14036 I am the child with pid 14036 of process id 14035 parent process's time to live in 4s. child process's time to live in 7s parent process's time to live in 3s. child process's time to live in 6s parent process's time to live in 2s. child process's time to live in 5s parent process's time to live in 1s. child process's time to live in 4s parent process's time to live in 0s. the parent died or terminated before the child. child process's time to live in 3s liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ child process's time to live in 2s child process's time to live in 1s child process's time to live in 0s liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ ./lab7 5 88 5 keyboard event CTRL-C and CTRL-Z were ignored. I am the parent with pid 14748, start to wait the child 14751 I am the child with pid 14751 of process id 14748 parent process's time to live in 7s. child process's time to live in 4s parent process's time to live in 6s. child process's time to live in 3s parent process's time to live in 5s. child process's time to live in 2s parent process's time to live in 4s. child process's time to live in 1s parent process's time to live in 3s. child process's time to live in 0s the child died or terminated before the parent. parent process's time to live in 2s. parent process's time to live in 1s. parent process's time to live in 0s. liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ exicat rsample.txt liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ cat sample.txt lab7.c // 1. The program disables the CTRL-C and CTRL-Z sensitivity. (be careful if your program hands to do the ps command and kill the process) // 2. The program implements the timer alarm. // Logic of the program: // The program will launch a child. // The child will stay alive for a specified number of seconds between 1 and 10 (by a parameter) and then terminates. // The parent will stay alive for a specified number of seconds between 1 and 10 (by parameter) and then terminates. // Each of the child and parent will print a count-down every second to display how many seconds they have to live. // Consider the cases your program should report: // if the child dies before the parent dies: parent declares that the child is dead by displaying a message on the screen // if the child dies after the parent dies: the child declares it is an orphan by displaying a message on the screen // Test your code under the two circumstances and use a script file to log and submit your output. #include <sys/signal.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> void pEvent() { printf("the parent died or terminated before the child.\n"); } void cEvent() { printf("the child died or terminated before the parent.\n"); } int main(int argc, char *argv[]) { // process the arguments if (argc != 3) { printf("Arguments error!\n"); printf("Usage:\n"); printf("%s [parent TTL] [child TTL]\n",argv[0]); exit(-1); } int pttl,cttl; if ( (pttl = atoi(argv[1])) == 0 || (cttl = atoi(argv[2])) == 0 ) { printf("Arguments error! TTL should be integer.\n"); printf("Usage:\n"); printf("%s [parent TTL] [child TTL]\n",argv[0]); exit(-1); } //process the code int status = -1; pid_t pid,cpid; //disable CTL-C and CTL-Z to signal signal(SIGINT,SIG_IGN); signal(SIGTSTP,SIG_IGN); //bind child event signal(SIGALRM,cEvent); printf("keyboard event CTRL-C and CTRL-Z were ignored.\n"); //fork child pid = fork(); if (pid == 0) { //child process tasks //bind parent event signal(SIGALRM,pEvent); printf("I am the child with pid %d of process id %d\n",getpid(),getppid()); int n = cttl; while(n--) { sleep(1); printf("child process's time to live in %ds\n",n); } //send signal to parent before dying and ingnore error. //if ( kill(getppid(),SIGALRM) == -1 ) printf("the parent process was dead before the child.\n"); kill(getppid(),SIGALRM); exit(0); } else if(pid < 0) { printf("Error to fork new child process.\n"); } //parents tasks cpid = pid; printf("I am the parent with pid %d, start to wait the child %d\n",getpid(),cpid); waitpid(pid,&status,1); int m = pttl; while(m--) { sleep(1); printf("parent process's time to live in %ds.\n",m); } //send signal to child beofe dying and ignore the error message. //if ( kill(cpid,SIGALRM) == -1 ) printf("the child process was dead before the parent\n"); kill(cpid,SIGALRM); exit(0); } liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ exit exit Script done on Mon 06 Mar 2017 03:07:47 PM EST
import { Button } from "@material-ui/core"; import { DataGrid } from "@material-ui/data-grid"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Link } from "react-router-dom"; import Loader from "../Layout/Loader"; import { getAllOrdersOfShop } from "../../redux/actions/order"; import { AiOutlineArrowRight } from "react-icons/ai"; import currency from "currency-formatter"; const AllOrders = () => { const { orders, isLoading } = useSelector((state) => state.order); const { seller } = useSelector((state) => state.seller); const dispatch = useDispatch(); useEffect(() => { dispatch(getAllOrdersOfShop(seller._id)); }, [dispatch]); const columns = [ { field: "id", headerName: "ID ฤ‘ฦกn hร ng", minWidth: 150, flex: 0.7 }, { field: "status", headerName: "Trแบกng thรกi", minWidth: 130, flex: 0.7, cellClassName: (params) => { return params.getValue(params.id, "status") === "Delivered" ? "greenColor" : "redColor"; }, }, { field: "itemsQty", headerName: "Sแป‘ lฦฐแปฃng", type: "number", minWidth: 130, flex: 0.7, }, { field: "total", headerName: "Tแป•ng cแป™ng", type: "number", minWidth: 130, flex: 0.8, }, { field: " ", flex: 1, minWidth: 150, headerName: "", type: "number", sortable: false, renderCell: (params) => { return ( <> <Link to={`/order/${params.id}`}> <Button> <AiOutlineArrowRight size={20} /> </Button> </Link> </> ); }, }, ]; const row = []; orders && orders.forEach((item) => { row.push({ id: item._id, itemsQty: item.cart.length, total: `${currency.format(item.totalPrice, { code: "VND" })}`, status: item.status, }); }); return ( <> {isLoading ? ( <Loader /> ) : ( <div className="w-full mx-8 pt-1 mt-10 bg-white"> <DataGrid rows={row} columns={columns} pageSize={10} disableSelectionOnClick autoHeight /> </div> )} </> ); }; export default AllOrders;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SSHConfigurator.Extensions; namespace SSHConfigurator { /// <summary> /// This class configures services and the app's request pipeline. /// </summary> public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the DI container. public void ConfigureServices(IServiceCollection services) { services.InstallServicesInAssembly(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePagesWithRedirects("/Error/{0}"); app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
--- title: 7์ฃผ์ฐจ ๊ฐ•์˜ ๋ณต์Šต categories: [๋ฉ‹์Ÿ์ด์‚ฌ์ž์ฒ˜๋Ÿผ, ๊ฐ•์˜ ๋ณต์Šต] tags: [Spring] pin: false math: false mermaid: false --- <style>s{text-decoration: none;background: #ffd00066;border-radius: 4px;padding: 2px;}</style> ## Spring Security * <s>์Šคํ”„๋ง ๊ธฐ๋ฐ˜ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์ธ์ฆ๊ณผ ๊ถŒํ•œ์„ ๋‹ด๋‹นํ•˜๋Š” ํ•˜์œ„ ํ”„๋ ˆ์ž„์›Œํฌ</s> * ๊ด€๋ฆฌ์ž ๋ฐ ์‚ฌ์šฉ์ž ๊ณ„์ • ์ถ”๊ฐ€, ๊ถŒํ•œ ์ถ”๊ฐ€, DB ์—ฐ๋™์ด ๋ณต์žกํ•˜๋‹ค๋Š” ๋ฌธ์ œ์ ์ด ์žˆ์Œ * `build.gradle`์˜ dependencies์— ์•„๋ž˜ ๋ผ์ธ์„ ์ถ”๊ฐ€ํ•œ๋’ค ๋™๊ธฐํ™”ํ•˜์—ฌ ์ ์šฉ ๊ฐ€๋Šฅ ```gradle dependencies { // ... implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE' // ... } ``` * ์ ์šฉํ›„ ์‚ฌ์ดํŠธ๋ฅผ ๋“ค์–ด๊ฐ€๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ํ™”๋ฉด ๋œธ ![](/imgs/2023-06-29/login-page.png) * <s>Spring Security๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ธ์ฆ๋˜์ง€ ์•Š์€ ์‚ฌ์šฉ์ž๋Š” ์„œ๋น„์Šค๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๊ฒŒ๋” ๋˜์–ด ์žˆ์Œ</s> * ๋ฐฉ๋ฌธํ•œ ์‚ฌ์šฉ์ž๊ฐ€ ์‚ฌ์ดํŠธ๋ฅผ ์›ํ™œํžˆ ์ด์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์‹œํ๋ฆฌํ‹ฐ ์•„๋ž˜์˜ ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค˜์•ผ ํ•จ ```java package com.likelion.likelion230626; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration // ํ™˜๊ฒฐ์„ค์ •์„ ์˜๋ฏธํ•˜๋Š” ์–ด๋…ธํ…Œ์ด์…˜ @EnableWebSecurity // ๋ชจ๋“  ์š”์ฒญ URL์ด ์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๋„๋ก ๋งŒ๋“œ๋Š” ์–ด๋…ธํ…Œ์ด์…˜ public class SecurityConfig { // ๋‚ด๋ถ€์ ์œผ๋กœ URL ํ•„ํ„ฐ ์ ์šฉ @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests().requestMatchers( new AntPathRequestMatcher("/**")).permitAll() ; return http.build(); // ๋ชจ๋“  ์ธ์ฆ๋˜์ง€ ์•Š์€ ์š”์ฒญ์„ ํ—ˆ๋ฝ } } ``` {: file='src/main/java/com.likelion.likelion-230626/Security.java'} ## Spring Security์˜ ์ธ์ฆ ๊ณผ์ • ![](/imgs/2023-06-29/login-flow.png) _๊ธฐ๋ณธ์ ์ธ ๋กœ๊ทธ์ธ ๊ณผ์ •_ * ์‚ฌ์šฉ์ž๊ฐ€ `GET /home` ์š”์ฒญ์„ ํ•  ๋•Œ ๋งŒ์•ฝ ์‚ฌ์šฉ์ž์˜ ์ธ์ฆ์„ ํ™•์ธํ•  ์ˆ˜ ์—†์œผ๋ฉด ๋กœ๊ทธ์ธ ํŽ˜์ด์ง€๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ * ์‚ฌ์šฉ์ž๊ฐ€ ๋กœ๊ทธ์ธ ํŽ˜์ด์ง€์—์„œ username๊ณผ password๋ฅผ ์ž…๋ ฅํ›„ `POST` ๋ฉ”์„œ๋“œ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†กํ•˜๋ฉด, ํ•ด๋‹น ์œ ์ €์— ๋Œ€ํ•œ ์ธ์ฆ ํ† ํฐ์„ ์ƒ์„ฑํ•˜๊ณ  ์ €์žฅ * ๋‹ค์‹œ ์‚ฌ์šฉ์ž๊ฐ€ `GET /home` ์š”์ฒญ์„ ํ•˜๋ฉด ์ €์žฅ๋œ ์ธ์ฆ ํ† ํฐ์œผ๋กœ ์ ‘๊ทผ ํ—ˆ๊ฐ€ ![](/imgs/2023-06-29/login-validation-flow.png) _๋กœ๊ทธ์ธ ๊ฒ€์ฆ ๊ณผ์ •_ * `UsernamePasswordAuthenticationFilter`๋Š” ์ธ์ฆ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋Š” ํ•„ํ„ฐ๋กœ ํฌ๊ฒŒ ์ธ์ฆ ์ „๊ณผ ์ธ์ฆ ํ›„์˜ ์ž‘์—…๋“ค์„ ๊ด€๋ฆฌํ•จ * `UsernamePasswordAuthenticationFilter`๋Š” `AuthenticationManager`์— ์ธ์ฆ์ •๋ณด๋ฅผ ๋„˜๊ธฐ๋ฉด `AuthenticationProvider`์„ ํ†ตํ•ด ์ธ์ฆ ์„ฑ๊ณต ์œ ๋ฌด๋ฅผ ํ™•์ธํ•จ * ์„ฑ๊ณตํ•œ ์ธ์ฆ๊ฐ์ฒด๋ฅผ ๊ฐ€์ง€๊ณ  `SecurityContext`์— ์ €์žฅํ›„, ํ•ธ๋“ค๋Ÿฌ๋ฅผ ํ†ตํ•ด ์ธ์ฆ ์„ฑ๊ณต ํ›„์˜ ํ›„์† ์ž‘์—…๋“ค์„ ์ฒ˜๋ฆฌ * ์ด๋•Œ `SecurityContext`๋Š” ์ „์—ญ์ ์œผ๋กœ ์ธ์ฆ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„๋จ ![](/imgs/2023-06-29/logout-flow.png) ![](/imgs/2023-06-29/logout-flow-detailed.png) _๋กœ๊ทธ์•„์›ƒ ๊ณผ์ •_ ## Spring Security์˜ ์„ธ์…˜ ๋ณดํ˜ธ ### ๋™์‹œ ์„ธ์…˜ ์ œ์–ด ![](/imgs/2023-06-29/multiple-session-control.png) * <s>๊ฐ™์€ ์‚ฌ์šฉ์ž ๊ณ„์ •์ด ๊ฐ€์งˆ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์„ธ์…˜ ์ˆ˜๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ๋‘๊ฐ€์ง€์˜ ์ฒ˜๋ฆฌ๋ฐฉ๋ฒ•์„ ์ œ๊ณต</s> ### ์„ธ์…˜ ๊ณ ์ • ๋ณดํ˜ธ ![](/imgs/2023-06-29/protecting-session.png) * ๊ณต๊ฒฉ์ž๊ฐ€ ๋จผ์ € ์„ธ์…˜์ฟ ํ‚ค๋ฅผ ์–ป์€ ํ›„ ํ•ด๋‹น ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ „๋‹ฌ * ์‚ฌ์šฉ์ž๊ฐ€ ๋ฐ›์€ ์„ธ์…˜์„ ๊ฐ€์ง€๊ณ  ๋กœ๊ทธ์ธ ์‹œ๋„ํ•˜๊ณ  ๋กœ๊ทธ์ธ์ด ์„ฑ๊ณตํ•˜๋ฉด <s>๊ณต๊ฒฉ์ž๋Š” ํ•ด๋‹น ์„ธ์…˜์ฟ ํ‚ค๋ฅผ ๊ฐ€์ง€๊ณ  ์‚ฌ์šฉ์ž์˜ ์ •๋ณด ํƒˆ์ทจ๊ฐ€๋Šฅ</s> ## AWS * <s>์•„๋งˆ์กด ๋‹ท์ปด์—์„œ ๊ฐœ๋ฐœํ•œ ํด๋ผ์šฐ๋“œ ์ปดํ“จํŒ… ํ”Œ๋žซํผ</s> * ๊ฐ€์ƒ ์ปดํ“จํ„ฐ์™€ ์Šคํ† ๋ฆฌ์ง€, ๋„คํŠธ์›Œํฌ ์ธํ”„๋ผ ๋“ฑ ๋‹ค์–‘ํ•œ ์„œ๋น„์Šค ์ œ๊ณต ### Amazon EC2 * ๊ฐ€์ƒ ์ธ์Šคํ„ด์Šค์˜ ํฌ๊ธฐ๋ฅผ ์œ ๋™์ ์œผ๋กœ ์กฐ์ •์ด ๊ฐ€๋Šฅํ•œ ์ปดํ“จํŒ… ํŒŒ์›Œ * ์ปดํ“จํŒ… ๋ฆฌ์†Œ์Šค๋ฅผ ๊ณ ๊ฐ์ด ์™„์ „ํžˆ ์ œ์–ดํ•  ์ˆ˜ ์žˆ์Œ ## ์„œ๋ฒ„ ๋‚ด ๋ฐฐํฌ ### JDK ์„ค์น˜ ```bash sudo apt update sudo apt install openjdk-17-jdk java -version # java ์„ค์น˜ ํ™•์ธ ``` ### ๋„คํŠธ์›Œํฌ ์ƒํƒœ ํ™•์ธ ```bash sudo apt install net-tools netstat -nlpt # ๋„คํŠธ์›Œํฌ ์ƒํƒœ ํ™•์ธ ``` ### ์•„ํŒŒ์น˜ ์„ค์น˜ ๋ฐ .jarํŒŒ์ผ ์‹คํ–‰ ```bash sudo apt install apache2 nohup java -jar test.jar ```
<!DOCTYPE html> <!-- This is the first test html website while DJ is starting to learn HTML --> <html> <head> <meta charset= "UTF-8" > <meta name="description" content="DJ's Thank you Page"> <meta name="author" content="Dylan Jude Bautista"> <meta name="keywords" content= "Dylan, Bautista, Portfolio, DJ"> <meta name="newport" content="width=device width, initial scale=1.0"> <title>DJ Bautista</title> <!--bootstrap stuff--> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!--Playfair Display font Import--> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500&display=swap" rel="stylesheet"> <!--Lato font Import--> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato&family=League+Spartan:wght@100&family=Playfair+Display:wght@400;500&display=swap" rel="stylesheet"> <!-- <script src="script.js"></script> --> <style> .opening-text{ color:rgb(188, 192, 196); font-size: 2.8em; font-family: 'Playfair Display', serif; width: 40vw; line-height: 140%; text-shadow: 3px 3px 4px rgb(150, 137, 137); border: 6px; padding: 1%; border-style:solid; border-color:rgb(188, 192, 196); } p{ font-size: 18px; font-family: 'Lato', serif; color:rgb(30, 33, 37); line-height: 250%; text-align: center; } .header-image{ width:380px; border-style: groove; border-color: azure; border-width: 5px; border-radius: 5px; } .post-image{ width: 30vw; height: 40vh; border-style: ridge; } h1{ color: black; font-size: 2em; font-family: 'Playfair Display', serif; } h2{ font-size: 12px; font-family: 'Lato', serif; color:silver; line-height: 250%; text-align: center; font-style:italic ; } h3{ color:black; font-size: 3.5vh; font-family: 'Playfair Display', serif; } .silver-sub{ background-color:rgb(228, 220, 220); display: flex; justify-content: center; align-items: center; } footer{ background-color: white; font-family: 'Playfair Display', serif; line-height: 125%; text-align: center; display: flex; flex-direction: column; } .project-tab{ background-color: rgb(228, 220, 220); flex-direction: column; display: flex; align-items: center; justify-content: flex-start; } .project-description{ width: 45vw; height: 40vh; margin-left: 60px; } .slideshow-array{ background-color: rgb(228, 220, 220); display: flex; justify-content: space-around; flex-wrap: wrap; align-content: center; } .slideshow{ width: 20vw; height: 30vh; } .caption{ font-size: 18px; font-family: 'Lato', serif; color:beige; line-height: 250%; text-align: center; text-shadow: 2px 2px rgb(92, 84, 84); } h5{ font-family: 'Playfair Display', serif; } .topbar{ box-shadow: 0px 20px 35px rgba(0,0,0,.5); padding: 4px; position:fixed; top:0px; left: 0px; width:100%; background-color: white; display: flex; justify-content: space-between; } </style> <script src="contact.js"></script> </head> <body style="background-color:whitesmoke";> <!--Topbar--> <div class="topbar"> <h3> Dylan Jude Bautista </h3> <div class="dropdown" style="padding-right: 30px"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" style="width:25vw ;" data-bs-toggle="dropdown" aria-expanded="false"> Navigation </button> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="dropdownMenuButton1"> <li><a class="dropdown-item" href="index.html">Home</a></li> <li><a class="dropdown-item" href="about-me.html">About Me</a></li> <li><a class="dropdown-item" href="project-page.html">Project Page</a></li> <li><a class="dropdown-item" href="contact-me.html">Contact Me</a></li> </ul> </div> </div> <!--separator--> <div style="height: 3vh; background-color:rgb(56, 56, 56);"></div> <header style=" display:flex; align-items:center; justify-content: center; height: 22vh; background-color: rgb(56, 56, 56)"> <h1 class="opening-text" style="text-align: center;"> Contact Me </h1> </header> <main> <div style="display: flex; justify-content: center; padding-top:1vh; background-color: silver;"> <p style="width: 60vw;"> Thanks so Much for reaching out! I will soon be in contact with you. </p> </div> <div class="d-grid gap-2"><a class="btn btn-dark" role="button" href="index.html">Click Here to return to home page.</a></div> </main> <div style="height: 10vh; background-color: silver;"></div> <footer> <p style="flex-grow: 1; font-size: 20; font-family: 'Playfair Display', serif;"> Get in touch at <u>dylanjudebautista@icloud.com</u><br> LinkedIn profile: <a href="https://www.linkedin.com/in/dylan-bautista-a924a1210/" target="_blank">https://www.linkedin.com/in/dylan-bautista-a924a1210 </a><br> Find me on Handshake as <u>Dylan Bautista</u> </p> <h2> Website Constructed by DJ Bautista using HTML, CSS, JavaScript, <small>w/bootstrap</small> </h2> </footer> <!--bootstrap stuff--> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
import { CardItem } from './CardItem.component'; interface Props { items: IProspect[]; name: string; color: string; isDragging: boolean; handleDragging: (dragging: boolean) => void; handleUpdateList: (id: number, status: string) => void; } export const ContainerCards = ({ items = [], name, color, isDragging, handleDragging, handleUpdateList }: Props) => { const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); }; const handleDrop = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); const id = +e.dataTransfer.getData('text'); handleUpdateList(id, name); handleDragging(false); }; return ( <div className={`min-w-[350px] rounded-xl h-full overflow-hidden flex-1 flex flex-col border-2`} onDragOver={handleDragOver} onDrop={handleDrop} > <p style={{ backgroundColor: color, color: parseInt(color.replace('#', ''), 16) > 0xffffff / 2 ? '#000' : '#fff' }} className="border-b-2 border-slate-100 capitalize font-bold p-2 text-center" > {name} </p> <div className="h-[94%] overflow-y-auto"> {items.map( (item) => name === item.prospect_status?.name && ( <CardItem data={item} key={item.id} handleDragging={handleDragging} /> ), )} </div> </div> ); };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GPS Access with Flask</title> </head> <body> <h1>GPS Access with Flask</h1> <div id = "details"></div> <script> var reqcount = 0; navigator.geolocation.watchPosition(successCallback, errorCallback, options); function successCallback(position) { const {accuracy, latitude, longitude, altitude, heading, speed} = position.coords; reqcount++; // Update details on the webpage details.innerHTML = "Accuracy: " + accuracy + "<br>"; details.innerHTML += "Latitude: " + latitude + " | Longitude: " + longitude + "<br>"; details.innerHTML += "Speed: " + speed + "<br>"; // Send latitude and longitude to server-side Python script using AJAX sendDataToPython(latitude, longitude); } function errorCallback(error) { // Handle errors if needed } var options = { enableHighAccuracy: false, timeout: 5000, } function sendDataToPython(latitude, longitude) { // Create an XMLHttpRequest object var xhr = new XMLHttpRequest(); // Define the POST request endpoint (URL of the Python script) var url = "http://127.0.0.1:5000/update_location"; // Replace with your server URL // Prepare the data to be sent as JSON var data = { "latitude": latitude, "longitude": longitude }; // Convert data to JSON format var jsonData = JSON.stringify(data); // Configure the request xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); // Send the request with the data xhr.send(jsonData); } </script> </body> </html>
import { z } from "zod"; import { getYear } from "@/utils/getYear"; import DOMPurify from "isomorphic-dompurify"; export const reviewListSchema = z.array( z.object({ id: z.string(), movieId: z.number(), title: z.string(), description: z.string(), rating: z.number(), user: z.object({ id: z.string(), name: z.string(), avatarUrl: z.string(), }), }) ); export const createReviewData = z .object({ title: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), description: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), rating: z .string({ errorMap: () => ({ message: "Field required" }) }) .min(1, "Field required"), userId: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), movieId: z .number({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), }) .transform((review) => { const cleanDescription = DOMPurify.sanitize(review.description); return { ...review, description: cleanDescription }; }); export const editReviewData = z .object({ id: z.string(), title: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), description: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), rating: z .string({ errorMap: () => ({ message: "Field required" }) }) .min(1, "Field required"), userId: z .string({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), movieId: z .number({ errorMap: () => ({ message: "Field required" }), }) .min(1, "Field required"), }) .transform((review) => { const cleanDescription = DOMPurify.sanitize(review.description); return { ...review, description: cleanDescription }; }); export const reviewSchema = z .object({ id: z.string(), title: z.string(), description: z.string(), rating: z.number(), user: z.object({ id: z.string().uuid(), name: z.string(), avatarUrl: z.string(), }), movie: z.object({ poster: z.object({ src: z.string().nullable(), base64: z.string(), }), title: z.string(), releaseDate: z.string(), genres: z.array( z.object({ id: z.number(), name: z.string(), }) ), }), }) .transform((review) => { const { movie: { releaseDate, ...movieRest }, ...rest } = review; return { ...rest, movie: { ...movieRest, releaseYear: getYear(releaseDate), }, }; });
package com.jintin.bundle.key import io.mockk.every import io.mockk.verify import org.junit.Before import org.junit.Test class BooleanArrayKeyTest : BaseKeyTest() { private val key = BooleanArrayKey("Test") private val expect = BooleanArray(2) @Before fun setup() { every { bundle.getBooleanArray(any()) } returns expect every { persistableBundle.getBooleanArray(any()) } returns expect every { intent.getBooleanArrayExtra(any()) } returns expect } @Test fun putTest() { bundle[key] = expect verify(exactly = 1) { bundle.putBooleanArray(key.key, expect) } } @Test fun putPersistTest() { persistableBundle[key] = expect verify(exactly = 1) { persistableBundle.putBooleanArray(key.key, expect) } } @Test fun putIntentTest() { intent.putExtra(key, expect) verify(exactly = 1) { intent.putExtra(key.key, expect) } } @Test fun getTest() { val result = bundle[key] verify(exactly = 1) { bundle.getBooleanArray(key.key) } assert(result.contentEquals(expect)) } @Test fun getPersistTest() { val result = persistableBundle[key] verify(exactly = 1) { persistableBundle.getBooleanArray(key.key) } assert(result.contentEquals(expect)) } @Test fun getIntentTest() { val result = intent.getExtra(key) verify(exactly = 1) { intent.getBooleanArrayExtra(key.key) } assert(result.contentEquals(expect)) } }
import { Sequelize } from 'sequelize'; import { CacheStats } from '../types'; import { SyPersistMixin } from './mixins/SyPersistMixin'; import { SyLogger } from '../../logging/SyLogger'; /** * @todo persist mixin in clients, so the proper cache can be passed? */ export abstract class SyBaseCache<T> { public cache!: Map<any, any>; public database: Sequelize; public readonly logger: SyLogger; public cacheStats: CacheStats; public isInitialised: boolean; public evictionIntervalId?: NodeJS.Timeout; public declare persistMixin: SyPersistMixin<T>; constructor(database: Sequelize, logger: SyLogger) { this.logger = logger; this.database = database; this.cacheStats = { hits: 0, misses: 0, evictions: 0 }; this.persistMixin = new SyPersistMixin(this.cache, this.database, this.logger); this.registerShutdownHandler(); this.isInitialised = false; } /** * Registers a shutdown handler. */ private registerShutdownHandler(): void { process.on('SIGTERM', async () => { this.logger.info('Process is shutting down...'); await this.close(); process.exit(0); }); } /** * Stops the recurring process started by `startEvictingExpiredItems()` that evicts expired items * from the cache. */ public stopEvictingExpiredItems(): void { if (this.evictionIntervalId) { clearInterval(this.evictionIntervalId); this.evictionIntervalId = undefined; } } /** * Starts the cache. * @returns {Promise<void>} */ public async start(): Promise<void> { if (!this.isInitialised) { try { this.logger.info('Cache Initiated'); await this.persistMixin.loadCacheFromDatabase(); this.isInitialised = true; } catch (error: any) { this.logger.error('Error during cache start:', error); throw error; } } } /** * Closes the cache. * @returns {Promise<void>} */ public async close(): Promise<void> { try { this.stopEvictingExpiredItems(); await this.persistMixin.saveCacheToDatabase(); this.isInitialised = false; } catch (error: any) { this.logger.error('Error during cache close:', error); } } /** * Gets the cache stats. * @returns {{ hits: number; misses: number; evictions: number }} The cache stats. */ public getCacheStats(): { hits: number; misses: number; evictions: number } { return this.cacheStats; } /** * Monitors the performance of the cache. */ public monitorCachePerformance(): void { const hitRatio = this.cacheStats.hits / (this.cacheStats.hits + this.cacheStats.misses); if (hitRatio < 0.8) { this.logger.error(`Cache hit ratio dropped below 80%: ${hitRatio}`); } if (this.cacheStats.evictions > 100) { this.logger.error(`Cache evictions exceeded 100: ${this.cacheStats.evictions}`); } } // public incrementCacheMisses(): void { this.cacheStats.misses++; } // public incrementCacheHits(): void { this.cacheStats.hits++; } }
import { View, ScrollView, Image, TouchableOpacity } from 'react-native' import React, { useEffect, useState } from 'react' import { colors, defaultStyle } from '../../styles/styles' import Header from '../../components/Header' import PageHeading from '../../components/PageHeading' import ImageCard from '../../components/ImageCard' import { Avatar, Button } from 'react-native-paper' import mime from 'mime'; import { useAddProductImageMutation, useDeleteProductImageMutation, useGetProductDetailsQuery } from '../../redux/api/apiSlices/productApiSlice' import Loader from '../../components/Loader' import { Toast } from 'react-native-toast-message/lib/src/Toast' const ProductImages = ({ navigation, route }) => { const [addImage, { isLoading: isAddImageLoading }] = useAddProductImageMutation(); const [deleteImage, { isLoading: isDeleteImageLoading }] = useDeleteProductImageMutation(); const [images, setImages] = useState(route.params.images); const [productId] = useState(route.params.id); const [image, setImage] = useState(null); const [imageChanged, setImageChanged] = useState(false); const [productDetailsID] = useState(route.params.productDetailsID); const { data, isLoading: isProductLoading } = useGetProductDetailsQuery(productDetailsID); const productImages = data?.product.images; const deleteHandler = async (imageId) => { if (images.length < 2) return Toast.show({ type: "error", text1: 'The product must have at least one image', }); try { await deleteImage({productId, imageId}).unwrap(); } catch { } }; const submitHandler = async () => { const myForm = new FormData(); myForm.append("file", { uri: image, type: mime.getType(image), name: image.split("/").pop(), }); try { await addImage({ productId, formData: myForm }).unwrap(); } catch { } }; useEffect(() => { if (route.params?.image) { setImage(route.params.image); setImageChanged(true); } }, [route.params]); useEffect(() => { setImages(productImages); }, [productImages]); return ( <View style={{ ...defaultStyle, backgroundColor: colors.color5 }}> <Header back={true} /> {/* Heading */} <PageHeading text={"Manage Product Images"} paddingTopStyle={70} /> {isProductLoading ? <Loader /> : ( <> <ScrollView style={{ marginBottom: 20 }}> <View style={{ backgroundColor: colors.color2, padding: 40, minHeight: 400 }}> { images.map(i => ( <ImageCard key={i._id} src={i.url} id={i._id} deleteHandler={deleteHandler} /> )) } </View> </ScrollView> <View style={{ padding: 20, borderRadius: 10, backgroundColor: colors.color3 }}> <Image style={{ backgroundColor: colors.color2, width: 100, height: 100, alignSelf: "center", resizeMode: "contain" }} source={{ uri: image }} /> <View style={{ flexDirection: "row", justifyContent: "center" }}> <TouchableOpacity TouchableOpacity={0.8} onPress={() => navigation.navigate("camera", { updateProduct: true })}> <Avatar.Icon icon={"camera"} size={30} color={colors.color3} style={{ backgroundColor: colors.color2, margin: 10 }} /> </TouchableOpacity> </View> <Button style={{ backgroundColor: colors.color1, padding: 6 }} textColor={colors.color2} loading={isAddImageLoading} onPress={submitHandler} disabled={!imageChanged}> Add </Button> </View> </> )} </View> ) } export default ProductImages
import { render, screen } from '@testing-library/react'; import { getPeople } from './api/people'; import App from './App'; import data from './data.json'; test('It should show a six characters of the list from API', async () => { const list = await getPeople(); console.log("Running test async..."); expect(list.results[6].name).toBe("Beru Whitesun lars"); }); describe("StarsWars", () => { beforeAll(() => jest.spyOn(window, 'fetch')); test('It should show a list of characters from API', async () => { window.fetch.mockResolvedValueOnce({ ok: true, json: async () => data, }); render(<App />); expect(window.fetch).toHaveBeenCalledTimes(1) expect(window.fetch).toHaveBeenCalledWith('https://swapi.dev/api/people/'); for (let character of data.results) { expect(await screen.findByText(character.name)).toBeInTheDocument(); } }); test('It should show an error when has a network error', async () => { window.fetch.mockRejectedValueOnce(new Error('Network error')); render(<App />); expect(await screen.findByText("Network error")).toBeInTheDocument(); }); /*test('It should show a list of characters including Luke Skywalker', () => { render(<App />); expect(screen.getByText('Luke Skywalker')).toBeInTheDocument(); }); test('It should show a list of characters from json file', () => { render(<App />); for (let character of data.results) { expect(screen.getByText(character.name)).toBeInTheDocument } });*/ });
--- title: "Top 10 iPhone Lens Capabilities in iOS 11 for 2024" date: 2024-06-04T10:18:19.287Z updated: 2024-06-05T10:18:19.287Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "This Article Describes Top 10 iPhone Lens Capabilities in iOS 11 for 2024" excerpt: "This Article Describes Top 10 iPhone Lens Capabilities in iOS 11 for 2024" keywords: "IPhone Lens Features,IOS 11 Camera Enhancements,Top iPhones 10X Zoom,IOS 11 Lens API,ProLens in iOS 11,Macro Photography on iPhone,Wide Angle Zoom in iOS" thumbnail: https://thmb.techidaily.com/3dd5b17c533ab88ed9cc0f3b00c7a2aa3b7c864b4f9c2a1611133710cbbaabe1.jpg --- ## Top 10 iPhone Lens Capabilities in iOS 11 # 10 iPhone Camera Features You Should Know in iOS 11 ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) ##### Ollie Mattison Mar 27, 2024โ€ข Proven solutions iPhone's camera has been setting the standards for Smartphone cameras since the first model of the device was introduced to the public by Steve Jobs a little over a decade ago. The optics of iPhone cameras are without question powerful, but it is the combination of the software and the hardware that makes these cameras truly unique. **You may also like:** [Best Camera Apps for iPhone X/10/8 Plus/7 Plus](https://tools.techidaily.com/wondershare/filmora/download/) Each iPhone photographer has to ask themselves the same question: 'Am I really using the full capacity of my camera?'If the answer is no, maybe these iPhone camera features can help you improve the quality of your photos. ## 10 iPhone Camera Features You Should Know in iOS 11 The quality of your photos is in direct relation to your level of familiarity with the camera's features because the more you know about the camera the better you will be at finding the proper use for those features. #### 1\. Don't Be Shy to Use the Grid Mode ![](https://images.wondershare.com/filmora/article-images/grid-mode-iphone.jpg) Image resource: Macworld If you want to improve your photo taking skills, you must start paying attention to picture composition. Fortunately, the iPhone camera app offers the Grid Mode that divides the screen into nine equal parts. The grid will provide assistance in placing the subjects of your photos at the very center of the picture or when learning how to use the rule of thirds, one of the most basic composition techniques in photography. #### 2\. Set the Focus and Exposure manually ![](https://images.wondershare.com/filmora/article-images/set-focus-iphone.jpg) Image resource: iPhone Photography School Relying on auto settings will not get you far in the photography world. Even though your iPhone is perfectly capable of setting the exposure or focus automatically, adjusting these values manually will provide you with more control over the process of taking a photo. Choosing where the focal point in your photo will be and finding the perfect exposure by yourself will allow you to highlight the subjects of your pictures and it will enable you to decide how bright or dark your photo is going to be. #### 3\. HDR Photos Have More Balanced Lightning ![](https://images.wondershare.com/filmora/article-images/turn-on-hdr.jpg) Image resource: Gadget Bistro Malaysia Utilizing the HDR or High Dynamic Range feature is yet another effective way to control the exposure of your pictures. When activated, HDR feature will allow your iPhone to combine three different exposures in a single shot, and the result will be a picture that has a higher amount of detail in its shadows and highlights. #### 4\. Use the Timer to Stabilize Your Shots ![](https://images.wondershare.com/filmora/article-images/use-timer-on-iphone.jpg) iPhone X weighs only 174 grams, which makes it nearly impossible to hold perfectly still. This complicates things even further in difficult light conditions, but the Timer feature on iPhone X can help you solve this problem. You can compose your shot and set the Timer for 3 or 10 seconds and the device will take ten photos in a row, which will enable you to select the sharpest photo and delete the others. #### 5\. Edit Live Photos Taking Live Photos hasn't changed at all on the new model of the iPhone, but now you can also edit live photos in pretty much the same way you would edit a still photo. You can turn off the sound, crop or rotate live photos effortlessly, as well as apply filters, adjust color balance or improve lightning on all of your live photos. #### 6\. QR Codes Detection ![](https://images.wondershare.com/filmora/article-images/qr-detection-iphone.jpg) Image resource: 9to5Mac QR codes are actually quite convenient because they save you the trouble of typing the URL by yourself. The iOS 11 is the first iPhone OS with the ability to read QR codes. All you need to do is open your camera app and point it in the direction of the QR code you want to view, and your iPhone X will do the rest. #### 7\. Take Selfies in Portrait Mode - Only for iPhone X ![](https://images.wondershare.com/filmora/article-images/selfie-portrait-mode-iphone.jpg) Image resource: Tom's Guide The True Depth camera option that is now available on iPhone X will enable you to use the Portrait mode on your front camera. This iPhone X Portrait mode lets you control the depth of field, which means that objects closest to the lens are going to be crispy sharp, and the rest of the picture is going to have a smooth artistic blur. #### 8\. Improvements of the Video Features - iPhone X/8 The rear camera on iPhone X is capable of capturing 4K videos at 30 or at 60 fps, and you can also use it to record slow-motion 1080p videos at 120 or at 240 fps. These features are a significant step up from the previous iPhone model both in terms of video image quality and in terms of possibilities they provide to iPhone X owners. #### 9\. Dual Optical Image Stabilization Lets you Take Better Photos - iPhone X/8 ![](https://images.wondershare.com/filmora/article-images/dual-image-stabilization-iphone.jpg) Keeping the moving objects in focus is a major concern regardless of the camera you are using. We were excited about the [dual camera feature in iPhone 7](https://tools.techidaily.com/wondershare/filmora/download/), now the Dual Optical Image Stabilization feature in iOS 11 reduces motion blur and it also decreases the impact the camera shakes have on your photos. iPhone 8's Optical Image Stabilization has been improved on iPhone X and it works alongside the image sensor to ensure that all pictures taken with this device are razor sharp. #### 10\. Portrait Lighting Lets You Adjust Light to Best Fit Your Subject - iPhone X/8 ![](https://images.wondershare.com/filmora/article-images/portrait-lighting-iphone.jpg) iPhone 8 Plus and iPhone X offer a new feature, specifically designed to let you find the perfect lighting for the subject of your photos. This feature doesn't work like a filter, but rather like a real-time light meter, that calculates the optimum light values on the face of the person or persons depicted in a photo. ## Post Production Software for iPhone photography iPhone photographers, who would like to take their photos and videos a step further will unquestionably benefit from using [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/). The editor lets you create 9:16 aspect ratio images, designed to help mobile users who don't want to have the black bars alongside the edges of their vertically oriented photos and videos. Adding blur effects to your photos or videos, enhancing the colors or applying effects to your videos are just a few out of many possibilities provided by the Wondershare's software. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024โ€ข Proven solutions iPhone's camera has been setting the standards for Smartphone cameras since the first model of the device was introduced to the public by Steve Jobs a little over a decade ago. The optics of iPhone cameras are without question powerful, but it is the combination of the software and the hardware that makes these cameras truly unique. **You may also like:** [Best Camera Apps for iPhone X/10/8 Plus/7 Plus](https://tools.techidaily.com/wondershare/filmora/download/) Each iPhone photographer has to ask themselves the same question: 'Am I really using the full capacity of my camera?'If the answer is no, maybe these iPhone camera features can help you improve the quality of your photos. ## 10 iPhone Camera Features You Should Know in iOS 11 The quality of your photos is in direct relation to your level of familiarity with the camera's features because the more you know about the camera the better you will be at finding the proper use for those features. #### 1\. Don't Be Shy to Use the Grid Mode ![](https://images.wondershare.com/filmora/article-images/grid-mode-iphone.jpg) Image resource: Macworld If you want to improve your photo taking skills, you must start paying attention to picture composition. Fortunately, the iPhone camera app offers the Grid Mode that divides the screen into nine equal parts. The grid will provide assistance in placing the subjects of your photos at the very center of the picture or when learning how to use the rule of thirds, one of the most basic composition techniques in photography. #### 2\. Set the Focus and Exposure manually ![](https://images.wondershare.com/filmora/article-images/set-focus-iphone.jpg) Image resource: iPhone Photography School Relying on auto settings will not get you far in the photography world. Even though your iPhone is perfectly capable of setting the exposure or focus automatically, adjusting these values manually will provide you with more control over the process of taking a photo. Choosing where the focal point in your photo will be and finding the perfect exposure by yourself will allow you to highlight the subjects of your pictures and it will enable you to decide how bright or dark your photo is going to be. #### 3\. HDR Photos Have More Balanced Lightning ![](https://images.wondershare.com/filmora/article-images/turn-on-hdr.jpg) Image resource: Gadget Bistro Malaysia Utilizing the HDR or High Dynamic Range feature is yet another effective way to control the exposure of your pictures. When activated, HDR feature will allow your iPhone to combine three different exposures in a single shot, and the result will be a picture that has a higher amount of detail in its shadows and highlights. #### 4\. Use the Timer to Stabilize Your Shots ![](https://images.wondershare.com/filmora/article-images/use-timer-on-iphone.jpg) iPhone X weighs only 174 grams, which makes it nearly impossible to hold perfectly still. This complicates things even further in difficult light conditions, but the Timer feature on iPhone X can help you solve this problem. You can compose your shot and set the Timer for 3 or 10 seconds and the device will take ten photos in a row, which will enable you to select the sharpest photo and delete the others. #### 5\. Edit Live Photos Taking Live Photos hasn't changed at all on the new model of the iPhone, but now you can also edit live photos in pretty much the same way you would edit a still photo. You can turn off the sound, crop or rotate live photos effortlessly, as well as apply filters, adjust color balance or improve lightning on all of your live photos. #### 6\. QR Codes Detection ![](https://images.wondershare.com/filmora/article-images/qr-detection-iphone.jpg) Image resource: 9to5Mac QR codes are actually quite convenient because they save you the trouble of typing the URL by yourself. The iOS 11 is the first iPhone OS with the ability to read QR codes. All you need to do is open your camera app and point it in the direction of the QR code you want to view, and your iPhone X will do the rest. #### 7\. Take Selfies in Portrait Mode - Only for iPhone X ![](https://images.wondershare.com/filmora/article-images/selfie-portrait-mode-iphone.jpg) Image resource: Tom's Guide The True Depth camera option that is now available on iPhone X will enable you to use the Portrait mode on your front camera. This iPhone X Portrait mode lets you control the depth of field, which means that objects closest to the lens are going to be crispy sharp, and the rest of the picture is going to have a smooth artistic blur. #### 8\. Improvements of the Video Features - iPhone X/8 The rear camera on iPhone X is capable of capturing 4K videos at 30 or at 60 fps, and you can also use it to record slow-motion 1080p videos at 120 or at 240 fps. These features are a significant step up from the previous iPhone model both in terms of video image quality and in terms of possibilities they provide to iPhone X owners. #### 9\. Dual Optical Image Stabilization Lets you Take Better Photos - iPhone X/8 ![](https://images.wondershare.com/filmora/article-images/dual-image-stabilization-iphone.jpg) Keeping the moving objects in focus is a major concern regardless of the camera you are using. We were excited about the [dual camera feature in iPhone 7](https://tools.techidaily.com/wondershare/filmora/download/), now the Dual Optical Image Stabilization feature in iOS 11 reduces motion blur and it also decreases the impact the camera shakes have on your photos. iPhone 8's Optical Image Stabilization has been improved on iPhone X and it works alongside the image sensor to ensure that all pictures taken with this device are razor sharp. #### 10\. Portrait Lighting Lets You Adjust Light to Best Fit Your Subject - iPhone X/8 ![](https://images.wondershare.com/filmora/article-images/portrait-lighting-iphone.jpg) iPhone 8 Plus and iPhone X offer a new feature, specifically designed to let you find the perfect lighting for the subject of your photos. This feature doesn't work like a filter, but rather like a real-time light meter, that calculates the optimum light values on the face of the person or persons depicted in a photo. ## Post Production Software for iPhone photography iPhone photographers, who would like to take their photos and videos a step further will unquestionably benefit from using [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/). The editor lets you create 9:16 aspect ratio images, designed to help mobile users who don't want to have the black bars alongside the edges of their vertically oriented photos and videos. Adding blur effects to your photos or videos, enhancing the colors or applying effects to your videos are just a few out of many possibilities provided by the Wondershare's software. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://some-guidance.techidaily.com/2024-approved-streamline-conversion-selecting-the-top-10-free-tools/"><u>2024 Approved Streamline Conversion Selecting the Top 10 Free Tools</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-mastering-gopro-essentials-of-time-lapse-photography/"><u>In 2024, Mastering GoPro Essentials of Time-Lapse Photography</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-troubleshooting-tips-fixing-srt-from-premiere-freeze/"><u>[New] Troubleshooting Tips Fixing SRT From Premiere Freeze</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unhackable-blueprint-for-inserting-your-tiktok-links/"><u>2024 Approved Unhackable Blueprint for Inserting Your TikTok Links</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-neo-theater-narratives-virtual-realms/"><u>[Updated] Neo-Theater Narratives Virtual Realms</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-top-innovators-defining-next-gen-vr-experiences/"><u>2024 Approved Top Innovators Defining Next-Gen VR Experiences</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unveiling-30-preferred-steadicam-models-for-high-quality-dslr-projects/"><u>2024 Approved Unveiling 30 Preferred Steadicam Models for High-Quality DSLR Projects</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-the-ultimate-blueprint-for-srt-file-excellence/"><u>In 2024, The Ultimate Blueprint for SRT File Excellence</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-transforming-srt-a-complete-reference-guide-for-conversion/"><u>In 2024, Transforming SRT A Complete Reference Guide for Conversion</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-unveiling-ffxp-an-in-depth-guide/"><u>In 2024, Unveiling FFXP An In-Depth Guide</u></a></li> <li><a href="https://some-guidance.techidaily.com/unlock-the-secrets-of-your-lost-iphone-x-for-2024/"><u>Unlock the Secrets of Your Lost iPhone X for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-unlock-social-potential-with-easy-to-follow-tips-for-xbox-and-zoom-users/"><u>In 2024, Unlock Social Potential with Easy-to-Follow Tips for Xbox and Zoom Users</u></a></li> <li><a href="https://some-guidance.techidaily.com/transform-streams-into-premium-4k-videos-easily-for-2024/"><u>Transform Streams Into Premium 4K Videos Easily for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-unleash-bright-potential-in-your-android-videos/"><u>[New] Unleash Bright Potential in Your Android Videos</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-unlock-optimal-video-playback-by-tuning-speed-in-snapchat/"><u>[New] Unlock Optimal Video Playback by Tuning Speed in Snapchat</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-top-social-network-sites-for-youtube-growth/"><u>[New] Top Social Network Sites for YouTube Growth</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-essence-of-unaltered-audio-ffmpegs-precision/"><u>2024 Approved The Essence of Unaltered Audio FFmpegโ€™s Precision</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-navigating-new-realities-metaverse-meets-omniverse/"><u>[Updated] Navigating New Realities Metaverse Meets Omniverse</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unveiling-the-art-of-written-visual-narratives-a-guide-on-docuscripts/"><u>2024 Approved Unveiling the Art of Written Visual Narratives A Guide on Docuscripts</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-ultimate-png-alterations-guide/"><u>2024 Approved Ultimate PNG Alterations Guide</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-stream-power-showdown-vmix-clashes-with-wirecast-for-broadcast-excellence/"><u>2024 Approved Stream Power Showdown VMix Clashes with Wirecast for Broadcast Excellence</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unleashing-the-power-of-pip-videos-with-sierras-os-advantages/"><u>2024 Approved Unleashing the Power of PIP Videos with Sierra's OS Advantages</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-the-soundtrack-of-your-phone-classic-tones-download-site-guide/"><u>[New] The Soundtrack of Your Phone Classic Tones Download Site Guide</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-streamline-your-podcasts-effective-editing-tips-for-garageband-users/"><u>In 2024, Streamline Your Podcasts Effective Editing Tips for GarageBand Users</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-utilizing-in-presentation-speech-to-text-functionality-in-powerpoint/"><u>[Updated] Utilizing In-Presentation Speech-to-Text Functionality in PowerPoint</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-tiktok-number-modification-easy-to-follow-steps/"><u>[New] TikTok Number Modification Easy to Follow Steps</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-top-choice-5-image-background-adjuster-apps-ios/"><u>[New] Top Choice 5 Image Background Adjuster Apps (iOS)</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-top-8-collaborative-video-collage-apps-for-android-users-freepaid/"><u>[Updated] Top 8 Collaborative Video Collage Apps for Android Users (Free/Paid)</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-multimedia-artists-cyber-meeting-room/"><u>[Updated] Multimedia Artists' Cyber Meeting Room</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-tiktoks-best-practices-for-stellar-edits/"><u>[New] TikTok's Best Practices for Stellar Edits</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-sustaining-system-stability-returning-to-el-capitan/"><u>In 2024, Sustaining System Stability Returning to El Capitan</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-the-metaverse-and-omniverse-a-detailed-breakdown/"><u>[New] The Metaverse & Omniverse A Detailed Breakdown</u></a></li> <li><a href="https://some-guidance.techidaily.com/periscope-prodigy-from-beginner-to-expert-for-2024/"><u>Periscope Prodigy From Beginner to Expert for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-next-wave-of-social-media-top-apps-as-periscope-alternates/"><u>[Updated] The Next Wave of Social Media Top Apps as Periscope Alternates</u></a></li> <li><a href="https://youtube-video-recordings.techidaily.com/2024-approved-discovering-best-phone-based-asmr-experiences/"><u>2024 Approved Discovering Best Phone-Based ASMR Experiences</u></a></li> <li><a href="https://extra-resources.techidaily.com/photo-perfection-seamless-text-integration-on-pc-and-mac-systems/"><u>Photo Perfection Seamless Text Integration on PC & Mac Systems</u></a></li> <li><a href="https://sound-tweaking.techidaily.com/hunt-for-virtual-assorted-digestive-noises-in-sound-libraries-for-2024/"><u>Hunt for Virtual Assorted Digestive Noises in Sound Libraries for 2024</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/new-in-2024-from-one-self-portrait-to-a-thousand-mastering-the-art-of-repeating-yourself-on-tiktok/"><u>[New] In 2024, From One Self-Portrait to a Thousand Mastering the Art of Repeating Yourself on TikTok</u></a></li> <li><a href="https://android-unlock.techidaily.com/top-10-fingerprint-lock-apps-to-lock-your-samsung-galaxy-a15-4g-phone-by-drfone-android/"><u>Top 10 Fingerprint Lock Apps to Lock Your Samsung Galaxy A15 4G Phone</u></a></li> <li><a href="https://screen-recording.techidaily.com/2024-approved-immediate-streams-from-obs-to-insta/"><u>2024 Approved Immediate Streams From OBS to Insta</u></a></li> <li><a href="https://voice-adjusting.techidaily.com/1714938348202-updated-how-to-record-your-computer-audio-in-audacity-for-2024/"><u>Updated How to Record Your Computer Audio in Audacity for 2024</u></a></li> <li><a href="https://digital-screen-recording.techidaily.com/2024-approved-in-depth-insights-perfecting-the-craft-of-screen-recording-on-macbooks/"><u>2024 Approved In-Depth Insights Perfecting the Craft of Screen Recording on MacBooks</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/updated-slow-down-the-action-top-10-video-players-for-smooth-playback-for-2024/"><u>Updated Slow Down the Action Top 10 Video Players for Smooth Playback for 2024</u></a></li> <li><a href="https://digital-screen-recording.techidaily.com/new-in-2024-premium-4k-screen-capturing-solutions/"><u>[New] In 2024, Premium 4K Screen Capturing Solutions</u></a></li> <li><a href="https://desktop-recording.techidaily.com/updated-professional-voice-recording-made-easy-with-ipad-for-2024/"><u>[Updated] Professional Voice Recording Made Easy with iPad for 2024</u></a></li> <li><a href="https://audio-shaping.techidaily.com/updated-tune-infused-photography-link-free-audio-to-images-for-2024/"><u>Updated Tune-Infused Photography Link Free Audio to Images for 2024</u></a></li> <li><a href="https://techidaily.com/how-to-reset-a-tecno-pova-6-pro-5g-phone-that-is-locked-drfone-by-drfone-reset-android-reset-android/"><u>How to Reset a Tecno Pova 6 Pro 5G Phone That Is Locked | Dr.fone</u></a></li> <li><a href="https://instagram-video-recordings.techidaily.com/updated-2024-approved-mastering-instagram-video-downloads-pcmac-guide/"><u>[Updated] 2024 Approved Mastering Instagram Video Downloads PC/Mac Guide</u></a></li> <li><a href="https://techidaily.com/the-way-to-get-back-lost-videos-from-itel-s23-by-fonelab-android-recover-video/"><u>The way to get back lost videos from Itel S23</u></a></li> <li><a href="https://facebook-video-recording.techidaily.com/2024-approved-online-persona-transformation-rendering-your-cartoon-self/"><u>2024 Approved Online Persona Transformation Rendering Your Cartoon Self</u></a></li> <li><a href="https://extra-tips.techidaily.com/in-2024-boost-engagement-with-free-intro-templates/"><u>In 2024, Boost Engagement with Free Intro Templates</u></a></li> <li><a href="https://instagram-videos.techidaily.com/transform-your-reels-6-advanced-applications-for-instagram/"><u>Transform Your Reels 6 Advanced Applications for Instagram</u></a></li> <li><a href="https://unlock-android.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-vivo-y100-5g-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Vivo Y100 5G</u></a></li> </ul></div>
import React, { useContext } from "react"; import { IoTrashBin, IoThumbsUp, IoPencil, IoClipboardSharp } from "react-icons/io5"; import { EditingVeiculoContext } from "../../context/EditingVeiculoContext"; import { FormModalContext } from "../../context/FormModalContext"; import { MovimentationContext } from "../../context/MovimentationContext"; import { useAxios } from "../../hooks/useAxios"; import api from "../../services/api"; import { Container, ButtonArea, Button } from "./styles"; export default function Veiculo({ id, marca, modelo, placa, ano }) { const { handleEditMode } = useContext(FormModalContext); const { handleMovimentationEditMode } = useContext(MovimentationContext); const { setEditingVeiculo } = useContext(EditingVeiculoContext); const { data, mutate } = useAxios("veiculos"); function handleMovimento() { handleMovimentationEditMode(marca, modelo, placa, ano); } function handleDelete() { api.delete(`/veiculos/${id}`); const updatedVeiculos = { veiculos: data.veiculos?.filter((veiculo) => veiculo._id !== id), }; mutate(updatedVeiculos, false); } function handleEdit() { handleEditMode(marca, modelo, placa, ano); setEditingVeiculo(id); } return ( <li key={id}> <Container> <h2>{placa}</h2> <p>{marca}</p> <p>{modelo}</p> <p>{ano}</p> <ButtonArea> <Button onClick={handleMovimento}> <IoClipboardSharp /> </Button> <Button onClick={handleEdit}> <IoPencil /> </Button> <Button onClick={handleDelete}> <IoTrashBin /> </Button> </ButtonArea> </Container> </li> ); }
// // MountedElement.swift // SwiftAR // // Created by Jan Luca Siewert on 04.04.21. // // Based on the implementation of Tokamak import Foundation import Combine class MountedElement<R: Renderer>: Hashable { // MARK: - Initialization /// Element is the type elements get rendered into typealias Element = R.TargetType typealias Mounted = MountedElement<R> enum ElementType { case experience(AnyExperience) case anchor(AnyAnchor) case model(AnyModel) } var mounted: ElementType var experience: AnyExperience { get { guard case .experience(let e) = mounted else { fatalError("Can't get experience from \(mounted)") } return e } set { mounted = .experience(newValue) } } var model: AnyModel { get { guard case .model(let m) = mounted else { fatalError("Can't get model from \(mounted)") } return m } set { mounted = .model(newValue) } } var anchor: AnyAnchor { get { guard case .anchor(let a) = mounted else { fatalError("Can't get anchor from \(mounted)") } return a } set { mounted = .anchor(newValue) } } var _type: Any.Type { switch mounted { case .anchor(let a): return a.type case .experience(let e): return e.type case .model(let m): return m.type } } var bodyType: Any.Type { switch mounted { case .anchor(let a): return a.bodyType case .experience(let e): return e.bodyType case .model(let m): return m.bodyType } } var element: Element? weak var parent: Mounted? var children: [Mounted]? init<M: Model>(model: M, parent: Mounted, environment: EnvironmentValues? = nil) { self.mounted = .model(AnyModel(erasing: model)) self.parent = parent self.environmentValues = environment ?? parent.environmentValues } init<A: Anchor>(anchor: A, parent: Mounted, environment: EnvironmentValues? = nil) { self.mounted = .anchor(AnyAnchor(erasing: anchor)) self.parent = parent self.environmentValues = environment ?? parent.environmentValues } init<E: Experience>(experience: E, environment: EnvironmentValues = EnvironmentValues()) { self.mounted = .experience(AnyExperience(erasing: experience)) self.environmentValues = environment } func hash(into hasher: inout Hasher) { hasher.combine(element) } static func == (lhs: MountedElement, rhs: MountedElement) -> Bool { return lhs.element == rhs.element } // MARK: - Mounting func mount(with reconciler: StackReconciler<R>, to parent: R.TargetType? = nil) { updateEnvironment() switch mounted { case .experience(let e): children = createChild(for: e, reconciler: reconciler) case .model(let m): children = createChild(for: m, reconciler: reconciler) case .anchor(let a): children = createChild(for: a, reconciler: reconciler) } // Todo: Inject state and environment! element = reconciler.mount(self, to: parent) children?.forEach { $0.mount(with: reconciler, to: element) } } func createChild(for experience: AnyExperience, reconciler: StackReconciler<R>) -> [MountedElement] { print("Creating child for \(String(describing: experience.type)) of type \(String(describing: type(of: experience.bodyType.self)))") let body = reconciler.render(mountedExperience: self) let element = MountedElement(anchor: body, parent: self) return [element] } func createChild(for anchor: AnyAnchor, reconciler: StackReconciler<R>) -> [MountedElement] { print("Creating child for \(String(describing: anchor.type)) of type \(String(describing: type(of: anchor.bodyType.self)))") let body = reconciler.render(mountedAnchor: self) let element = MountedElement(model: body, parent: self) return [element] } func createChild(for model: AnyModel, reconciler: StackReconciler<R>) -> [MountedElement] { if let m = model.model as? ChildProvidingModel { print("Creating Child for ChildProvidingModel \(model.type)") return m.children.map { MountedElement(model: $0, parent: self) } } print("Creating child for \(String(describing: model.type))") guard model.bodyType != Never.Type.self else { print("Skipping child for \(model.type)") return [] } print("Mounting children for \(model.type)") let body = reconciler.render(mountedModel: self) let child = MountedElement<R>(model: body, parent: self) return [child] } func update(with reconciler: StackReconciler<R>) { guard let element = element else { return } updateEnvironment() switch mounted { case .experience(let e): self.update(experience: e, with: reconciler, element: element) case .anchor(let a): self.update(anchor: a, with: reconciler, element: element) case .model(let m): self.update(model: m, with: reconciler, element: element) } } private func update(experience: AnyExperience, with reconciler: StackReconciler<R>, element target: R.TargetType) { let element = reconciler.render(mountedExperience: self) reconciler.reconcile( self, with: element, getElementType: { $0.type }, updateChild: { $0.environmentValues = environmentValues $0.anchor = AnyAnchor(erasing: element) }, mountChild: { let child = MountedElement(anchor: $0, parent: self) // child.mount(with: reconciler, to: target) return child } ) } private func update(anchor: AnyAnchor, with reconciler: StackReconciler<R>, element target: R.TargetType) { let element = reconciler.render(mountedAnchor: self) reconciler.reconcile( self, with: element, getElementType: { $0.type }, updateChild: { $0.environmentValues = environmentValues $0.model = AnyModel(erasing: element) reconciler.updateWithRenderer(self) }, mountChild: { let child = MountedElement(model: $0, parent: self) // child.mount(with: reconciler, to: target) return child } ) } private func update(model: AnyModel, with reconciler: StackReconciler<R>, element target: R.TargetType) { guard model.bodyType != Never.Type.self else { reconciler.updateWithRenderer(self) let newChildren = (model.model as? ChildProvidingModel)?.children switch (children, newChildren) { case (nil, nil): break // Nothing to do case (nil, .some(let newChildren)): let newElements = newChildren.map { Mounted(model: $0, parent: self) } self.children = newElements newElements.forEach { $0.mount(with: reconciler, to: target) } case (.some, nil): children?.forEach({ $0.update(with: reconciler) }) case (.some(let children), .some(let newChildren)): for i in 0..<children.count { guard i < newChildren.count else { // Some childs were removed, unmount them later after the loop break } let oldChild = children[i] let newChild = newChildren[i] let oldChildType = TypeInfo.typeConstructorName(oldChild._type) let newChildType = TypeInfo.typeConstructorName(newChild.type) if oldChildType == newChildType { oldChild.environmentValues = environmentValues oldChild.updateEnvironment() oldChild.model = newChild oldChild.update(with: reconciler) } else { oldChild.unmount(with: reconciler) let newElement = Mounted(model: newChild, parent: self) newElement.mount(with: reconciler, to: target) self.children?[i] = newElement } // reconciler.reconcile( // children[i], // with: newChildren[i], // getElementType: {$0.type}, // updateChild: { // $0.environmentValues = self.environmentValues // $0.updateEnvironment() // $0.model = newChildren[i] // $0.update(with: reconciler) // }, mountChild: { // MountedElement(model: $0, parent: self) // }) } if children.count > newChildren.count { for i in newChildren.count..<children.count { children[i].unmount(with: reconciler) } self.children?.removeLast(children.count - newChildren.count) } else if newChildren.count > children.count { var newElements: [Mounted] = [] for i in children.count..<newChildren.count { let new = Mounted(model: newChildren[i], parent: self) new.mount(with: reconciler, to: target) newElements.append(new) } self.children?.append(contentsOf: newElements) } } children?.forEach({ $0.environmentValues = environmentValues $0.updateEnvironment() $0.update(with: reconciler) }) if let modifier = model.model as? ApplyableModel { modifier.applyModifier({ reconciler.renderer.apply($0, to: target) }) } return } let element = reconciler.render(mountedModel: self) if let modifier = element as? ApplyableModel { modifier.applyModifier({ reconciler.renderer.apply($0, to: target) }) } reconciler.reconcile( self, with: element, getElementType: { $0.type }, updateChild: { $0.environmentValues = self.environmentValues $0.model = AnyModel(erasing: element) $0.update(with: reconciler) }, mountChild: { let child = MountedElement(model: $0, parent: self) // child.mount(with: reconciler, to: target) return child } ) } func unmount(with reconciler: StackReconciler<R>) { children?.forEach( { $0.unmount(with: reconciler) } ) reconciler.unmountFromRenderer(self) } // MARK: Storage /// A type erased storage for `@State` values var store: [Any] = [] /// A store for all subscriptions var subscriptions: [AnyCancellable] = [] var environmentValues: EnvironmentValues func updateEnvironment() { switch mounted { case .experience(let e): environmentValues.inject(into: &experience.experience, e.type) case .model(let m): environmentValues.inject(into: &model.model, m.type) case .anchor(let a): environmentValues.inject(into: &anchor.anchor, a.type) } } } extension EnvironmentValues { mutating func inject(into element: inout Any, _ type: Any.Type) { guard let info = TypeInfo.typeInfo(of: type) else { return } // Extract the view from the AnyView for modification, apply Environment changes: if let container = element as? ModifierContainer { container.environmentModifier?.modifyEnvironment(&self) } // Inject @Environment values // swiftlint:disable force_cast // `DynamicProperty`s can have `@Environment` properties contained in them, // so we have to inject into them as well. for dynamicProp in info.properties.filter({ $0.type is DynamicProperty.Type }) { guard let propInfo = TypeInfo.typeInfo(of: dynamicProp.type) else { return } var propWrapper = dynamicProp.get(from: element) as! DynamicProperty for prop in propInfo.properties.filter({ $0.type is EnvironmentReader.Type }) { var wrapper = prop.get(from: propWrapper) as! EnvironmentReader wrapper.setContent(from: self) prop.set(value: wrapper, on: &propWrapper) } dynamicProp.set(value: propWrapper, on: &element) } for prop in info.properties.filter({ $0.type is EnvironmentReader.Type }) { var wrapper = prop.get(from: element) as! EnvironmentReader wrapper.setContent(from: self) prop.set(value: wrapper, on: &element) } // swiftlint:enable force_cast } } extension TypeInfo { /// Extract all `DynamicProperty` from a type, recursively. /// This is necessary as a `DynamicProperty` can be nested. /// `EnvironmentValues` can also be injected at this point. func dynamicProperties( _ environment: inout EnvironmentValues, source: inout Any ) -> [PropertyInfo] { var dynamicProps = [PropertyInfo]() for prop in properties where prop.type is DynamicProperty.Type { dynamicProps.append(prop) guard let propInfo = TypeInfo.typeInfo(of: prop.type) else { continue } environment.inject(into: &source, prop.type) var extracted = prop.get(from: source) dynamicProps.append( contentsOf: propInfo.dynamicProperties( &environment, source: &extracted ) ) // swiftlint:disable:next force_cast var extractedDynamicProp = extracted as! DynamicProperty extractedDynamicProp.update() prop.set(value: extractedDynamicProp, on: &source) } return dynamicProps } }
import { Address } from "@/app/staff/utils/orders"; import AddressAutoComplete from "@/components/Form/AutoCompleteInput"; import { District, SpecificAddress, Ward, getDistrictsByProvince, getProvinces, getWardsByDistrictAndProvince, } from "@/libs/address"; import { removeVietnameseTones } from "@/utils/helper"; import { faCircleXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Input } from "antd"; import { KeyboardEventHandler, useState } from "react"; const provinces = getProvinces(); export default function AddressInput({ value, handleChange, className, includeSpecificAddress = true, rowLayoutOnSmallView = false, }: { value: Address; handleChange: (newAddress: Address) => void; className?: string; includeSpecificAddress?: boolean; rowLayoutOnSmallView?: boolean; }) { const [districts, setDistricts] = useState<District[]>([]); const [wards, setWards] = useState<Ward[]>([]); const [specificAddresses, setSpecificAddresses] = useState<SpecificAddress[]>( [] ); const handleChangeProvince = (province: string) => { setDistricts(getDistrictsByProvince(province)); setWards([]); setSpecificAddresses([]); handleChange({ province, district: "", ward: "", name: "", id: "" }); }; const handleChangeDistrict = (district: string) => { setWards(getWardsByDistrictAndProvince(district, value.province!)); setSpecificAddresses([]); handleChange({ district, ward: "", name: "", id: "" }); }; const handleChangeWard = (ward: string) => { setSpecificAddresses([]); handleChange({ ward, name: "", id: "" }); }; const handleEnterSpecificAddress: KeyboardEventHandler = async (e) => { if (e.key === "Enter") { e.preventDefault(); const res = await fetch( "/api/address/search?" + new URLSearchParams({ province: value.province ? value.province : "", district: value.district ? value.district : "", ward: value.ward ? value.ward : "", specificAddress: value.name ? value.name : "", }) ); const response = await res.json(); if (res.status === 200) { setSpecificAddresses(response.data); } } }; const filterOption = ( inputValue: string, option: { value: string; label: string } ) => { return ( removeVietnameseTones(option!.value) .toUpperCase() .indexOf(removeVietnameseTones(inputValue).toUpperCase()) !== -1 ); }; return ( <div className={className}> <div className="flex flex-col gap-4"> <div className={`flex ${ rowLayoutOnSmallView ? "flex-row" : "flex-col" } sm:flex-col gap-4`} > <AddressAutoComplete label="Tแป‰nh/Thร nh Phแป‘" placeholder="Tแป‰nh/Thร nh Phแป‘" required={true} value={value.province} options={provinces} onChange={handleChangeProvince} filterOption={filterOption} /> <AddressAutoComplete label="Quแบญn/Huyแป‡n" placeholder="Quแบญn/Huyแป‡n" required={true} value={value.district} options={districts} onChange={handleChangeDistrict} filterOption={filterOption} /> <AddressAutoComplete label="Xรฃ/Phฦฐแปng" placeholder="Xรฃ/Phฦฐแปng" required={true} value={value.ward} options={wards} onChange={handleChangeWard} filterOption={filterOption} /> </div> {includeSpecificAddress && ( <AddressAutoComplete label="ฤแป‹a Chแป‰ Cแปฅ Thแปƒ" placeholder="ฤแป‹a Chแป‰ Cแปฅ Thแปƒ" required={true} value={value.name} options={specificAddresses} disabled={!value.province || !value.district || !value.ward} filterOption={filterOption} onSearch={(address) => handleChange({ name: address, id: "" })} onSelect={(address, option) => { handleChange({ name: address, id: option.placeId }); }} onKeyDown={handleEnterSpecificAddress} > <Input size="large" allowClear={{ clearIcon: <FontAwesomeIcon icon={faCircleXmark} />, }} /> </AddressAutoComplete> )} </div> </div> ); }
# cython: profile=True ## # S. Rychkov, S. El-Showk, May-June 2013 # File contains prec_float and prec_interval classes : cython wrappers for mpfr_t and mpfi_t # with overloaded arithmetic operations ## # Edit by Carlos Cardona 2022 from libc.stdlib cimport malloc, free import utils.stats as stats def isinteger(a): return (isinstance(a,int) or isinstance(a,long)) def zeros(size,prec): return [ prec_float(0,prec=prec) for i in range(size)] cpdef prec_float sqrt(prec_float x): cdef prec_float ret ret = prec_float (0, prec = <int>mpfr_get_prec (x.data)) mpfr_sqrt(ret.data, x.data, MPFR_RNDD) return ret cpdef double to_double(prec_float x): return mpfr_get_d(x.data,MPFR_RNDD) # used to unpickle a prec float def make_prec_float(val, prec): return prec_float(val, prec=prec) #################### BEGIN --- CLASS ------prec_float ############################# cdef class prec_float: def __cinit__(self, value, int prec = 212): """initialize an mpfr float with precision prec, from integer, double or """ # not working for some reason #if prec < 0: # raise ValueError("precision must be specified") self.prec=prec mpfr_init2(self.data, self.prec) if isinstance (value, int): mpfr_set_si(self.data, value,MPFR_RNDD) elif isinstance(value, str): # mpfr_set_str(self.data, value, 10, MPFR_RNDD) bytes_str=value.encode('ascii') # Carlos edit mpfr_set_str(self.data, bytes_str, 10, MPFR_RNDD) elif isinstance(value, float): mpfr_set_d(self.data, value,MPFR_RNDD) elif isinstance(value, prec_float): typed_value = <prec_float>value mpfr_set(self.data, typed_value.data, MPFR_RNDD) else: raise TypeError("Prec_float can be initialized from int, str, double, or prec_float") stats.pf_init +=1 stats.pf_mem += sizeof(mpfr_t) def __dealloc__(self): mpfr_clear(self.data) # for some reason we can't access this this way stats.pf_del +=1 stats.pf_free += sizeof(mpfr_t) ## Overloaded functions def __neg__(prec_float self): """Sign flip""" ret=prec_float(0, prec = self.prec) mpfr_neg(ret.data, self.data, MPFR_RNDD) return ret def __add__(prec_float self, prec_float other): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_add(ret.data, self.data, other.data, MPFR_RNDD) stats.pf_adds += 1 return ret def __sub__(prec_float self, prec_float other): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_sub(ret.data, self.data, other.data, MPFR_RNDD) return ret def __mul__(prec_float self, prec_float other): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_mul(ret.data, self.data, other.data, MPFR_RNDD) stats.pf_mults += 1 return ret # def __div__(prec_float self, prec_float other): def __truediv__(prec_float self, prec_float other): # Carlos edit cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_div(ret.data, self.data, other.data, MPFR_RNDD) return ret def __pow__(prec_float self, prec_float other, z): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_pow(ret.data, self.data, other.data, MPFR_RNDD) return ret def log(prec_float self): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_log(ret.data, self.data, MPFR_RNDD) return ret def exp(prec_float self): cdef prec_float ret ret=prec_float(0, prec=self.prec) mpfr_exp(ret.data, self.data, MPFR_RNDD) return ret def sqrt(prec_float self): cdef prec_float ret ret = prec_float(0, prec = self.prec) mpfr_sqrt(ret.data, self.data, MPFR_RNDD) return ret def abs(prec_float self): """abs value""" ret=prec_float(0, prec = self.prec) mpfr_abs(ret.data, self.data, MPFR_RNDD) return ret # DON'T USE THESE - BUGGY # def __iadd__(prec_float self, prec_float other): # mpfr_add(self.data, self.data, other.data, MPFR_RNDD) # def __isub__(prec_float self, prec_float other): # mpfr_sub(self.data, self.data, other.data, MPFR_RNDD) # def __imul__(prec_float self, prec_float other): # mpfr_mul(self.data, self.data, other.data, MPFR_RNDD) # def __idiv__(prec_float self, prec_float other): # mpfr_div(self.data, self.data, other.data, MPFR_RNDD) def __richcmp__(prec_float self, prec_float value, int cmptype): """comparison op cmptype < 0 == 2 > 4 <= 1 != 3 >= 5""" cdef int cmp cmp = mpfr_cmp(self.data, value.data) if cmptype == 0: if cmp < 0: return True else: return False if cmptype == 2: if cmp == 0: return True else: return False if cmptype == 4: if cmp > 0: return True else: return False if cmptype == 1: if cmp <= 0: return True else: return False if cmptype == 3: if cmp != 0: return True else: return False if cmptype == 5: if cmp >= 0: return True else: return False ## Printing functions def __str__(self): bs= 2*self.prec # grossly overkill cdef char* buf = <char*> malloc(bs * sizeof(char)) mpfr_sprintf(buf, "%.Re", self.data) #return str(buf) # Carlos edit return buf.decode('ascii') def __bytes__(self): bs= 2*self.prec # grossly overkill cdef char* buf = <char*> malloc(bs * sizeof(char)) mpfr_sprintf(buf, "%.Re", self.data) return buf # Carlos edit def __repr__(self): return self.__str__() def __reduce__(self): pstr=self.__str__() #ret=(prec_float.__init__, pstr, self.prec) return (make_prec_float, (pstr, self.prec)) def bufrepr(self, buf): mpfr_sprintf(<char*>buf, "%.Re", self.data) return buf def assign_prec_float(self, value): """assigns the already initialized precision float with data from another precision float; only works if the two precision floats have the same precision""" if not isinstance(value, prec_float): raise TypeError("assign_prec_float: attempted to assign value which is not prec_float") typed_value = <prec_float>value # cast static typed copy to be able to access private fields data and prec if not self.prec == typed_value.prec: raise TypeError("assign_prec_float: attempted to assign value which has different precision") mpfr_set(self.data, typed_value.data, MPFR_RNDD) #################### BEGIN --- CLASS ------prec_interval ############################# cdef class prec_interval: def __cinit__(self, v1, v2, int prec): """initialize an mpfi float with precision prec, from integer, double, string or prec_float. If v1 is a string it should be either a number or in the form '[a,b]' and then v2 is ignored. Otherwise v1 and v2 assumed to be of the same type.""" self.prec=prec mpfi_init2(self.data, self.prec) if isinstance (v1, int): mpfi_interv_si(self.data,v1,v2) elif isinstance(v1, str): mpfi_set_str(self.data, v1, 10) elif isinstance(v1, float): mpfi_interv_d(self.data, v1, v2) elif isinstance(v1, prec_float): typed_value = <prec_float>v1 typed_value2 = <prec_float>v2 mpfi_interv_fr(self.data, typed_value.data, typed_value2.data) else: raise TypeError("Prec_interval can be initialized from int, str, double, or prec_float") def __dealloc__(self): mpfi_clear(self.data) ## Overloaded functions def __neg__(prec_interval self): """Sign flip""" ret=prec_interval(0, 0, prec = self.prec) mpfi_neg(ret.data, self.data) return ret def __add__(prec_interval self, prec_interval other): cdef prec_interval ret ret=prec_interval(0, 0, prec=self.prec) mpfi_add(ret.data, self.data, other.data) return ret def __sub__(prec_interval self, prec_interval other): cdef prec_interval ret ret=prec_interval(0, 0, prec=self.prec) mpfi_sub(ret.data, self.data, other.data) return ret def __mul__(prec_interval self, prec_interval other): cdef prec_interval ret ret=prec_interval(0, 0, prec=self.prec) mpfi_mul(ret.data, self.data, other.data) return ret def __div__(prec_interval self, prec_interval other): cdef prec_interval ret ret=prec_interval(0, 0, prec=self.prec) mpfi_div(ret.data, self.data, other.data) return ret def __pow__(prec_interval self, prec_interval other, z): cdef prec_interval ret ret=prec_interval(0, 0, prec=self.prec) mpfi_log(ret.data, self.data) mpfi_mul(ret.data, ret.data, other.data) mpfi_exp(ret.data, ret.data) return ret ## unpacks into a pair of prec_float def unpack(self): x0 = prec_float(0,prec=self.prec) x1 = prec_float(0,prec=self.prec) mpfi_get_left(x0.data, self.data) mpfi_get_right(x1.data, self.data) return (x0,x1) def length(self): x0 = prec_float(0,prec=self.prec) x1 = prec_float(0,prec=self.prec) mpfi_get_left(x0.data, self.data) mpfi_get_right(x1.data, self.data) return x1 - x0 ## Printing functions def __str__(self): return self.unpack().__str__() def __repr__(self): return self.__str__()
# global import abc from typing import Optional, Union # local import ivy class _ArrayWithLossesExperimental(abc.ABC): def l1_loss( self: Union[ivy.Array, ivy.NativeArray], target: Union[ivy.Array, ivy.NativeArray], /, *, reduction: Optional[str] = "mean", out: Optional[ivy.Array] = None, ) -> ivy.Array: """ ivy.Array instance method variant of ivy.l1_loss. This method simply wraps the function, and so the docstring for ivy.l1_loss also applies to this method with minimal changes. Parameters ---------- self input array. target input array containing the targeted values. reduction ``'mean'``: The output will be averaged. ``'sum'``: The output will be summed. ``'none'``: No reduction will be applied to the output. Default: ``'mean'``. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The L1 loss between the input array and the targeticted values. Examples -------- >>> x = ivy.array([1.0, 2.0, 3.0]) >>> y = ivy.array([0.7, 1.8, 2.9]) >>> z = x.l1_loss(y) >>> print(z) ivy.array(0.20000000000000004) """ return ivy.l1_loss(self._data, target, reduction=reduction, out=out) def smooth_l1_loss( self: ivy.Array, target: Union[ivy.Array, ivy.NativeArray], /, *, beta: Optional[float] = 1.0, reduction: Optional[str] = "mean", out: Optional[ivy.Array] = None, ) -> ivy.Array: """ ivy.Array instance method variant of ivy. smooth_l1_loss. This method simply wraps the function, and so the docstring for ivy.smooth_l1_loss also applies to this method with minimal changes. Parameters ---------- self input array containing true labels. target input array containing targeted labels. beta A float specifying the beta value for the smooth L1 loss. Default: 1.0. reduction Reduction method for the loss. Options are 'none', 'mean', or 'sum'. Default: 'mean'. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The smooth L1 loss between the given labels. Examples -------- >>> x = ivy.array([1, 2, 3, 4]) >>> y = ivy.array([2, 2, 2, 2]) >>> z = x.smooth_l1_loss(y, beta=0.5) >>> print(z) ivy.array(0.8125) """ return ivy.smooth_l1_loss( self._data, target, beta=beta, reduction=reduction, out=out )
/* * dedupv1 - iSCSI based Deduplication System for Linux * * (C) 2008 Dirk Meister * (C) 2009 - 2011, Dirk Meister, Paderborn Center for Parallel Computing * (C) 2012 Dirk Meister, Johannes Gutenberg University Mainz * * This file is part of dedupv1. * * dedupv1 is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * dedupv1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with dedupv1. If not, see http://www.gnu.org/licenses/. */ #ifndef LOG_REPLAYER_H__ #define LOG_REPLAYER_H__ #include <core/dedup.h> #include <base/locks.h> #include <base/thread.h> #include <core/idle_detector.h> #include <core/log.h> namespace dedupv1d { /** * The LogReplayer has the responsibility to replay log entries in background if any of the following * two conditions are true: * - The log is nearly full: Nearly full is usually seen as something like 70% of the log capacity * - The system is idle and the log replaying is activated * * If the system detects and idle period and if the replay during idle time is not deactivated using the configuration system, * the log replayer will replay event. When the idle period ends and the system has not been stopped before, the old state is * restored. * * TODO (dmeister) Adapt the replay speed to the amount of idle ticks. */ class LogReplayer: public dedupv1::IdleTickConsumer { DISALLOW_COPY_AND_ASSIGN(LogReplayer); public: /** * stats of the log replayer */ enum log_replayer_state { LOG_REPLAYER_STATE_CREATED,//!< LOG_REPLAYER_STATE_CREATED LOG_REPLAYER_STATE_STARTED, LOG_REPLAYER_STATE_RUNNING,//!< LOG_REPLAYER_STATE_RUNNING LOG_REPLAYER_STATE_PAUSED, //!< LOG_REPLAYER_STATE_PAUSED LOG_REPLAYER_STATE_STOPPED,//!< LOG_REPLAYER_STATE_STOPPED LOG_REPLAYER_STATE_FAILED //!< LOG_REPLAYER_STATE_FAILED }; private: /** * Default number of elements replayed at one if system is idle */ static const uint32_t kDefaultMaxAreaSizeReplaySystemIdle_ = 4096; /** * Default number of elements replayed at one if system going full */ static const uint32_t kDefaultMaxAreaSizeReplayLogFull_ = 4096; /** * Reference to the log. * Set during the startup */ dedupv1::log::Log* log_; /** * Reference to the idle detector * Set during the startup, but maybe null if no idle system is used */ dedupv1::IdleDetector* idle_detector_; /** * log replay background thread */ dedupv1::base::Thread<bool> thread_; /** * State of the log replayer. */ volatile enum log_replayer_state state_; /** * State of the log replayer thread. */ volatile bool thread_state_; /** * Lock to protected shared variables of the log replayer, e.g. the stats */ dedupv1::base::MutexLock lock_; /** * Condition that is fired if the log replayer thread stops. */ dedupv1::base::Condition cond_; /** * Sleep time between in microseconds. * Default: 50ms */ uint32_t throttle_; /** * Sleep time in microseconds when the log is nearly full * Default: 0ms */ uint32_t nearly_full_throttle_; /** * Sleep time between checks * Default: 1s */ uint32_t check_interval_; /** * Stores the state of the system before the idle period. * LOG_REPLAYER_STATE_CREATED denotes a non-set value */ enum log_replayer_state state_before_idle_; /** * iff true, the log is currently replaying items because of one of several reasons: * idleness, unpauses log replay, log full. */ bool is_replaying_; /** * lock to protect is_replaying_ */ dedupv1::base::MutexLock is_replaying_lock_; /** * Maxmimum Events to be replayed at once if system is idle */ uint32_t max_area_size_replay_system_idle_; /** * Maxmimum Events to be replayed at once if log is going full */ uint32_t max_area_size_replay_log_full_; /** * Loop method that is called in a background thread. * @return */ bool Loop(); /** * the actual loop contents */ bool DoLoop(); /** * replays a single log event. * * @param num_elements Number of Elements to replay */ dedupv1::log::log_replay_result Replay(uint32_t num_elements = 1); /** * Tries to start the log replay. * Does nothing if the log is already being replayed */ bool TryStartReplay(); /** * Tries to stop the log replay. * Does nothing if the log is already being replayed */ bool TryStopReplay(); public: /** * Constructor. * @return */ LogReplayer(); /** * Destructor * @return */ virtual ~LogReplayer(); /** * * @param log * @param idle_detector reference to the idle detector. May be null. If a idle detector is given, the client has to ensure * that the detector lives longer than the log replayer. * @return */ bool Start(dedupv1::log::Log* log, dedupv1::IdleDetector* idle_detector); /** * Runs the log replayer * @return */ bool Run(); /** * Stops the replayer * @param stop_context * @return */ bool Stop(const dedupv1::StopContext& stop_context); /** * Pauses the log replayer. * @return */ bool Pause(); /** * Resumes the log replayer * @return */ bool Resume(); /** * Configures the log replayer * * Available options: * - throttle.default: uint32_t * - throttle.nearly-full: uint32_t * - area-size-system-idle: StorageUnit * - area-size-log-full: StorageUnit * * @param option_name * @param option * @return */ bool SetOption(const std::string& option_name, const std::string& option); /** * Returns the name of the current state * @return */ const char* state_name(); /** * Returns the log of the replayer * @return */ inline dedupv1::log::Log* log(); /** * Returns the state of the log replayer * @return */ inline enum log_replayer_state state() const; /** * Called then the system is detected to be idle */ void IdleStart(); /** * Called when the system stopped to be idle */ void IdleEnd(); inline bool is_replaying() const; inline bool is_failed() const; #ifdef DEDUPV1D_TEST void ClearData(); #endif }; bool LogReplayer::is_failed() const { return state_ == LOG_REPLAYER_STATE_FAILED || (state_ == LOG_REPLAYER_STATE_PAUSED && !thread_state_) || (state_ == LOG_REPLAYER_STATE_RUNNING && !thread_state_); } dedupv1::log::Log* LogReplayer::log() { return this->log_; } LogReplayer::log_replayer_state LogReplayer::state() const { return this->state_; } bool LogReplayer::is_replaying() const { return is_replaying_; } } #endif // LOG_REPLAYER_H__
import styled from "styled-components"; import SectionHeader from "./SectionHeader"; // import useFakeFixtures from "../../hooks/fake/useFakeFixtures"; import useColor from "../../hooks/useColor"; import { mix } from "polished"; import SubTitle from "../common/SubTitle"; import Loading from "../common/Loading"; import { LazyLoadImage } from "react-lazy-load-image-component"; import "react-lazy-load-image-component/src/effects/blur.css"; import useLeagueId from "../../hooks/useLeagueId"; import useFixtures from "../../hooks/useFixtures"; interface MatchProps { $color: string; } const LatestMatchesWrapper = styled.div` flex: 1; padding: 0.5rem 1rem; border-radius: ${(props) => props.theme.border.radius}; background-color: ${(props) => props.theme.colors.secondBackground}; min-width: 250px; `; const MatchWrapper = styled.div` width: 100%; display: flex; gap: 1rem; margin-top: 1rem; @media (max-width: 950px) { flex-direction: column; } `; const Match = styled.div<MatchProps>` flex: 1; padding: 1rem 1rem; border-radius: ${(props) => props.theme.border.radius}; background-color: ${(props) => mix(0.8, "#808080", props.$color)}; `; const ScoreWrapper = styled.div` width: 100%; display: flex; align-items: center; justify-content: space-between; `; const LogoWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 1rem; gap: 0.5rem; text-align: center; `; const Logo = styled(LazyLoadImage)` width: 70%; height: auto; min-width: 50px; max-width: 100px; `; const TeamName = styled.p` font-size: 0.8rem; `; const Score = styled.div` padding: 8px; border-radius: ${(props) => props.theme.border.radius}; background-color: ${(props) => props.theme.colors.background}; min-width: 50px; text-align: center; `; const LatestMatches = () => { const color = useColor(); const leagueId = useLeagueId(); // const { // fakeLatestMatchesQuery: { data: matches, isLoading, isError }, // } = useFakeFixtures(); const { bannerLatestMatchesQuery: { data: matches, isLoading, isError }, } = useFixtures(leagueId); return ( <LatestMatchesWrapper> <SectionHeader title="์ตœ๊ทผ ๊ฒฝ๊ธฐ" src={`/league/${leagueId}/schedule`} /> {isError && <div>Error</div>} {isLoading && <Loading />} {isLoading || (matches && ( <> <MatchWrapper> <Match $color={color || "#777"}> <SubTitle subtitle={matches[0].league.round || ""} /> <ScoreWrapper> <LogoWrapper> <Logo effect="blur" src={matches[0].teams.home.logo || "Not-Name"} alt="logo" /> <TeamName>{matches[0].teams.home.name || "Not-Name"}</TeamName> </LogoWrapper> <Score>{`${matches[0].goals.home} : ${matches[0].goals.away}`}</Score> <LogoWrapper> <Logo effect="blur" src={matches[0].teams.away.logo || "Not-Name"} alt="logo" /> <TeamName>{matches[0].teams.away.name || "Not-Name"}</TeamName> </LogoWrapper> </ScoreWrapper> </Match> <Match $color={color || "#777"}> <SubTitle subtitle={matches[1]?.league.round || ""} /> <ScoreWrapper> <LogoWrapper> <Logo effect="blur" src={matches[1]?.teams.home.logo || "Not-Name"} alt="logo" /> <TeamName>{matches[1]?.teams.home.name || "Not-Name"}</TeamName> </LogoWrapper> <Score>{`${matches[1]?.goals.home || 0} : ${matches[1]?.goals.away || 0}`}</Score> <LogoWrapper> <Logo effect="blur" src={matches[1]?.teams.away.logo || "Not-Name"} alt="logo" /> <TeamName>{matches[1]?.teams.away.name || "Not-Name"}</TeamName> </LogoWrapper> </ScoreWrapper> </Match> </MatchWrapper> </> ))} </LatestMatchesWrapper> ); }; export default LatestMatches;
/* render.c: functions for rendering a peg solitaire game * Copyright (C) 2018 Juhani Numminen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "render.h" #include <gtk/gtk.h> #include <librsvg/rsvg.h> #include <math.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "callbacks.h" #include "data.h" #include "game.h" #include "i18n.h" #include "share.h" #define GAME_NOT_DRAGGING -1 static int game_dragging_at_x = GAME_NOT_DRAGGING; static int game_dragging_at_y = GAME_NOT_DRAGGING; static bool button_down = false; static GdkPoint dragging_peg = {0, 0}; static GdkCursor *hand_closed_cursor = NULL; static GdkCursor *hand_open_cursor = NULL; static GdkCursor *default_cursor = NULL; static cairo_pattern_t *hole_pattern = NULL; static cairo_pattern_t *peg_pattern = NULL; static double offset_x = 0, offset_y = 0; static double tile_size = 0; static GdkCursor *try_cursor_names(const char *names[]) { GdkDisplay *display = gtk_widget_get_display(pegSolitaireWindow); GdkCursor *cursor = NULL; for (int i = 0; names[i] && !cursor; i++) cursor = gdk_cursor_new_from_name(display, names[i]); if (!cursor) g_warning(_("The \"%s\" cursor is not available"), names[0]); return cursor; } void init_cursors(void) { default_cursor = try_cursor_names((const char *[]){"default", NULL}); hand_closed_cursor = try_cursor_names((const char *[]){"closedhand", "grabbing", NULL}); hand_open_cursor = try_cursor_names((const char *[]){"openhand", "grab", NULL}); } static void set_cursor(GdkCursor *cursor) { gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(boardDrawingArea)), cursor); } static GdkPoint widget_coords_to_cell(int x, int y) { return (GdkPoint){(x - offset_x) / tile_size, (y - offset_y) / tile_size}; } static RsvgHandle *load_svg(const char *str) { GError *err = NULL; RsvgHandle *svg = rsvg_handle_new_from_data((const guint8 *)str, strlen(str), &err); if (err) { GtkDialog *dialog = GTK_DIALOG(gtk_message_dialog_new( NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("Something went wrong.\n" "Could not load internal image data:\n" "%s"), err->message)); gtk_window_set_title(GTK_WINDOW(dialog), _("Peg Solitaire")); gtk_dialog_run(dialog); exit(1); } return svg; } static cairo_pattern_t *rsvg_to_pattern(RsvgHandle *svg) { RsvgDimensionData svg_dimensions; rsvg_handle_get_dimensions(svg, &svg_dimensions); cairo_surface_t *surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, svg_dimensions.width, svg_dimensions.height); cairo_t *cr = cairo_create(surface); rsvg_handle_render_cairo(svg, cr); cairo_pattern_t *pattern = cairo_pattern_create_for_surface(surface); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); cairo_matrix_t scale; cairo_matrix_init_scale(&scale, svg_dimensions.width, svg_dimensions.height); cairo_pattern_set_matrix(pattern, &scale); cairo_destroy(cr); cairo_surface_destroy(surface); g_object_unref(svg); return pattern; } void game_load_resources(void) { hole_pattern = rsvg_to_pattern(load_svg(hole_svg)); peg_pattern = rsvg_to_pattern(load_svg(peg_svg)); } void game_unload_resources(void) { cairo_pattern_destroy(peg_pattern); cairo_pattern_destroy(hole_pattern); } // Following functions are gtk callbacks and all their parameters are required. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" gboolean drawarea_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data) { int width = gtk_widget_get_allocated_width(widget); int height = gtk_widget_get_allocated_height(widget); double shorter_side = fmin(width, height); offset_x = 0.5 * (width - shorter_side); offset_y = 0.5 * (height - shorter_side); tile_size = shorter_side / game_board_size; cairo_translate(cr, offset_x, offset_y); cairo_scale(cr, tile_size, tile_size); cairo_set_source(cr, hole_pattern); for (int y = 0; y < game_board_size; y++) for (int x = 0; x < game_board_size; x++) if (game_board_mask[y][x]) cairo_rectangle(cr, x, y, 1, 1); cairo_fill(cr); cairo_set_source(cr, peg_pattern); for (int y = 0; y < game_board_size; y++) for (int x = 0; x < game_board_size; x++) if (game_board[y][x]) cairo_rectangle(cr, x, y, 1, 1); cairo_fill(cr); if (game_dragging_at_x != GAME_NOT_DRAGGING) { cairo_translate(cr, (game_dragging_at_x - offset_x) / tile_size - 0.5, (game_dragging_at_y - offset_y) / tile_size - 0.5); cairo_set_source(cr, peg_pattern); cairo_rectangle(cr, 0, 0, 1, 1); cairo_fill(cr); } return FALSE; } gboolean drawarea_motion(GtkWidget *widget, GdkEventMotion *event, gpointer user_data) { GdkPoint cell = widget_coords_to_cell(event->x, event->y); if (button_down) { game_dragging_at_x = event->x; game_dragging_at_y = event->y; gtk_widget_queue_draw(widget); } else if (game_is_peg_at(cell)) { set_cursor(hand_open_cursor); } else { set_cursor(default_cursor); } return FALSE; } gboolean drawarea_button_press(GtkWidget *widget, GdkEventButton *event, gpointer user_data) { if (event->button == 1 && !button_down /* && !is_game_end()*/) { GdkPoint cell = widget_coords_to_cell(event->x, event->y); if (!game_is_peg_at(cell)) return FALSE; game_dragging_at_x = event->x; game_dragging_at_y = event->y; set_cursor(hand_closed_cursor); dragging_peg = cell; button_down = true; game_toggle_cell(cell); gtk_widget_queue_draw(widget); } return FALSE; } gboolean drawarea_button_release(GtkWidget *widget, GdkEventButton *event, gpointer user_data) { if (event->button == 1 && button_down) { button_down = false; game_dragging_at_x = GAME_NOT_DRAGGING; GdkPoint dest = widget_coords_to_cell(event->x, event->y); // Either execute the move or put the peg back where we started. if (game_move(dragging_peg, dest)) { set_cursor(hand_open_cursor); update_statusbar(); if (is_game_end()) { gtk_label_set_text(statusMessageLabel, game_cheese()); } } else { game_toggle_cell(dragging_peg); } gtk_widget_queue_draw(widget); } return FALSE; } #pragma GCC diagnostic pop
<!DOCTYPE html> <html> <head> <title>Using a Function for Promises</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <script> $(document).ready(function() { const apple = new Image(), orange = new Image(), carrot = new Image(), pumpkin = new Image(), eggplant = new Image(); function loadImage(img, src) { img.src = src; return img.decode(); } loadImage(apple, "apple.png") .then(() => loadImage(orange, "orange.png")) .then(() => loadImage(carrot, "carrot.png")) .then(() => loadImage(pumpkin, "pumpkin.png")) .then(() => loadImage(eggplant, "eggplant.png")) .then(() => { $("body").append($(apple), $(orange), $(carrot), $(pumpkin), $(eggplant)); }) .catch(() => { $("body").append($("<p>The image cannot be loaded.</p>")); }) }); </script> </body> </html>
/* * @Author: lyf * @Date: 2021-02-25 16:37:45 * @LastEditors: lyf * @LastEditTime: 2021-12-13 15:07:57 * @Description: In User Settings Edit * @FilePath: /js-css-case/src/examples-react/case3/index.tsx * * context * 1. context็š„valueๅ€ผๆ”นๅ˜, ๅ…ถๅญๅญ™็ป„ๅปบไธญ ไฝฟ็”จuseContext็š„็ป„ๅปบ้ƒฝไผš้‡ๆ–ฐๆธฒๆŸ“(ๅณไฝฟ่ฏฅ็ป„ๅปบ่ขซmemoๅ‡ฝๆ•ฐๅŒ…่ฃน, ๅณไฝฟ่ฏฅ็ป„ๅปบ็š„propsๆœชๆ”นๅ˜) * 2. ๅฆ‚ไธ‹: context็š„valueๅ€ผๆœ‰ๅ‡ฝๆ•ฐ, ๅˆ™่ฏฅๅ‡ฝๆ•ฐๅฟ…้กป็”จuseCallbackๅŒ…่ฃน, ๅฆๅˆ™ๆฏๆฌกๆธฒๆŸ“้ƒฝไผš็”Ÿๆˆๆ–ฐๅ‡ฝๆ•ฐ */ import React, { useState, useCallback, useMemo } from 'react'; import ShowX from './showX'; import ShowY from './showY'; import Show from './show'; import { useMutationObserver } from '@hooks/utils'; import Context from './constants'; const Case3 = () => { const [time, setTime] = useState(Date.now()); const [state, setState] = useState({ x: 1, y: 1, m: 1 }); const microtask = useMutationObserver(() => { console.log('microtask...'); }); const addX = useCallback(() => { // ่ฟ™็งๆ–นๅผ, ไป–ๅœจdepsไธญๅฟ…้กปๆœ‰state // const { y } = state // setState((state) => ({ ...state, y: y + 1 })) // ๆŽจ่ๅฆ‚ไธ‹ๆ–นๅผ, ไธ้œ€่ฆไปปไฝ•deps setState(({ x, y, m }) => ({ x: x + 1, y, m })); }, []); const addY = useCallback(() => { setState(({ x, y, m }) => ({ x, y: y + 1, m })); }, []); const addZ = useCallback(() => { setTime(Date.now()); }, []); const handleM = () => { setState((state) => ({ ...state, m: state.m + 1 })); }; const handleMicrotask = () => { microtask(); Promise.resolve().then(() => { console.log('handleMicrotask...'); }); setTimeout(() => { console.log('handleMicrotask setTimeout...'); }, 0); }; const value = useMemo(() => ({ ...state, addX, addY, addZ }), [state]); return ( <Context.Provider value={value}> time: {time} <ShowX /> <ShowY /> <Show /> <button onClick={handleM}>ๅŠ m</button> <button onClick={handleMicrotask}>่งฆๅ‘microtask</button> </Context.Provider> ); }; export default Case3;
const app = require("../server"); const request = require("supertest"); const authenticateToken = require("../middlewares/authenticateToken"); const { UserRepository } = require("../repositories/user.repository"); const { reportRepository } = require("../repositories/report.repository"); jest.mock("jsonwebtoken"); jest.mock("../repositories/user.repository"); jest.mock("../repositories/report.repository"); jest.mock("../middlewares/authenticateToken", () => jest.fn().mockImplementation((req, res, next) => { next(); }) ); describe("GET /api/reports/home", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_provider" }; next(); }); }); it("should return 500 for server errors", async () => { UserRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app).get(`/api/reports/home`); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 404 for not found user", async () => { UserRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app).get(`/api/reports/home`); expect(response.status).toBe(404); expect(response.body).toEqual( "No data found at getAllReportsOfUser with id 123 ." ); }); it("should return 404 when no reports found", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_provider" }; }); reportRepository.findReportsOfUser.mockImplementation(() => { return []; }); const response = await request(app).get(`/api/reports/home`); expect(response.status).toBe(404); expect(response.body).toEqual("No data found at getAllReportsOfUser ."); }); it("should return 200 and reports", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_provider" }; }); reportRepository.findReportsOfUser.mockImplementation(() => { return [{ reportId: "1" }]; }); const response = await request(app).get(`/api/reports/home`); expect(response.status).toBe(200); expect(response.body).toEqual([{ reportId: "1" }]); }); }); describe("GET /api/reports/past", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_provider" }; next(); }); }); it("should return 500 for server errors", async () => { UserRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app).get(`/api/reports/past`); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 404 for not found user", async () => { UserRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app).get(`/api/reports/past`); expect(response.status).toBe(404); expect(response.body).toEqual( "No data found at getOldReportsOfUser with id 123 ." ); }); it("should return 404 when no reports found", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_provider" }; }); reportRepository.findReportsOfUser.mockImplementation(() => { return []; }); const response = await request(app).get(`/api/reports/past`); expect(response.status).toBe(404); expect(response.body).toEqual("No data found at getOldReportsOfUser ."); }); it("should return 200 and reports", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_provider" }; }); reportRepository.findReportsOfUser.mockImplementation(() => { return [{ reportId: "1" }]; }); const response = await request(app).get(`/api/reports/past`); expect(response.status).toBe(200); expect(response.body).toEqual([{ reportId: "1" }]); }); }); describe("GET /api/reports/:id", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_provider" }; next(); }); }); it("should return 500 for server errors", async () => { reportRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app).get(`/api/reports/1`); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 404 when no report found", async () => { reportRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app).get(`/api/reports/1`); expect(response.status).toBe(404); expect(response.body).toEqual("No data found at getReport with id 1 ."); }); it("should return 403 when report is not assigned to user", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", assignedUser: "456" }; }); const response = await request(app).get(`/api/reports/1`); expect(response.status).toBe(403); expect(response.body).toEqual( "Access Denied you forbidden for this content." ); }); it("should return 200 and report", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", assignedUser: "123" }; }); const response = await request(app).get(`/api/reports/1`); expect(response.status).toBe(200); expect(response.body).toEqual({ reportId: "1", assignedUser: "123" }); }); }); describe("POST /api/reports", () => { beforeEach(() => { jest.clearAllMocks(); authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_provider" }; next(); }); }); it("should return 500 for server errors", async () => { UserRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app).post(`/api/reports`); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 404 when no user found", async () => { UserRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app).post(`/api/reports`); expect(response.status).toBe(404); expect(response.body).toEqual( "No data found at createReport with id 123 ." ); }); it("should return 400 if user of service_provider try to create a report", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_provider" }; }); const response = await request(app).post(`/api/reports`); expect(response.status).toBe(400); expect(response.body).toEqual( "Only service request users can submit reports." ); }); it("should return 400 for form errors", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_request" }; }); reportRepository.create.mockImplementation(() => { throw new Error("Form error"); }); const response = await request(app).post(`/api/reports`); expect(response.status).toBe(400); expect(response.body).toEqual( "Please provide all required fields at createReport" ); }); it("should return 400 for no service provider available", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_request" }; }); UserRepository.findNearbyAndByProfession.mockImplementation(() => { return []; }); const response = await request(app).post(`/api/reports`).send({ location: "location", profession: "profession", description: "description", urgency: "low", dateOfResolve: "24/12/2021", range: 10, }); expect(response.status).toBe(400); expect(response.body).toEqual( "No service provider available for this report. Please try again later." ); }); }); describe("PUT /api/reports/updateDate/:id", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_request" }; next(); }); }); it("should return 500 for server errors", async () => { UserRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: "24/12/2024" }); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 400 when no new date provided", async () => { const response = await request(app).put(`/api/reports/updateDate/1`); expect(response.status).toBe(400); expect(response.body).toEqual( "Please provide a new date and the report id" ); }); it("should return 400 when the new date is invalid", async () => { const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2000-12-24") }); expect(response.status).toBe(400); expect(response.body).toEqual("The date must be in the future"); }); it("should return 404 when no user found with this token", async () => { UserRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24") }); expect(response.status).toBe(404); expect(response.body).toEqual( "No data found at updateDateOfResolve with id 123 ." ); }); it("should return 403 when a service provider user try to change the date", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "456", role: "service_provider" }; }); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24") }); expect(response.status).toBe(403); expect(response.body).toEqual( "Access Denied you forbidden for this content." ); }); it("should return 404 when no report found", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_request" }; }); reportRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24") }); expect(response.status).toBe(404); expect(response.body).toEqual( "No data found at updateDateOfResolve with id 1 ." ); }); it("should return 400 when the new date is equal to the old date", async () => { UserRepository.retrieve.mockImplementation(() => { return { userId: "123", role: "service_request" }; }); reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", dateOfResolve: new Date("2030-12-24") }; }); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24") }); expect(response.status).toBe(400); expect(response.body).toEqual( "The new date must be different from the old date" ); }); it("should return 400 when failed crud", async () => { UserRepository.retrieve .mockImplementationOnce(() => Promise.resolve({ userId: "123", role: "service_request" }) ) .mockImplementationOnce(() => Promise.resolve({ userId: "456", role: "service_request", reports: ["1"], }) ); reportRepository.retrieve.mockImplementation((id) => Promise.resolve({ reportId: id, assignedUser: "456", dateOfResolve: new Date("2032-12-24"), }) ); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24").toISOString() }); expect(response.status).toBe(400); expect(response.body).toEqual("Failed to update the report"); }); it("should return 200 when the date is updated", async () => { UserRepository.retrieve.mockResolvedValue({ userId: "123", role: "service_request", }); reportRepository.retrieve.mockResolvedValue({ reportId: "1", assignedUser: "456", dateOfResolve: new Date("2025-12-24"), }); UserRepository.retrieve.mockResolvedValue({ userId: "456", role: "service_request", reports: ["1"], }); reportRepository.retrieve.mockResolvedValue({ reportId: "1", assignedUser: "456", dateOfResolve: new Date("2025-12-24"), }); reportRepository.updateDateOfResolve.mockResolvedValue(true); const response = await request(app) .put(`/api/reports/updateDate/1`) .send({ newDateOfResolve: new Date("2030-12-24").toISOString() }); expect(response.status).toBe(200); expect(response.body).toEqual("Report updated"); }); }); describe("PUT /api/reports/updateStatus/:id", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_provider" }; next(); }); }); it("should return 500 for server errors", async () => { reportRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "in_progress" }); // expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 400 when no new status provided", async () => { const response = await request(app).put(`/api/reports/updateStatus/1`); expect(response.status).toBe(400); expect(response.body).toEqual( "Please provide the status and the report id" ); }); it("should return 403 when a service_request user try to change the status", async () => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_request" }; next(); }); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "in_progress" }); expect(response.status).toBe(403); expect(response.body).toEqual( "Access Denied you forbidden for this content." ); }); it("should return 404 when no report found", async () => { reportRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "in_progress" }); expect(response.status).toBe(404); expect(response.body).toEqual("No data found at updateStatus with id 1 ."); }); it("should return 400 when the new status is invalid", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", status: "pending" }; }); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "invalid" }); expect(response.status).toBe(400); expect(response.body).toEqual("Invalid status"); }); it("should return 400 when the new status is equal to the old status", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", status: "pending", assignedUser: "123" }; }); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "pending" }); expect(response.status).toBe(400); expect(response.body).toEqual( "The new status must be different from the old status" ); }); it("should return 400 when failed crud", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", status: "pending", assignedUser: "123" }; }); reportRepository.updateStatus.mockImplementation(null); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "in_progress" }); expect(response.status).toBe(400); expect(response.body).toEqual("Failed to update the report"); }); it("should return 200 when the status is updated", async () => { reportRepository.retrieve.mockResolvedValue({ reportId: "1", status: "pending", assignedUser: "123", }); reportRepository.updateStatus.mockResolvedValue(true); const response = await request(app) .put(`/api/reports/updateStatus/1`) .send({ newStatus: "in_progress" }); expect(response.status).toBe(200); expect(response.body).toEqual("Report status updated"); }); }); describe("DELETE /api/reports", () => { beforeEach(() => { authenticateToken.mockImplementation((req, res, next) => { req.user = { userId: "123", role: "service_request" }; next(); }); }); it("should return 500 for server errors", async () => { reportRepository.retrieve.mockImplementation(() => { const error = new Error("Unexpected error"); error.name = "UnknownError"; throw error; }); const response = await request(app).delete(`/api/reports`).send({ id: 1 }); expect(response.status).toBe(500); expect(response.body).toEqual( "server encountered an unexpected condition that prevented it from fulfilling the request." ); }); it("should return 400 for no id provided", async () => { const response = await request(app).delete(`/api/reports`); expect(response.status).toBe(400); expect(response.body).toEqual("Please provide the report id"); }); it("should return 404 when no report found with this id", async () => { reportRepository.retrieve.mockImplementation(() => { return null; }); const response = await request(app).delete(`/api/reports`).send({ id: 1 }); expect(response.status).toBe(404); expect(response.body).toEqual("No data found at deleteReport with id 1 ."); }); it("should return 403 when a service_request user try to delete report that he didnt submit", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", reportByUser: "456" }; }); const response = await request(app).delete(`/api/reports`).send({ id: 1 }); expect(response.status).toBe(403); expect(response.body).toEqual( "Access Denied you forbidden for this content." ); }); it("should return 400 when failed crud", async () => { reportRepository.retrieve.mockImplementation(() => { return { reportId: "1", reportByUser: "123" }; }); reportRepository.delete.mockImplementation(() => { return null; }); const response = await request(app).delete(`/api/reports`).send({ id: 1 }); expect(response.status).toBe(400); expect(response.body).toEqual("failed to delete the report"); }); it("should return 200 when the report is deleted", async () => { reportRepository.retrieve.mockResolvedValue({ reportId: "1", reportByUser: "123", }); reportRepository.delete.mockResolvedValue(true); const response = await request(app).delete(`/api/reports`).send({ id: 1 }); expect(response.status).toBe(200); expect(response.body).toEqual("Report has been deleted"); }); });
<?php declare(strict_types=1); /* * This file is part of the latent/el-admin. * * (c) latent<pltrueover@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Latent\ElAdmin\Controller; use Illuminate\Http\JsonResponse; use Latent\ElAdmin\Enum\ModelEnum; use Latent\ElAdmin\Exceptions\ValidateException; use Latent\ElAdmin\Services\AuthServices; use Latent\ElAdmin\Services\Permission; use Latent\ElAdmin\Support\Helpers; use Psr\SimpleCache\InvalidArgumentException; class AuthController extends Controller { use Permission; /** * User guard. */ protected string $guard; public function __construct() { $this->guard = (string) config('el_admin.guard'); } /** * User login. * * @throws ValidateException */ public function login(): JsonResponse { $params = $this->validator([ 'email' => 'required|email', 'password' => 'required|min:6|max:20', ]); if (! $token = auth($this->guard)->attempt([ 'email' => $params['email'], 'password' => $params['password'], 'status' => ModelEnum::NORMAL] )) { return $this->fail(trans('el_admin.login_error')); } return (new AuthServices())->respondWithToken((string) $token); } /** * Get the authenticated User. * * @throws InvalidArgumentException * @throws ValidateException */ public function me(): JsonResponse { $params = $this->validator([ 'is_menus' => 'int|in:0,1', ]); $user = auth($this->guard)->user()?->toArray(); if (! empty($params['is_menus'])) { [$menus, $nodes] = $this->getUserMenusAndNode(); $menus = Helpers::getTree($menus); $nodes = Helpers::getTree($nodes); $user = array_merge($user, ['menus' => $menus, 'nodes' => $nodes]); } return $this->success($user); } public function logout(): JsonResponse { auth($this->guard)->logout(); return $this->success(); } /** * Refresh token. */ public function refresh(): JsonResponse { return (new AuthServices())->respondWithToken((string) auth($this->guard)->refresh()); } }
# Inventory Management System (MERN Project) ![Homepage](./screenshots/Homepage.JPG) ## Introduction Welcome to the Inventory Management System! This project is built using the MERN stack (MongoDB, Express.js, React.js, Node.js). It allows users to manage inventory by performing CRUD (Create, Read, Update, Delete) operations on products. ## Demo of CRUD operation in App [Watch Demo on YouTube](https://youtu.be/p90kZwRzoWA) ## Server Setup ### Installation 1. Navigate to the `server` directory. 2. Run `npm install` to install dependencies. - ![Server Installation](./screenshots/Installating%20server.JPG) ### Starting the Server - Start the server by running `npm start`. - Upon successful start, you'll see the message: - ![Server Running](./screenshots/Server%20running%20succesfull.JPG) ### Endpoints - **Create a Product:** `POST /products/create?name=<name>&price=<price>&desc=<description>&supplier=<supplier name>&mfg=<mfg date>&exp=<exp date>&quantity=<quantity>` - **Get All Products:** `GET /products/get` - **Update a Product:** `PUT /products/update/<_id>/?name=<name>&price=<price>&desc=<description>&supplier=<supplier name>&mfg=<mfg date>&exp=<exp date>&quantity=<quantity>` - **Delete a Product:** `DELETE /products/delete/<_id>` ## Client Setup ### Installation 1. Navigate to the `client/inventory` directory. 2. Run `npm install` to install dependencies. - ![Client Installation](./screenshots/Installing%20client.JPG) ### Starting the React App - Start the React app by running `npm start`. - The app will open in your default browser at http://localhost:3000. ## Usage 1. Use the navigation buttons to access different sections: - **Home:** Click on the logo. - ![Homepage](./screenshots/Homepage.JPG) - **Products:** Click on the "Product" button. - ![Product Page](./screenshots/ProductPage.JPG) 2. On the Product page, you can perform CRUD operations on products. 3. [Click to watch the demo](https://youtu.be/p90kZwRzoWA) ## Notes - Ensure that the server is running for successful frontend communication to backend server for CRUD operations . - Make sure your MongoDB service is running properly on your operating system.![Mongo server running](./screenshots/MongoDB%20server%20running.JPG)
# Stable Diffusion XL for JAX + TPUv5e [TPU v5e](https://cloud.google.com/blog/products/compute/how-cloud-tpu-v5e-accelerates-large-scale-ai-inference) is a new generation of TPUs from Google Cloud. It is the most cost-effective, versatile, and scalable Cloud TPU to date. This makes them ideal for serving and scaling large diffusion models. [JAX](https://github.com/google/jax) is a high-performance numerical computation library that is well-suited to develop and deploy diffusion models: - **High performance**. All JAX operations are implemented in terms of operations in [XLA](https://www.tensorflow.org/xla/) - the Accelerated Linear Algebra compiler - **Compilation**. JAX uses just-in-time (jit) compilation of JAX Python functions so it can be executed efficiently in XLA. In order to get the best performance, we must use static shapes for jitted functions, this is because JAX transforms work by tracing a function and to determine its effect on inputs of a specific shape and type. When a new shape is introduced to an already compiled function, it retriggers compilation on the new shape, which can greatly reduce performance. **Note**: JIT compilation is particularly well-suited for text-to-image generation because all inputs and outputs (image input / output sizes) are static. - **Parallelization**. Workloads can be scaled across multiple devices using JAX's [pmap](https://jax.readthedocs.io/en/latest/_autosummary/jax.pmap.html), which expresses single-program multiple-data (SPMD) programs. Applying pmap to a function will compile a function with XLA, then execute in parallel on XLA devices. For text-to-image generation workloads this means that increasing the number of images rendered simultaneously is straightforward to implement and doesn't compromise performance. ๐Ÿ‘‰ Try it out for yourself: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/google/sdxl) ## Stable Diffusion XL pipeline in JAX Upon having access to a TPU VM (TPUs higher than version 3), you should first install a TPU-compatible version of JAX: ``` pip install jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html ``` Next, we can install [flax](https://github.com/google/flax) and the diffusers library: ``` pip install flax diffusers transformers ``` In [sdxl_single.py](./sdxl_single.py) we give a simple example of how to write a text-to-image generation pipeline in JAX using [StabilityAI's Stable Diffusion XL](stabilityai/stable-diffusion-xl-base-1.0). Let's explain it step-by-step: **Imports and Setup** ```python import jax import jax.numpy as jnp import numpy as np from flax.jax_utils import replicate from MuseVdiffusers import FlaxStableDiffusionXLPipeline from jax.experimental.compilation_cache import compilation_cache as cc cc.initialize_cache("/tmp/sdxl_cache") import time NUM_DEVICES = jax.device_count() ``` First, we import the necessary libraries: - `jax` is provides the primitives for TPU operations - `flax.jax_utils` contains some useful utility functions for `Flax`, a neural network library built on top of JAX - `diffusers` has all the code that is relevant for SDXL. - We also initialize a cache to speed up the JAX model compilation. - We automatically determine the number of available TPU devices. **1. Downloading Model and Loading Pipeline** ```python pipeline, params = FlaxStableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", revision="refs/pr/95", split_head_dim=True ) ``` Here, a pre-trained model `stable-diffusion-xl-base-1.0` from the namespace `stabilityai` is loaded. It returns a pipeline for inference and its parameters. **2. Casting Parameter Types** ```python scheduler_state = params.pop("scheduler") params = jax.tree_util.tree_map(lambda x: x.astype(jnp.bfloat16), params) params["scheduler"] = scheduler_state ``` This section adjusts the data types of the model parameters. We convert all parameters to `bfloat16` to speed-up the computation with model weights. **Note** that the scheduler parameters are **not** converted to `blfoat16` as the loss in precision is degrading the pipeline's performance too significantly. **3. Define Inputs to Pipeline** ```python default_prompt = ... default_neg_prompt = ... default_seed = 33 default_guidance_scale = 5.0 default_num_steps = 25 ``` Here, various default inputs for the pipeline are set, including the prompt, negative prompt, random seed, guidance scale, and the number of inference steps. **4. Tokenizing Inputs** ```python def tokenize_prompt(prompt, neg_prompt): prompt_ids = pipeline.prepare_inputs(prompt) neg_prompt_ids = pipeline.prepare_inputs(neg_prompt) return prompt_ids, neg_prompt_ids ``` This function tokenizes the given prompts. It's essential because the text encoders of SDXL don't understand raw text; they work with numbers. Tokenization converts text to numbers. **5. Parallelization and Replication** ```python p_params = replicate(params) def replicate_all(prompt_ids, neg_prompt_ids, seed): ... ``` To utilize JAX's parallel capabilities, the parameters and input tensors are duplicated across devices. The `replicate_all` function also ensures that every device produces a different image by creating a unique random seed for each device. **6. Putting Everything Together** ```python def generate(...): ... ``` This function integrates all the steps to produce the desired outputs from the model. It takes in prompts, tokenizes them, replicates them across devices, runs them through the pipeline, and converts the images to a format that's more interpretable (PIL format). **7. Compilation Step** ```python start = time.time() print(f"Compiling ...") generate(default_prompt, default_neg_prompt) print(f"Compiled in {time.time() - start}") ``` The initial run of the `generate` function will be slow because JAX compiles the function during this call. By running it once here, subsequent calls will be much faster. This section measures and prints the compilation time. **8. Fast Inference** ```python start = time.time() prompt = ... neg_prompt = ... images = generate(prompt, neg_prompt) print(f"Inference in {time.time() - start}") ``` Now that the function is compiled, this section shows how to use it for fast inference. It measures and prints the inference time. In summary, the code demonstrates how to load a pre-trained model using Flax and JAX, prepare it for inference, and run it efficiently using JAX's capabilities. ## Ahead of Time (AOT) Compilation FlaxStableDiffusionXLPipeline takes care of parallelization across multiple devices using jit. Now let's build parallelization ourselves. For this we will be using a JAX feature called [Ahead of Time](https://jax.readthedocs.io/en/latest/aot.html) (AOT) lowering and compilation. AOT allows to fully compile prior to execution time and have control over different parts of the compilation process. In [sdxl_single_aot.py](./sdxl_single_aot.py) we give a simple example of how to write our own parallelization logic for text-to-image generation pipeline in JAX using [StabilityAI's Stable Diffusion XL](stabilityai/stable-diffusion-xl-base-1.0) We add a `aot_compile` function that compiles the `pipeline._generate` function telling JAX which input arguments are static, that is, arguments that are known at compile time and won't change. In our case, it is num_inference_steps, height, width and return_latents. Once the function is compiled, these parameters are omitted from future calls and cannot be changed without modifying the code and recompiling. ```python def aot_compile( prompt=default_prompt, negative_prompt=default_neg_prompt, seed=default_seed, guidance_scale=default_guidance_scale, num_inference_steps=default_num_steps ): prompt_ids, neg_prompt_ids = tokenize_prompt(prompt, negative_prompt) prompt_ids, neg_prompt_ids, rng = replicate_all(prompt_ids, neg_prompt_ids, seed) g = jnp.array([guidance_scale] * prompt_ids.shape[0], dtype=jnp.float32) g = g[:, None] return pmap( pipeline._generate,static_broadcasted_argnums=[3, 4, 5, 9] ).lower( prompt_ids, p_params, rng, num_inference_steps, # num_inference_steps height, # height width, # width g, None, neg_prompt_ids, False # return_latents ).compile() ```` Next we can compile the generate function by executing `aot_compile`. ```python start = time.time() print("Compiling ...") p_generate = aot_compile() print(f"Compiled in {time.time() - start}") ``` And again we put everything together in a `generate` function. ```python def generate( prompt, negative_prompt, seed=default_seed, guidance_scale=default_guidance_scale ): prompt_ids, neg_prompt_ids = tokenize_prompt(prompt, negative_prompt) prompt_ids, neg_prompt_ids, rng = replicate_all(prompt_ids, neg_prompt_ids, seed) g = jnp.array([guidance_scale] * prompt_ids.shape[0], dtype=jnp.float32) g = g[:, None] images = p_generate( prompt_ids, p_params, rng, g, None, neg_prompt_ids) # convert the images to PIL images = images.reshape((images.shape[0] * images.shape[1], ) + images.shape[-3:]) return pipeline.numpy_to_pil(np.array(images)) ``` The first forward pass after AOT compilation still takes a while longer than subsequent passes, this is because on the first pass, JAX uses Python dispatch, which Fills the C++ dispatch cache. When using jit, this extra step is done automatically, but when using AOT compilation, it doesn't happen until the function call is made. ```python start = time.time() prompt = "photo of a rhino dressed suit and tie sitting at a table in a bar with a bar stools, award winning photography, Elke vogelsang" neg_prompt = "cartoon, illustration, animation. face. male, female" images = generate(prompt, neg_prompt) print(f"First inference in {time.time() - start}") ``` From this point forward, any calls to generate should result in a faster inference time and it won't change. ```python start = time.time() prompt = "photo of a rhino dressed suit and tie sitting at a table in a bar with a bar stools, award winning photography, Elke vogelsang" neg_prompt = "cartoon, illustration, animation. face. male, female" images = generate(prompt, neg_prompt) print(f"Inference in {time.time() - start}") ```
#include <Seeed_Arduino_SSCMA.h> #include <Arduino.h> #include <ArduinoJson.h> #include <WiFi.h> #include <WiFiMulti.h> #include <HTTPClient.h> #include <WiFiClientSecure.h> #include "certs.h" SSCMA AI; JsonDocument doc; JsonDocument dataIn; WiFiMulti WiFiMulti; void setup() { AI.begin(); WiFi.mode(WIFI_STA); WiFiMulti.addAP(ssid, password); while ((WiFiMulti.run() != WL_CONNECTED)) { // Wait for WiFi Start } setClock(); } void loop() { // Fill This with your data dataIn["detection"] = predict(); // Dont Modify Nothing After This // API Call Preparation doc["apikey"] = apikey; doc["sensor"] = sensorName; doc["private"] = privateFlag; // Pre Process the JSON object doc["dataIn"] = dataIn; String data; serializeJson(doc, data); // Send API Call sendData(data); // Wait 10 min delay(1000 * 60 * 10); // Testing } int predict() { if (!AI.invoke()) { return AI.classes()[0].target; } else { return -1; } } void sendData(String httpRequestData) { WiFiClientSecure *client = new WiFiClientSecure; if (client) { client->setCACert(CERT_CA); { // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is HTTPClient https; if (https.begin(*client, "https://us-central1-bot-weave.cloudfunctions.net/addData")) { // HTTPS // start connection and send HTTP header https.addHeader("Content-Type", "application/json"); https.setTimeout(1000 * 30); // 30 Seconds int httpCode = https.POST(httpRequestData); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = https.getString(); } } https.end(); } else { // No Connection } } delete client; } } void setClock() { configTime(0, 0, "pool.ntp.org"); time_t nowSecs = time(nullptr); while (nowSecs < 8 * 3600 * 2) { delay(500); yield(); nowSecs = time(nullptr); } struct tm timeinfo; gmtime_r(&nowSecs, &timeinfo); }
# ะ—ะฐะดะฐะฝะธะต ะฝะฐ ะฟั€ะฐะบั‚ะธะบัƒ ![](https://img.shields.io/badge/Done-green.svg) # ะ—ะฐะดะฐะฝะธั ะปะตะบั†ะธะธ 1. ะ”ะปั ะทะฐะดะฐะฝะฝั‹ั… ะทะฝะฐั‡ะตะฝะธะน ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะฝะตััƒั‰ะตะณะพ ะบะพะปะตะฑะฐะฝะธั ะธ ะะง ัะธะณะฝะฐะปะฐ ะพะฟั€ะตะดะตะปะธั‚ะต ะทะฝะฐั‡ะตะฝะธะต ั‡ะฐัั‚ะพั‚ั‹ ะดะธัะบั€ะตั‚ะธะทะฐั†ะธะธ (ะฒ ะผะตะฝะตะดะถะตั€ะต ะฟะตั€ะตะผะตะฝะฝั‹ั…), ะทะฝะฐั‡ะตะฝะธะต ะธะฝะดะตะบัะฐ ะะœ. ะŸะพะปัƒั‡ะธั‚ะต ะฒั€ะตะผะตะฝะฝัƒัŽ ะธ ัะฟะตะบั‚ั€ะฐะปัŒะฝัƒัŽ ะดะธะฐะณั€ะฐะผะผั‹ ะฝะตััƒั‰ะตะณะพ ะบะพะปะตะฑะฐะฝะธั ะธ ะะง ัะธะณะฝะฐะปะฐ. 2. ะŸะพะปัƒั‡ะธั‚ะต ัะธะณะฝะฐะป ะะœ ั ะฟะฐั€ะฐะผะตั‚ั€ะฐะผะธ fc = 4, fm = 0.2, Ac = 2 , Am = 0.5. ะŸะพะปัƒั‡ะธั‚ะต ะฒั€ะตะผะตะฝะฝัƒัŽ ะธ ัะฟะตะบั‚ั€ะฐะปัŒะฝัƒัŽ ะดะธะฐะณั€ะฐะผะผั‹ ะฝะตััƒั‰ะตะณะพ ะบะพะปะตะฑะฐะฝะธั ะธ ะะง ัะธะณะฝะฐะปะฐ. ะžะฟั€ะตะดะตะปะธั‚ะต ะฝะพั€ะผะธั€ะพะฒะฐะฝะฝัƒัŽ ั‡ะฐัั‚ะพั‚ัƒ ัั€ะตะทะฐ ะคะะง fn ะฒ ะผะตะฝะตะดะถะตั€ะต ะฟะตั€ะตะผะตะฝะฝั‹ั…. ะŸะพะฟั€ะพะฑัƒะนั‚ะต ะธะทะผะตะฝะธั‚ัŒ ะตะต ะทะฝะฐั‡ะตะฝะธะต (ะทะฐะดะฐะนั‚ะต ะฒ ะฟั€ะพะณั€ะฐะผะผะต fn) ะธ ัั€ะฐะฒะฝะธั‚ะต ะบะฐั‡ะตัั‚ะฒะพ ะดะตั‚ะตั‚ะธั€ะพะฒะฐะฝะธั. 3. ะŸะพะปัƒั‡ะธั‚ะต ัะธะณะฝะฐะป ะะœ ั ะฟะฐั€ะฐะผะตั‚ั€ะฐะผะธ fc = 2, fm = 0.2, Ac = 2 , Am = 1.5. ะŸะพะปัƒั‡ะธั‚ะต ะฒั€ะตะผะตะฝะฝัƒัŽ ะธ ัะฟะตะบั‚ั€ะฐะปัŒะฝัƒัŽ ะดะธะฐะณั€ะฐะผะผั‹ ะฝะตััƒั‰ะตะณะพ ะบะพะปะตะฑะฐะฝะธั ะธ ะะง ัะธะณะฝะฐะปะฐ. ะžะฟั€ะตะดะตะปะธั‚ะต ะฝะพั€ะผะธั€ะพะฒะฐะฝะฝัƒัŽ ั‡ะฐัั‚ะพั‚ัƒ ัั€ะตะทะฐ ะคะะง fn ะฒ ะผะตะฝะตะดะถะตั€ะต ะฟะตั€ะตะผะตะฝะฝั‹ั…. ะŸะพะฟั€ะพะฑัƒะนั‚ะต ะธะทะผะตะฝะธั‚ัŒ ะตะต ะทะฝะฐั‡ะตะฝะธะต (ะทะฐะดะฐะนั‚ะต ะฒ ะฟั€ะพะณั€ะฐะผะผะต fn) ะธ ัั€ะฐะฒะฝะธั‚ะต ะบะฐั‡ะตัั‚ะฒะพ ะดะตั‚ะตั‚ะธั€ะพะฒะฐะฝะธั. # ะ—ะฐะดะฐะฝะธั ะฟั€ะฐะบั‚ะธะบะธ **ะ—ะฐะดะฐะฝะธะต โ„–1** 1. ะŸั€ะธ ะฟะพะผะพั‰ะธ ะดะพะบัƒะผะตะฝั‚ะฐั†ะธะธ ะฝะฐัั‚ั€ะพะนั‚ะต ะฟั€ะธะตะผะฝะธะบ ะธ ะฟะตั€ะตะดะฐั‚ั‡ะธะบ ะฝะฐ ะพะดะฝัƒ ะฝะตััƒั‰ัƒัŽ ั‡ะฐัั‚ะพั‚ัƒ - **2.4** [GHz] + **2** [MHz] * โ€œ**ะฝะพะผะตั€ ัั‚ะพะปะฐ**โ€; 2. ะฃัั‚ะฐะฝะพะฒะธั‚ัŒ `.sample_rate = 1e6`; 3. ะŸะพ ัƒะผะพะปั‡ะฐะฝะธัŽ, ะบะพะปะธั‡ะตัั‚ะฒะพ ััะผะฟะปะพะฒ, ะฟะพะปัƒั‡ะฐะตะผั‹ั… ั ะฑัƒั„ะตั€ะฐ, ั€ะฐะฒะฝะพ **1024**. 4. ะกะณะตะฝะตั€ะธั€ัƒะนั‚ะต ะฟั€ะพัั‚ัƒัŽ ัะธะฝัƒัะพะธะดัƒ: 1. ะšะพะปะธั‡ะตัั‚ะฒะพ ัะปะตะผะตะฝั‚ะพะฒ ะฒะตะบั‚ะพั€ะฐ - ะฝะฐ ัะฒะพะต ัƒัะผะพั‚ั€ะตะฝะธะต; 2. ะœะฐะบั. ะฐะผะฟะปะธั‚ัƒะดะฐ ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ั€ะฐะฒะฝะฐ **2**14;** 5. ะžั‚ะฟั€ะฐะฒัŒั‚ะต ัะณะตะฝะตั€ะธั€ะพะฒะฐะฝะฝั‹ะต ััะผะฟะปั‹ ัะธะฝัƒัะพะธะดั‹ ะฝะฐ ั„ัƒะฝะบั†ะธัŽ ะฟะตั€ะตะดะฐั‚ั‡ะธะบะฐ; 6. ะžั‚ะพะฑั€ะฐะทะธั‚ะต ะฝะฐ ะณั€ะฐั„ะธะบะต ะฟั€ะธะฝัั‚ั‹ะน ัะธะณะฝะฐะป ะธ ะตะณะพ ัะฟะตะบั‚ั€; 7. p.s. ะทะฐ ั€ะตะณัƒะปะธั€ะพะฒะบัƒ ะผะพั‰ะฝะพัั‚ะธ ะฟะตั€ะตะดะฐั‚ั‡ะธะบะฐ ะธ ั‡ัƒะฒัั‚ะฒะธั‚ะตะปัŒะฝะพัั‚ัŒัŽ ะฟั€ะธะตะผะฝะธะบะฐ ะพั‚ะฒะตั‡ะฐัŽั‚ ะผะตั‚ะพะดั‹ `tx_hardwaregain_chan0` ะธ `rx_hardwaregain_chan0` ัะพะพั‚ะฒะตั‚ัั‚ะฒะตะฝะฝะพ; **ะ—ะฐะดะฐะฝะธะต โ„–2** 1. ะฃัั‚ะฐะฝะพะฒะธั‚ะต ั€ะฐะทะผะตั€ **1 ัะธะผะฒะพะปะฐ** - ะฝะฐ ัะฒะพะต ัƒัะผะพั‚ั€ะตะฝะธะต. 2. ะŸั€ะธ ะฟะพะผะพั‰ะธ **ASCII** ั‚ะฐะฑะปะธั†ั‹ (ะบะพะดะธั€ะพะฒั‰ะธะบะฐ) ะทะฐะบะพะดะธั€ัƒะนั‚ะต ัะฒะพะธ ะดะฐะฝะฝั‹ะต (ะคะ˜ะž) ะฒ ะฒะธะดะต ะฑะธั‚ะพะฒะพะน ะฟะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพัั‚ะธ. 3. ะŸั€ะธ ะฟะพะผะพั‰ะธ ะธะทะผะตะฝะตะฝะธั ะผะฐะบัะธะผะฐะปัŒะฝะพะน ะฐะผะฟะปะธั‚ัƒะดั‹ ั€ะฐะดะธะพัะธะณะฝะฐะปะฐ ัั„ะพั€ะผะธั€ัƒะนั‚ะต ัะธะฝัƒัะพะธะดัƒ (ะธะท ะ—ะฐะดะฐะฝะธั โ„–1) ะฟะพ ะฟั€ะฐะฒะธะปะฐะผ ะฐะผะฟะปะธั‚ัƒะดะฝะพะน ะผะพะดัƒะปัั†ะธะธ. ะฃั€ะพะฒะฝะธ ะผะพะดัƒะปัั†ะธะธ ะดะปั `โ€œ0โ€` ะธ `โ€œ1โ€` ัƒัั‚ะฐะฝะพะฒะธั‚ะต ะพะฟั‹ั‚ะฝั‹ะผ ะฟัƒั‚ะตะผ. 4. ะŸะตั€ะตะดะฐะนั‚ะต ะฒะฐัˆะธ ะดะฐะฝะฝั‹ะต ะฝะฐ `tx()` ะธ โ€œ**ะฟั€ะธะผะธั‚ะต + ะดะตะบะพะดะธั€ัƒะนั‚ะต**โ€ ะฝะฐ ัั‚ะพั€ะพะฝะต `rx()`. 5. ะžะฟะธัˆะธั‚ะต ั ะบะฐะบะธะผะธ ะฟั€ะพะฑะปะตะผะฐะผะธ ะฒั‹ ัั‚ะพะปะบะฝัƒะปะธััŒ ะฒะพ ะฒั€ะตะผั ะฒั‹ะฟะพะปะฝะตะฝะธั ะทะฐะดะฐะฝะธั ะธ ะบะฐะบ ะธั… ั€ะตัˆะธะปะธ. **ะ—ะฐะดะฐะฝะธะต โ„–3 (ะฑะพะฝัƒั)** 1. ะŸั€ะธะผะธั‚ะต + ะดะตะบะพะดะธั€ัƒะนั‚ะต ะดะฐะฝะฝั‹ะต ะพั‚ ัะพัะตะดะตะน. 2. ะ—ะฐะฟะธัˆะธั‚ะต ะฟะพะปัƒั‡ะตะฝะฝั‹ะน ัะฟะธัะพะบ ัะพัะตะดะตะน ะฒ ั„ะฐะนะป. # ะ’ั‹ะฟะพะปะฝะตะฝะธะต ## ะ—ะฐะดะฐะฝะธั ะปะตะบั†ะธะธ <details> ## โ„–1 ะงะฐัั‚ะพั‚ะฐ ะดะธัะบั€ะตั‚ะธะทะฐั†ะธะธ `fs` = *204.7* ะ—ะฝะฐั‡ะตะฝะธะต ะธะฝะดะตะบัะฐ ะะœ `mu`=*0.5* <img src="./photo/1.png" width="800" /> <img src="./photo/1_0.png" width="600" /> ## โ„–2 `fc = 4, fm = 0.2, Ac = 2 , Am = 0.5` <img src="./photo/2_0.png" width="600" /><img src="./photo/2.png" width="800" /> <img src="./photo/2_3.png" width="600" /> ะะพั€ะผะธั€ะพะฒะฐะฝะฝะฐั ั‡ะฐัั‚ะพั‚ะฐ ัั€ะตะทะฐ ะคะะง `fn` = *0.000977* <img src="./photo/2_200.png" width="800" /> ะะพั€ะผะธั€ะพะฒะฐะฝะฝัƒัŽ ั‡ะฐัั‚ะพั‚ัƒ ัั€ะตะทะฐ ะคะะง ัƒะผะฝะพะถะธะป ะฝะฐ 200 `fn*200` = *0.1954* ะคะะง ะฝะต ั€ะฐะฑะพั‚ะฐะตั‚ ## โ„–3 `fc = 2, fm = 0.2, Ac = 2 , Am = 1.5` <img src="./photo/3_0.png" width="600" /><img src="./photo/3.png" width="800" /> <img src="./photo/3_3.png" width="600" /> ะะพั€ะผะธั€ะพะฒะฐะฝะฝะฐั ั‡ะฐัั‚ะพั‚ะฐ ัั€ะตะทะฐ ะคะะง `fn` = *0.000977* <img src="./photo/3_20.png" width="600" /> ะะพั€ะผะธั€ะพะฒะฐะฝะฝัƒัŽ ั‡ะฐัั‚ะพั‚ัƒ ัั€ะตะทะฐ ะคะะง ัƒะผะฝะพะถะธะป ะฝะฐ 50 `fn*50` = *0.04885* ะคะะง ั€ะฐะฑะพั‚ะฐะตั‚, ะฝะพ ะฝะต ะธะดะตะฐะปัŒะฝะพ </details> ## ะ—ะฐะดะฐะฝะธั ะฟั€ะฐะบั‚ะธะบะธ <details> ### ะ—ะฐะดะฐะฝะธะต โ„–1 **1** ```py frequency = 2400e6+(2e6*2) sdr.rx_lo = int(frequency) sdr.tx_lo = int(frequency) ``` **2** ```py sdr.sample_rate = 1e6 ``` **4** ```py fc = 10000 ts = 1/float(1e6) t = np.arange(0, fc*ts, ts) i = np.sin(2*np.pi*t*fc) * 2**14 q = np.cos(2*np.pi*t*fc) * 2**14 samples = i + 1j*q ``` **5** ```py sdr.tx_cyclic_buffer = True # Enable cyclic buffers sdr.tx(samples) ``` **6** ```py for r in range(30): rx = sdr.rx() plt.clf() plt.plot(rx.real) plt.ylim(-1000, 1000) plt.draw() plt.pause(0.05) time.sleep(0.0001) ``` <img src="./photo/p1.png" width="500" /> ### ะ—ะฐะดะฐะฝะธะต โ„–2 **1** ```py symbol=12 ``` **2** ` 112, 117, 115, 104, 110, 105, 116, 115, 97 - pushnitsa ` ะฒ ะดะฒะพะธั‡ะฝะพะผ ะบะพะดะต: `0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1` **3** ะกั„ะพั€ะผะธั€ะพะฒะฐะป ัะธะณะฝะฐะป ```py for i in range(len(binary_list)): if(binary_list[i]==0): for p in range(symbol): x.append(1) else: for p in range(symbol): x.append(6) x1=np.array(x) ``` ะกั„ะพั€ะผะธั€ะพะฒะฐะป ัะธะฝัƒัะพะธะดัƒ ```py t=np.linspace(0,len(x1),len(x1)) fc=80 q=np.sin(2*np.pi*t*fc) ``` ะŸะตั€ะตะผะฝะพะถะธะป ะธั… ```py sam = 2*(1.5*x1)*q ``` <img src="./photo/p2.png" width="600" /> ##### (4,5 ะฟัƒะฝะบั‚ั‹ ะฒั€ะตะผัะฝะธ ะฒั‹ะฟะพะปะฝะธั‚ัŒ ะฝะต ั…ะฒะฐั‚ะธะปะพ) (ะฟะตั€ะตะฝะตัะตะฝะพ ะฝะฐ ัะปะตะดัƒัŽั‰ัƒัŽ ะฟั€ะฐะบั‚ะธะบัƒ) </details>
/* * Unless expressly otherwise stated, code from this project is licensed under the MIT license [https://opensource.org/licenses/MIT]. * * Copyright (c) <2018> <Markus Gรคrtner, Volodymyr Kushnarenko, Florian Fritze, Sibylle Hermann and Uli Hahn> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package bwfdm.replaydh.ui.workflow; import static java.util.Objects.requireNonNull; import java.awt.BorderLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.LocalDateTime; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.SwingUtilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jgoodies.forms.builder.FormBuilder; import bwfdm.replaydh.core.RDHEnvironment; import bwfdm.replaydh.core.RDHException; import bwfdm.replaydh.io.FileTracker; import bwfdm.replaydh.io.LocalFileObject; import bwfdm.replaydh.io.TrackerException; import bwfdm.replaydh.io.TrackerListener; import bwfdm.replaydh.io.TrackingAction; import bwfdm.replaydh.io.TrackingStatus; import bwfdm.replaydh.resources.ResourceManager; import bwfdm.replaydh.ui.GuiUtils; import bwfdm.replaydh.ui.actions.ActionManager; import bwfdm.replaydh.ui.actions.ActionManager.ActionMapper; import bwfdm.replaydh.ui.helper.CloseableUI; import bwfdm.replaydh.ui.helper.ScrollablePanel; import bwfdm.replaydh.ui.helper.ScrollablePanel.ScrollableSizeHint; import bwfdm.replaydh.ui.icons.IconRegistry; import bwfdm.replaydh.utils.LazyCollection; import bwfdm.replaydh.utils.annotation.Experimental; /** * @author Markus Gรคrtner * */ public class WorkspaceTrackerPanel extends JPanel implements CloseableUI { private static final long serialVersionUID = 5100311840353055034L; private static final Logger log = LoggerFactory.getLogger(WorkspaceTrackerPanel.class); private final RDHEnvironment environment; private final ActionManager actionManager; private final ActionMapper actionMapper; /** * Container for the fast changing content */ private final ScrollablePanel contentPanel; private final JToolBar toolBar; private final Map<TrackingStatus, FileOutlinePanel> panels = new EnumMap<>(TrackingStatus.class); private final JLabel contentHeader; /** * Interface to the file tracker facility (usually GIT) */ private final FileTracker fileTracker; private final Handler handler; /** * Flag to prevent redundant refresh operations when the file tracker * posts both events via the {@link PropertyChangeListener} and * {@link TrackerListener} interfaces. Switching this field to {@code true} * will result in the next property change event to be ignored. */ private boolean ignoreNextStatusChange = false; public WorkspaceTrackerPanel(RDHEnvironment environment) { super(new BorderLayout()); this.environment = requireNonNull(environment); handler = new Handler(); actionManager = environment.getClient().getGui().getActionManager().derive(); try { actionManager.loadActions(WorkspaceTrackerPanel.class.getResource("workspace-tracker-panel-actions.xml")); } catch (IOException e) { throw new RDHException("Failed to load actions for"+WorkspaceTrackerPanel.class, e); } actionMapper = actionManager.mapper(this); toolBar = actionManager.createToolBar("replaydh.ui.core.workspaceTrackerPanel.toolBarList", null); fileTracker = environment.getClient().getFileTracker(); fileTracker.addTrackerListener(handler); contentHeader = (JLabel) GuiUtils.createInfoComponent("", false, null); for(TrackingStatus status : TrackingStatus.values()) { panels.put(status, new FileOutlinePanel(environment, actionManager, status)); } contentPanel = new ScrollablePanel(); contentPanel.setScrollableWidth(ScrollableSizeHint.FIT); FormBuilder.create() .columns("fill:pref:grow") .rows("pref, 5dlu, pref, pref, pref, pref, pref") .panel(contentPanel) .add(contentHeader) .xy(1, 1) .add(panel(TrackingStatus.CORRUPTED)) .xy(1, 3) .add(panel(TrackingStatus.UNKNOWN)) .xy(1, 4) .add(panel(TrackingStatus.MISSING)) .xy(1, 5) .add(panel(TrackingStatus.MODIFIED)) .xy(1, 6) .add(panel(TrackingStatus.TRACKED)) .xy(1, 7) .build(); environment.addPropertyChangeListener(RDHEnvironment.NAME_WORKSPACE, handler); JScrollPane scrollPane = new JScrollPane(contentPanel); add(toolBar, BorderLayout.NORTH); add(scrollPane, BorderLayout.CENTER); environment.getClient().getGui().registerHelp(this, "replaydh.ui.core.workspaceTrackerPanel"); registerActions(); refreshActions(); update(); } private FileOutlinePanel panel(TrackingStatus status) { FileOutlinePanel panel = panels.get(status); if(panel==null) throw new IllegalStateException("No outline panel for tracking status: "+status); return panel; } private void registerActions() { actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.createDummyFile", handler::createDummyFile); actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.editDummyFile", handler::editDummyFile); actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.deleteDummyFile", handler::deleteDummyFile); } private void refreshActions() { // no-op } /** * @see bwfdm.replaydh.ui.helper.CloseableUI#close() */ @Override public void close() { environment.removePropertyChangeListener(RDHEnvironment.NAME_WORKSPACE, handler); fileTracker.removeTrackerListener(handler); actionMapper.dispose(); } private void checkDevMode() { if(!environment.getClient().isDevMode()) throw new IllegalStateException("Cannot execute method outside of dev mode!!!"); } public void update() { TrackerStateHint hint = fileTracker.hasStatusInfo() ? TrackerStateHint.UPDATE_DONE : TrackerStateHint.UNKNOWN; showFileTrackerState(hint); } private LocalFileObject wrapFile(Path file, TrackingStatus trackingStatus) { return new LocalFileObject(file.toAbsolutePath(), trackingStatus); } private boolean hasFiles(TrackingStatus trackingStatus) { try { return fileTracker.hasFilesForStatus(trackingStatus); } catch (TrackerException e) { log.error("Failed to query file tracker for state on "+trackingStatus, e); return false; } } private Set<Path> getFiles(TrackingStatus trackingStatus) { try { return fileTracker.getFilesForStatus(trackingStatus); } catch (TrackerException e) { log.error("Failed to query file tracker for files on "+trackingStatus, e); return Collections.emptySet(); } } private Set<LocalFileObject> wrapFilesFromTracker(TrackingStatus trackingStatus) { Set<Path> files = getFiles(trackingStatus); LazyCollection<LocalFileObject> result = LazyCollection.lazySet(); files.forEach(file -> result.add(wrapFile(file, trackingStatus))); return result.getAsSet(); } private Set<LocalFileObject> extractFilesForUpdate( Set<LocalFileObject> filesToUpdate, Set<LocalFileObject> files) { for(LocalFileObject fileObject : files) { // Schedule all files for update if not inked to a known resource definition if(fileObject.getResource()==null) { filesToUpdate.add(fileObject); } } return files; } private void showFileTrackerState(final TrackerStateHint hint) { // Switch over to EDT if needed if(!SwingUtilities.isEventDispatchThread()) { GuiUtils.invokeEDT(() -> showFileTrackerState(hint)); return; } // System.out.println(hint); String textKey = null; Icon icon = null; Set<LocalFileObject> filesToUpdate = new HashSet<>(); boolean showCorruptedPanel = false; boolean showNewPanel = false; boolean showMissingPanel = false; boolean showModifiedPanel = false; boolean showTrackedPanel = false; switch (requireNonNull(hint)) { case UPDATE_DONE: { boolean hasNew = hasFiles(TrackingStatus.UNKNOWN); boolean hasMissing = hasFiles(TrackingStatus.MISSING); boolean hasModified = hasFiles(TrackingStatus.MODIFIED); boolean hasCorrupted = hasFiles(TrackingStatus.CORRUPTED); boolean hasTracked = hasFiles(TrackingStatus.TRACKED); if(!hasNew && !hasMissing && !hasModified && !hasCorrupted) { textKey = "replaydh.panels.workspaceTracker.unchangedState"; } else { textKey = "replaydh.panels.workspaceTracker.validState"; if(hasCorrupted) { Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.CORRUPTED); panel(TrackingStatus.CORRUPTED).setFiles(extractFilesForUpdate(filesToUpdate, files)); } if(hasNew) { Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.UNKNOWN); panel(TrackingStatus.UNKNOWN).setFiles(extractFilesForUpdate(filesToUpdate, files)); } if(hasMissing) { Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.MISSING); panel(TrackingStatus.MISSING).setFiles(extractFilesForUpdate(filesToUpdate, files)); } if(hasModified) { Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.MODIFIED); panel(TrackingStatus.MODIFIED).setFiles(extractFilesForUpdate(filesToUpdate, files)); } if(hasTracked) { Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.TRACKED); panel(TrackingStatus.TRACKED).setFiles(extractFilesForUpdate(filesToUpdate, files)); } showCorruptedPanel = hasCorrupted; showNewPanel = hasNew; showMissingPanel = hasMissing; showModifiedPanel = hasModified; showTrackedPanel = hasTracked; } } break; case UPDATE_CANCELLED: textKey = "replaydh.panels.workspaceTracker.updateCanceled"; break; case UPDATE_FAILED: textKey = "replaydh.panels.workspaceTracker.updateFailed"; break; case UPDATING: textKey = "replaydh.panels.workspaceTracker.updateRunning"; icon = IconRegistry.getGlobalRegistry().getIcon("loading-128.gif"); break; // Default state, let's just show generic "welcome" screen case UNKNOWN: default: textKey = "replaydh.panels.workspaceTracker.unknownStatus"; break; } panel(TrackingStatus.CORRUPTED).setVisible(showCorruptedPanel); panel(TrackingStatus.UNKNOWN).setVisible(showNewPanel); panel(TrackingStatus.MISSING).setVisible(showMissingPanel); panel(TrackingStatus.MODIFIED).setVisible(showModifiedPanel); panel(TrackingStatus.TRACKED).setVisible(showTrackedPanel); String text = null; if(textKey!=null) { text = ResourceManager.getInstance().get(textKey); } contentHeader.setText(GuiUtils.toSwingTooltip(text)); contentHeader.setIcon(icon); contentHeader.setVisible(text!=null || icon!=null); //TODO schedule update revalidate(); repaint(); refreshActions(); } private FileOutlinePanel getFileOutlinePanel(TrackingStatus trackingStatus) { switch (trackingStatus) { case IGNORED: return null; default: return panel(trackingStatus); } } private void updateFilePanel(LocalFileObject file) { FileOutlinePanel fileOutlinePanel = getFileOutlinePanel(file.getTrackingStatus()); if(fileOutlinePanel!=null) { fileOutlinePanel.updateFilePanel(file); } } private enum TrackerStateHint { UNKNOWN, UPDATING, UPDATE_FAILED, UPDATE_CANCELLED, UPDATE_DONE, ; } private class Handler implements PropertyChangeListener, TrackerListener { @Experimental private final Random random = new Random(System.currentTimeMillis()); /** * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ @Override public void propertyChange(PropertyChangeEvent evt) { //TODO handle workspace change } /** * @see bwfdm.replaydh.io.TrackerListener#statusInfoChanged(bwfdm.replaydh.io.FileTracker) */ @Override public void statusInfoChanged(FileTracker tracker) { if(!ignoreNextStatusChange) { TrackerStateHint hint = fileTracker.hasStatusInfo() ? TrackerStateHint.UPDATE_DONE : TrackerStateHint.UNKNOWN; showFileTrackerState(hint); } ignoreNextStatusChange = false; } /** * @see bwfdm.replaydh.io.TrackerListener#refreshStarted(bwfdm.replaydh.io.FileTracker) */ @Override public void refreshStarted(FileTracker tracker) { showFileTrackerState(TrackerStateHint.UPDATING); } /** * @see bwfdm.replaydh.io.TrackerListener#refreshFailed(bwfdm.replaydh.io.FileTracker, java.lang.Exception) */ @Override public void refreshFailed(FileTracker tracker, Exception e) { showFileTrackerState(TrackerStateHint.UPDATE_FAILED); } /** * @see bwfdm.replaydh.io.TrackerListener#refreshDone(bwfdm.replaydh.io.FileTracker, boolean) */ @Override public void refreshDone(FileTracker tracker, boolean canceled) { TrackerStateHint hint = canceled ? TrackerStateHint.UPDATE_CANCELLED : TrackerStateHint.UPDATE_DONE; showFileTrackerState(hint); } /** * @see bwfdm.replaydh.io.TrackerListener#trackingStatusChanged(bwfdm.replaydh.io.FileTracker, java.util.Set, bwfdm.replaydh.io.TrackingAction) */ @Override public void trackingStatusChanged(FileTracker tracker, Set<Path> files, TrackingAction action) { update(); } @Experimental private Path getNewFile() { Path workspace = fileTracker.getTrackedFolder(); Path file; do { String fileName = "test"+String.valueOf(1+random.nextInt(200))+".txt"; file = workspace.resolve(fileName); } while(Files.exists(file, LinkOption.NOFOLLOW_LINKS)); return file; } @Experimental private void createDummyFile() { checkDevMode(); Path file = getNewFile(); try { Files.createFile(file); appendToDummyFile(file); } catch (IOException e) { log.error("Failed to create dummy file: "+file, e); GuiUtils.beep(); } } @Experimental private Path getRandomFile() { try { Path[] files = Files.list(fileTracker.getTrackedFolder()) .filter(path -> path.getFileName().toString().startsWith("test")) .sorted() .toArray(size -> new Path[size]); int num = files.length; return num>0 ? files[random.nextInt(num)] : null; } catch (IOException e) { log.error("Failed to pick random file in folder", e); GuiUtils.beep(); return null; } } @Experimental private void editDummyFile() { checkDevMode(); Path file = getRandomFile(); if(file!=null) { appendToDummyFile(file); } } private void appendToDummyFile(Path file) { try(Writer w = Files.newBufferedWriter(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { w.append(LocalDateTime.now().toString()); w.append(System.lineSeparator()); } catch (IOException e) { log.error("Failed to edit random file {}", file, e); } } @Experimental private void deleteDummyFile() { checkDevMode(); Path file = getRandomFile(); if(file!=null) { try { Files.delete(file); } catch (IOException e) { log.error("Failed to delete random file {}", file, e); } } } } }
# ๅฐ†ไธคไธชๅ‡ๅบ้“พ่กจๅˆๅนถไธบไธ€ไธชๆ–ฐ็š„ ๅ‡ๅบ ้“พ่กจๅนถ่ฟ”ๅ›žใ€‚ๆ–ฐ้“พ่กจๆ˜ฏ้€š่ฟ‡ๆ‹ผๆŽฅ็ป™ๅฎš็š„ไธคไธช้“พ่กจ็š„ๆ‰€ๆœ‰่Š‚็‚น็ป„ๆˆ็š„ใ€‚ # # # # ็คบไพ‹๏ผš # # ่พ“ๅ…ฅ๏ผš1->2->4, 1->3->4 # ่พ“ๅ‡บ๏ผš1->1->2->3->4->4 # # Related Topics ้“พ่กจ # ๐Ÿ‘ 1260 ๐Ÿ‘Ž 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # ่ฟญไปฃ:ๅˆคๆ–ญ่กจๅคดๅ“ชไธ€ไธชๅ€ผๆ›ดๅฐ๏ผŒๆทปๅŠ ๅˆฐ่Š‚็‚น,ๅŽŸๅœฐ่ฐƒๆ•ดๆŒ‡ๅ‘ # ๆ—ถ้—ดn+m๏ผŒ็ฉบ้—ด1 head = ListNode(0) pre = head while l1 and l2: if l1.val <= l2.val: pre.next = l1 l1 = l1.next else: pre.next = l2 l2 = l2.next pre = pre.next # ๅˆๅนถๅŽ๏ผŒๆœ€ๅคšๅ‰ฉไธ€ไธช็š„๏ผŒๆ•ฐๅ€ผๅพˆๅคง๏ผŒ็›ดๆŽฅๆ’ๅ…ฅๅŽ้ข if l1 is not None: pre.next = l1 else: pre.next = l2 return head.next def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode: # ้€’ๅฝ’๏ผšๆ—ถ้—ดO(n+m),็ฉบ้—ดO(n+m) if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
import { TECH_STACKS } from '@/constants'; import { QueryType } from '@/type'; import { Button, Form, Input, InputNumber, message, Radio, Select } from 'antd'; import dayjs from 'dayjs'; import { Dispatch, SetStateAction } from 'react'; import styles from './Sider.module.scss'; const Option = Select.Option; export default function Sider({ onSend, loading, setQrShow, hasKey, }: { onSend: (values: QueryType) => Promise<void>; loading: boolean; setQrShow: Dispatch<SetStateAction<boolean>>; hasKey: boolean; }) { const handleFinish = (values: QueryType) => { if (hasKey) { return onSend(values); } const limitFetch = JSON.parse(localStorage.getItem('limitFetch') || '{}'); const resumeCode = localStorage.getItem('resumeCode'); if (!resumeCode) setQrShow(true); const dateA = dayjs(); const dateB = dayjs(limitFetch.day); const daysDiff = dayjs(dateA).diff(dayjs(dateB), 'day'); // ๅคฉๆ•ฐๅคงไบŽ1ๅคฉๆˆ–่€…ๆฌกๆ•ฐๅฐไบŽ10ๆฌก้ƒฝๅฏไปฅ่ฏทๆฑ‚ if (daysDiff >= 1) { localStorage.setItem( 'limitFetch', JSON.stringify({ day: dateA, count: 1, }) ); } else if (!limitFetch?.count || limitFetch?.count <= 10) { localStorage.setItem( 'limitFetch', JSON.stringify({ day: dateA, count: (limitFetch.count || 0) + 1, }) ); } else { // ๅคฉๆ•ฐๅฐไบŽ10๏ผŒๆฌกๆ•ฐๅคงไบŽ10 return message.warning('ๆฌกๆ•ฐ้™ๅˆถ๏ผŒๆ˜Žๅคฉๅ†ๅฐ่ฏ•'); } onSend(values); }; return ( <div className={styles.sider}> <div className={styles.title}>ChatResume</div> <div className={styles.tips1}> ่‹ฅไธ€็›ดๆ— ๆณ•่ฟ”ๅ›ž็ป“ๆžœ๏ผŒๅˆ™่กจๆ˜Žkey็š„้ขๅบฆ็”จๅฎŒไบ†ๆˆ–่€…้œ€่ฆ็ง‘ๅญฆไธŠ็ฝ‘ใ€‚ </div> <div className={styles.tips2}> ไธบไบ†ๅปถ้•ฟkey็š„ไฝฟ็”จๆ—ถ้—ด๏ผŒๆ‰€ไปฅ้™ๅˆถไบ†ไฝฟ็”จ้ข‘็އใ€‚ๅณไธŠ่ง’่ฎพ็ฝฎ่‡ชๅทฑ็š„keyๅˆ™ๆฒกๆœ‰ไฝฟ็”จๆฌกๆ•ฐ้™ๅˆถใ€‚ </div> <Form onFinish={handleFinish} layout="vertical" size="middle" initialValues={{ isNeedTitle: 'ๅฆ' }} > <Form.Item name="title" label="้กน็›ฎๅ็งฐ" rules={[{ required: true, message: '่ฏท่พ“ๅ…ฅๆ ‡้ข˜' }]} > <Input placeholder="่พ“ๅ…ฅไฝ ็š„้กน็›ฎๅ็งฐ" /> </Form.Item> <Form.Item name="isNeedTitle" label="ๆ˜ฏๅฆ้œ€่ฆๅˆซๅ"> <Radio.Group> <Radio value="ๆ˜ฏ">ๆ˜ฏ</Radio> <Radio value="ๅฆ">ๅฆ</Radio> </Radio.Group> </Form.Item> <Form.Item name="year" label="ๅทฅไฝœ็ป้ชŒ"> <InputNumber placeholder="่พ“ๅ…ฅไฝ ๅธŒๆœ›็š„ๅนด้™" /> </Form.Item> <Form.Item name="techStacks" label="ๆŠ€ๆœฏๆ ˆ" rules={[{ required: true, message: '่ฏท้€‰ๆ‹ฉๆŠ€ๆœฏๆ ˆ' }]} > <Select mode="tags" placeholder="้€‰ๆ‹ฉไฝ ้กน็›ฎๆŠ€ๆœฏๆ ˆ" maxTagCount={5} filterOption={(inputValue: string, option: { value: string }) => { return (option?.value as string) .toLowerCase() .includes(inputValue.toLowerCase()); }} > {TECH_STACKS.map((stack) => ( <Option key={stack} value={stack}> {stack} </Option> ))} </Select> </Form.Item> <Form.Item name="business" label="ไธšๅŠกๆ–นๅ‘"> <Input placeholder="่พ“ๅ…ฅไฝ ็š„ไธšๅŠก" /> </Form.Item> <Button loading={loading} htmlType="submit" size="middle" className={styles.button} > ็”Ÿๆˆ </Button> </Form> </div> ); }
<?php /* * This file is part of the 'octris/core' package. * * (c) Harald Lapp <harald@octris.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Octris\Core\Db\Type; /** * Iterator for recursive iterating data objects of query results * * @copyright copyright (c) 2012-2014 by Harald Lapp * @author Harald Lapp <harald@octris.org> */ class DataIterator implements \Iterator { /** * The dataobject to iterate. * * @type \Octris\Core\Db\Type\SubObject */ protected $data; /** * Keys stored in dataobject. * * @type array */ protected $keys; /** * Internal pointer position. * * @type int */ protected $position = 0; /** * Constructor. * * @parem \Octris\Core\Db\Type\SubObject $dataobject The dataobject to iterate. */ public function __construct(\Octris\Core\Db\Type\SubObject $dataobject) { $this->data = $dataobject; $this->keys = $dataobject->getKeys(); } /** Iterator **/ /** * Get value of item. * * @return mixed Value stored at current position. */ public function current() { return $this->data[$this->keys[$this->position]]; } /** * Get key of current item. * * @return scalar Key of current position. */ public function key() { return $this->keys[$this->position]; } /** * Advance pointer. */ public function next() { ++$this->position; } /** * Reset pointer. */ public function rewind() { $this->position = 0; } /** * Test if current pointer position is valid. * * @return bool True, if position is valid. */ public function valid() { return isset($this->keys[$this->position]); } }
import React, {useContext, useEffect} from "react"; import {browseDisplayStrings} from "../../../resources/PublicDisplayStrings"; import {LocaleContext} from "../../../context/LocaleContext"; import {apiUrl} from "../../../helpers/Variables"; import Panel from "../../commons/elements/containers/Panel"; import ArticleCard from "../../commons/elements/containers/ArticleCard"; import {PanelLoader} from "../../commons/elements/loaders/Loader"; import {PanelEmp} from "../../commons/elements/loaders/AlertEmpty"; import {PanelErr} from "../../commons/elements/loaders/AlertError"; const BrowseBlogs = ({user, data, isLoading, isError, fetchData}) => { // Localizations browseDisplayStrings.setLanguage(useContext(LocaleContext)); // Executes fetch on page load const api = `${apiUrl}/blogs/getall?page=1&limit=100${user ? `&userID=${user.id}` : ``}`; useEffect(() => { fetchData(api); }, [user]); return ( <section> <div className="section-content"> <h1>{browseDisplayStrings.browseBlogsHeader}</h1> <p>{browseDisplayStrings.browseBlogsSubheader}</p> <Panel filler="card--full"> {!isLoading ? <> {!isError ? <> {data && data.length > 0 ? <> {data.map(item => ( <ArticleCard className="card--full" key={item.blog_id} id={item.blog_id} type="blog" title={item.blog_title} thumbnail={item.blog_thumbnail} subtitle={item.blog_subtitle} userId={item.user_id} firstName={item.first_name} lastName={item.last_name} time={item.time_created} isFavorite={item.is_like} totalLikes={item.totalLike}/>))} </> : <PanelEmp/>} </> : <PanelErr reload={() => fetchData(api)}/>} </> : <PanelLoader/>} </Panel> </div> </section> ) } export default BrowseBlogs;
import "./product-search-bar.css"; import React, { Dispatch, SetStateAction, useState } from "react"; import ICategory from "../../models/category.model"; import IBrand from "../../models/brand.model"; export interface ProductSearchBarProps { className?: string; categories: ICategory[]; brands: IBrand[]; searchFilter: Dispatch<SetStateAction<string | undefined>>; categoryFilter: Dispatch<SetStateAction<number | undefined>>; brandFilter: Dispatch<SetStateAction<number | undefined>>; } export const ProductSearchBar: React.FC<ProductSearchBarProps> = ({ className = "", categories, brands, searchFilter, categoryFilter, brandFilter, }) => { const [brand, setBrandValue] = useState<number | undefined>(undefined); const [category, setCategoryValue] = useState<number | undefined>(undefined); const [searchValue, setSearchValue] = useState<string | undefined>(undefined); const handleSearchInputChange = ( event: React.ChangeEvent<HTMLInputElement> ) => { setSearchValue(event.target.value); searchFilter(event.target.value); }; const handleBrandSelectChange = ( event: React.ChangeEvent<HTMLSelectElement> ) => { setBrandValue(parseInt(event.target.value)); brandFilter(parseInt(event.target.value)); }; const handleCategorySelectChange = ( event: React.ChangeEvent<HTMLSelectElement> ) => { setCategoryValue(parseInt(event.target.value)); categoryFilter(parseInt(event.target.value)); }; return ( <div className={`${className} searchContainer`}> <label> <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" className="css-i6dzq1" > <circle cx="11" cy="11" r="8"></circle> <line x1="21" y1="21" x2="16.65" y2="16.65"></line> </svg> <input placeholder="Buscar Producto" type="search" value={searchValue} onChange={handleSearchInputChange} /> </label> <select defaultValue="" className="searchSelect" value={brand} onChange={handleBrandSelectChange} > <option hidden value=""> Lรญnea </option> {brands.map((brand: IBrand) => ( <option value={brand.id}>{brand.name}</option> ))} </select> <select defaultValue="" className="searchSelect" value={category} onChange={handleCategorySelectChange} > <option hidden value=""> Categorรญa </option> {categories .filter((category) => category.is_active) .map((category: ICategory) => ( <option value={category.id}>{category.name}</option> ))} </select> </div> ); };
import {inject} from 'aurelia-framework'; import {Dependency} from './dependecy'; import {Redirect} from 'aurelia-router'; @inject(Dependency) export class App { constructor() { this.header = 'Navigation'; this.content = 'Page info'; console.log(Dependency); } updateContent() { this.header = 'New Cool Name' this.content = 'New Content' } configureRouter(config, router) { this.router = router; config.title = 'Aurelia Recipe App'; config.map([ { route: ['', 'home'], name: 'home', moduleId: 'home/index', title: 'Main Page', nav: true }, { route: 'login', name: 'login', moduleId: 'login', title: 'Log In', nav: true }, { route: 'registration', name: 'registration', moduleId: 'registration', title: 'Registration', nav: true }, { route: 'fridge', name: 'fridge', moduleId: 'fridge', title: 'Fridge', nav: true, settings: { roles: ['admin']} }, { route: 'recipe-add', name: 'recipe-add', moduleId: 'recipe-add', title: 'Add Recipe', nav: true }, ]); } manage_sideBar() { if (document.getElementById("navigation").style.display == "block") { this.close_sideBar(); } else { this.open_sideBar(); } } open_sideBar() { document.getElementById("navigation").style.display = "block"; } close_sideBar() { document.getElementById("navigation").style.display = "none"; } created(owningView, myView) { // Invoked once the component is created... } bind(bindingContext, overrideContext) { // Invoked once the databinding is activated... } attached(argument) { // Invoked once the component is attached to the DOM... } detached(argument) { // Invoked when component is detached from the dom } unbind(argument) { // Invoked when component is unbound... } } class AuthorizeStep { run(navigationInstruction, next) { if (navigationInstruction.getAllInstructions().some(i => i.config.settings.auth)) { var isLoggedIn = false; // insert magic here; if (!isLoggedIn) { return next.cancel(new Redirect('login')); } } return next(); } }
import React from "react"; import { Form } from "antd"; import { useMultiStepForm } from "../Hooks/useMultiStepForm"; import Styles from "../App.module.css"; import From1 from "./From1"; import From2 from "./From2"; import { useFroms } from "../Contest/FormContext"; const NewForm = ({ setOpen }) => { const { steps, currentStepIndex, step, isFirstStep, back, next, isLastStep } = useMultiStepForm([<From1 />, <From2 />]); const { userDetails, setuserDetails, forms, setforms } = useFroms(); function onFinish(e) { setforms((prev) => [...prev, userDetails]); setuserDetails({}); back(); setOpen(false); } console.log(userDetails); return ( <> <Form name="sCorpForm" layout="vertical" onFinish={onFinish}> <div style={{ position: "absolute", top: "1rem", right: "3rem" }}> Page {currentStepIndex + 1}/{steps.length} </div> {step} <div className={Styles.pageButtons}> <div> {isFirstStep && ( <button type="button" onClick={back}> Back </button> )} </div> <div className={Styles.savebutton}> <button type="button" onClick={back}> Save </button> {!isLastStep && ( <button type="button" onClick={next}> Next </button> )} {isLastStep && <button type="submit">Submit</button>} </div> </div> </Form> </> ); }; export default NewForm;
#include "Bureaucrat.hpp" Bureaucrat::Bureaucrat(std::string name, size_t grade) : _name(name), _grade(grade) { if (this->_grade < 1) throw Bureaucrat::GradeTooHighException(); if (this->_grade > 150) throw Bureaucrat::GradeTooLowException(); } Bureaucrat::~Bureaucrat() { } Bureaucrat::Bureaucrat(const Bureaucrat &rhs) { *this = rhs; } Bureaucrat& Bureaucrat::operator=(const Bureaucrat &rhs) { if (this != &rhs) this->_grade = rhs._grade; return (*this); } size_t Bureaucrat::getGrade() const { return (this->_grade); } const std::string Bureaucrat::getName() const { return (this->_name); } void Bureaucrat::incrementGrade() { if (this->_grade > 1) this->_grade -= 1; else throw Bureaucrat::GradeTooHighException(); } void Bureaucrat::decrementGrade() { if (this->_grade < 150) this->_grade += 1; else throw Bureaucrat::GradeTooLowException(); } std::ostream& operator<<(std::ostream &os, const Bureaucrat &rhs) { os << rhs.getName() << ", bureaucrat grade " << rhs.getGrade() << "." << std::endl; return (os); } const char* Bureaucrat::GradeTooHighException::what() const throw() { return ("Grade too high"); } const char* Bureaucrat::GradeTooLowException::what() const throw() { return ("Grade too low"); }
if !exists('g:loaded_telescope') | finish | endif nnoremap <silent> ff <cmd>Telescope find_files<cr> nnoremap <silent> fr <cmd>Telescope live_grep<cr> nnoremap <silent> \\ <cmd>Telescope buffers<cr> nnoremap <silent> ;; <cmd>Telescope help_tags<cr> lua << EOF local actions = require('telescope.actions') local fb_actions = require "telescope".extensions.file_browser.actions local builtin = require("telescope.builtin") -- Global remapping ------------------------------ require("telescope").setup { defaults = { mappings = { n = { ["q"] = actions.close }, }, }, extensions = { file_browser = { theme = "dropdown", -- disables netrw and use telescope-file-browser in its place hijack_netrw = true, mappings = { -- your custom insert mode mappings ["i"] = { ["<C-w>"] = function() vim.cmd('normal vbd') end, }, ["n"] = { -- your custom normal mode mappings ["N"] = fb_actions.create, ["h"] = fb_actions.goto_parent_dir, ["/"] = function() vim.cmd('startinsert') end }, }, }, }, } require("telescope").load_extension "file_browser" vim.keymap.set('n', 'ff', function() builtin.find_files({ no_ignore = false, hidden = true }) end) vim.keymap.set('n', 'fr', function() builtin.live_grep() end) vim.keymap.set('n', '\\\\', function() builtin.buffers() end) vim.keymap.set('n', ';t', function() builtin.help_tags() end) vim.keymap.set('n', ';;', function() builtin.resume() end) vim.keymap.set('n', ';e', function() builtin.diagnostics() end) vim.api.nvim_set_keymap( "n", "fb", ":Telescope file_browser", { noremap = true } )
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"> <h:head> <meta charset="utf-8"></meta> <title><ui:insert name="title">Default Title</ui:insert></title> <meta content="width=device-width, initial-scale=1.0" name="viewport"></meta> <meta content="" name="keywords"></meta> <meta content="" name="description"></meta> <meta charset="utf-8"></meta> <meta name="viewport" content="width=device-width, initial-scale=1"></meta> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></link> <link rel="stylesheet" href="resources/css/mycss.css"></link> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </h:head> <h:body> <h:form> <nav class="navbar bg-dark navbar-dark"> <h:link class="navbar-brand" outcome="dashboard"><img class="grow" src="#{resource['images/cricket.png']}" style="height: 50px;width:65px;" /></h:link> <h:panelGroup rendered="#{sessionBean.isLogged}"> <p id="hm">Welcome,#{sessionBean.email}|<h:graphicImage value="#{rankBean.processFindRank()}"></h:graphicImage>:#{rankBean.returnTypeOfRank()}|Won Trophies: <ui:repeat value="#{trophyBean.catch3Trophies()}" var="trophyTmp" varStatus="getObj"> <h:graphicImage value="#{trophyTmp}"></h:graphicImage> </ui:repeat> </p> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav float-right"> <!-- <li class="nav-item"> <h:commandLink action="#{sessionBean.editUser(sessionBean.email)}" style="color:white;"> #{bundle.User} <img src="https://img.icons8.com/color/48/000000/gender-neutral-user.png"></img> </h:commandLink> </li> --> <li class="nav-item"> <h:link outcome="indexHistory" style="color:white;"> #{bundle.History} <img src="https://img.icons8.com/office/40/000000/opened-folder.png"></img> </h:link> </li> <li class="nav-item"> <h:link outcome="indexTrophy" style="color:white;"> #{bundle.Trophy} <img src="https://img.icons8.com/color/48/000000/trophy.png"></img> </h:link> </li> <li class="nav-item"> <h:link outcome="indexCategories" style="color:white;"> #{bundle.Categories} <img src="https://img.icons8.com/office/40/000000/opened-folder.png"></img> </h:link> </li> <li class="nav-item"> <li> <h:commandLink action="#{sessionBean.processLogout}"> <img src="https://img.icons8.com/office/30/000000/shutdown.png"></img> </h:commandLink> </li> </li> </ul> </div> </h:panelGroup> </nav> <br></br> </h:form> <div class="container"> <div class="row"> <div class="col-2"></div> <div class="col-8"> <div class="container"> <header class="section-header"> <div class="jumbotron"> <ui:insert name="containerTitle">Default Title</ui:insert> </div> </header> </div> </div> <div class="col-2"></div> </div> <div class="row"> <div class="col-2"></div> <div class="col-8"> <div class="container"> <ui:insert name="containerContent">Default Body</ui:insert> </div> </div> <div class="col-2"></div> </div> <div class="row"> <div class="col-12"> <div class="container"> <div class="copyright"> &copy; Copyright <strong>7(--2) Homens 1 Desafio</strong>| <img src="#{resource['images/isec.png']}" style="height:25px;width:25px;" />|<Strong>UC:</Strong> PS. <Strong> Professor:</Strong> Joรฃo Cunha. <Strong>All Rights Reserved</Strong> </div> </div> </div> </div> </div> <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> <!-- DatePicker JavaScript & CSS --> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> </link> <script src="resources/js/formatDatePicker.js"></script> <script src="resources/js/toggleButton.js"></script> </h:body> </html>
import { Logger } from '@nestjs/common'; import { IoAdapter } from '@nestjs/platform-socket.io'; import { ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; class StartChat { chat: { id: number; me_id: number; opp_id: number; }; } @WebSocketGateway(3201, { transports: ['websocket'], namespace: 'chat', cors: true, }) export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { @WebSocketServer() server: Server; sockets = []; private logger: Logger = new Logger('ChatGateWay'); @SubscribeMessage('startChat') handleStartChat( @ConnectedSocket() socket: Socket, @MessageBody() startChat: StartChat, ) { const { chat: { id, opp_id, me_id }, } = startChat; const chatId = String(id); socket.join(chatId); socket.to(chatId).emit('startChat', { room: chatId }); return; } @SubscribeMessage('events') handleEvent(@MessageBody() data: string): string { console.log(data); this.server.emit(data); return data; } @SubscribeMessage('clientToServer') async handleMessage(@MessageBody() data: string) { console.log(data); return data; } @SubscribeMessage('whoAreThere') handleWho(@MessageBody() data: string) { } @SubscribeMessage('create') handleCreate(@MessageBody() data: string) { console.log(data); return; } afterInit(server: Server) { this.logger.log('Init'); } handleConnection(socket: Socket) { this.logger.log(`Client Connected : ${socket.id}`); } handleDisconnect(socket: Socket) { this.logger.log(`Client Disconnected : ${socket.id}`); } }
<template> <ValidationObserver v-slot="{ handleSubmit }"> <form @submit.prevent="handleSubmit(processForm)"> <div class="modal-card" style="width: 40em"> <header class="modal-card-head"> <p class="modal-card-title"> {{ currentData ? `Edit ${currentData.name}` : "Add a new Client" }} </p> </header> <section class="modal-card-body"> <ValidatedInput v-model="name" placeholder="Enter a client name" maxlength="32" :validation="{ name: 'name', rules: 'required|alpha_dash', }" :field="{ label: 'Name', expanded: true }" /> <ValidatedInput v-model="description" placeholder="Enter client description" type="textarea" maxlength="255" :validation="{ name: 'Description', rules: '' }" :field="{ label: 'Description', expanded: true }" /> <b-table :data="clients.filter((e) => e.name !== startName)"> <b-table-column v-slot="props" label="Name" width="80pt" centered> <p>{{ props.row.name }}</p> </b-table-column> <b-table-column label="Cost" centered v-slot="props"> <ValidatedInput inputType="b-numberinput" v-model="cost[props.row.name]" min="0" step="0.01" :validation="{ rules: 'required', }" :showStar="false" :field="{}" /> </b-table-column> <b-table-column label="Time" centered v-slot="props"> <ValidatedInput inputType="b-numberinput" v-model="time[props.row.name]" min="0" step="0.01" :validation="{ rules: 'required', }" :showStar="false" :field="{}" /> </b-table-column> </b-table> </section> <footer class="modal-card-foot"> <button class="button" type="button" @click="$parent.close()"> Close </button> <button class="button is-primary"> <p v-if="!currentData">Add</p> <p v-else>Update</p> </button> </footer> </div> </form> </ValidationObserver> </template> <script> import { mapActions, mapGetters } from "vuex"; export default { name: "ClientForm", props: ["currentData"], data() { return { name: this.currentData ? this.currentData.name : "", description: this.currentData ? this.currentData.description : "", cost: this.currentData ? this.currentData.cost : {}, time: this.currentData ? this.currentData.time : {}, startName: this.currentData ? this.currentData.name : "", }; }, methods: { ...mapActions("clients", ["getClients", "addClient", "updateClient"]), processForm() { const processFormAction = this.currentData ? this.updateClient : this.addClient; let requestData = { name: this.name, description: this.description, cost: this.cost, time: this.time, }; if (this.currentData) { requestData = { update: { payload: { name: this.name, description: this.description, cost: this.cost, time: this.time, }, clientId: this.currentData.id, }, }; } const toastMessage = this.currentData ? `Updated ${this.name} Client` : "Added a new Client"; processFormAction(requestData) .then(() => { this.$parent.close(); this.$buefy.toast.open({ message: toastMessage, position: "is-top", type: "is-primary", container: "div.toast-space", }); }) .catch((err) => { this.$errorHandler.handleResponseError(err); }); }, }, computed: { ...mapGetters("clients", ["clients"]), }, }; </script>
<template> <main> <div class="container-elements"> <div class="mt-5"> <a v-show="searchedFilmList != 0" class="anchor" href="#film-list">FILM</a> <a v-show="searchedSeriesList != 0" class="anchor" href="#series-list">SERIE TV</a> </div> <div class="pt-3" v-show="searchedFilmList == 0"> <h2 class="text-white text-start display-2 text-center fw-bold">I <span class="main-text-color">FILM</span> DEL MOMENTO</h2> <ElementsList :searchedElements="trends" :searchedCast="searchedFilmActors" :genreList="movieGenre" /> </div> <div class="py-5" v-show="searchedFilmList != 0" id="film-list"> <h2 class="text-white text-start display-2 text-center fw-bold">FILM</h2> <ElementsList :searchedElements="searchedFilmList" :searchedCast="searchedFilmActors" :genreList="movieGenre" /> </div> <div class="py-4" v-show="searchedSeriesList != 0" id="series-list"> <h2 class="text-white text-start display-2 text-center fw-bold">SERIE TV</h2> <ElementsList :searchedElements="searchedSeriesList" :searchedCast ="searchedSeriesActors" :genreList="seriesGenre" /> </div> </div> </main> </template> <script> import axios from 'axios'; import ElementsList from "./ElementsList.vue" export default { props:{ searchedFilmList:Array, searchedSeriesList:Array, searchedFilmActors:Array, searchedSeriesActors:Array, keyApi:String, }, components:{ ElementsList, }, data:function(){ return{ trends:[], seriesGenre:[], movieGenre:[], } }, created(){ axios.get(`https://api.themoviedb.org/3/trending/movie/day?api_key=${this.keyApi}`) // Facciamo una ricerca nei film e popoliamo il suo array .then( (result) => { this.trends = result.data.results axios.get(`https://api.themoviedb.org/3/genre/movie/list?api_key=${this.keyApi}`) .then((result) => { this.movieGenre = result.data.genres }) .catch((error) => { console.warn(error) }) }) axios.get(`https://api.themoviedb.org/3/genre/tv/list?api_key=${this.keyApi}`) .then((result) => { this.seriesGenre = result.data.genres }) .catch((error) => { console.warn(error) }) .catch((error) => { console.warn(error) }) } } </script> <style lang="scss"> @import "../styles/variables.scss"; // Style for both menu horizontal scroll main{ margin-top: 150px; } .container-elements{ margin: 0 100px; .anchor{ text-decoration: none; color: white; padding: 10px 15px; text-align: center; background-color: grey; border-radius: 10px; margin: 0 10px; letter-spacing: 2px; } } </style>
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { UsersComponent } from './users/users.component'; import { PostsComponent } from './posts/posts.component'; import { DetailsComponent } from './details/details.component'; import { TodoComponent } from './todo/todo.component'; const routes: Routes = [ { path: '', component: UsersComponent }, { path: 'details/:id', component: DetailsComponent }, { path: 'posts', component: PostsComponent }, { path: 'todo', component: TodoComponent }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes)], exports: [RouterModule], declarations: [] }) export class AppRoutingModule { }
import numpy as np import torch import re import os import wfdb U_INDICES = [16, 23, 24, 31] NO_U_INDICES = [0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15,17, 18,19,20,21,22,25,26, 27,28,29,30] def extract_info_from_name(filename): parsed = {} basename = os.path.basename(filename).split(".")[0] pattern = r"session(\d+)_participant(\d+)_gesture(\d+)_trial(\d+)" match = re.match(pattern, basename) parsed['session'] = match.group(1) parsed['participant'] = match.group(2) parsed['gesture'] = match.group(3) parsed['trial'] = match.group(4) parsed['filename'] = filename return parsed def extract_basename(filename): """ Function to extract just the unique headers of the dat and hea files (removing the file spec) """ return os.path.splitext(filename)[0] def extract_unique_values_from_folder(folder:str): """ Function to extract just the unique headers of the dat and hea files (removing the file name) """ unique = set() for f in os.listdir(folder): unique.add(extract_basename(os.path.join(folder, f))) return list(unique) def get_label(file): info = extract_info_from_name(file) return int(info['gesture']) def load_file(file:str): """Load in a wav file Args: file (str): This is a filename where the .dat / .hea has been stripped off Returns: _type_: Nd.Array """ wave_file = wfdb.rdrecord(file) wave_data = wave_file.p_signal #filter out the U signal wave_data = wave_data[:, NO_U_INDICES] return wave_data
<template> <q-banner rounded class="bg-grey-3"> <q-img :src=coaBackground height="160px"> <div class="absolute-full text-subtitle2 flex flex-center"> name: {{ name }} <br/> wins: {{ nWins }} <br/> losses: {{ nLosses }} <br/> ratio: {{ ratio }} </div> </q-img> </q-banner> </template> <script lang="ts" setup> import { computed, ComputedRef, defineComponent, } from 'vue'; import { asyncComputed } from '@vueuse/core'; import { useAuthStore } from 'src/stores/auth.store'; import { CoalitionChoice } from 'src/types'; import { useMatchHistoryStore } from 'src/stores/history.store'; import { useSocialStore } from '../stores/social.store'; const $soc = useSocialStore(); const $auth = useAuthStore(); const $his = useMatchHistoryStore(); defineComponent({ name: 'StatsBanner' }); const props = defineProps({ userId: { type: Number, default: -1, }, name: { type: String, default: '', }, nWins: { type: Number, defaut: 0, }, nLosses: { type: Number, default: 0, }, height: { type: String, }, }); const ratio = computed(() => $his.getUserMatchesHistory($auth.user.id)?.stats.ratio); const isSelf = computed(() => (props.userId === $auth.user.id)); const rel = asyncComputed(async () => { if (isSelf.value) { return undefined; } // const res = $soc.getRelByUserId(props.userId); // if (res) { return res; } // try { // await $soc.addRelByUserId(props.userId); // } catch (e) { // // e // } return $soc.getRelByUserId(props.userId); }); const coalition: ComputedRef<CoalitionChoice> = computed(() => { if (isSelf.value) { return $auth.user.coalition; } if (rel.value) { return rel.value.to.coalition; } return CoalitionChoice.FEDERATION; }); const coaBackground = computed(() => `/${coalition.value}_background.jpg`); </script>
#!/usr/bin/python3 """Function that prints a square with # character""" def print_square(size): """prints square with # character""" if type(size) is not int: raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") elif type(size) is float and size < 0: raise TypeError("size must be an integer") else: for i in range(size): for j in range(size): print("#", end="") print()
from django.db import models import random import datetime from django.contrib.auth.models import User from django.utils import timezone from django.core.validators import MaxValueValidator, MinValueValidator import os from django.conf import settings from django.utils.safestring import mark_safe class Publisher(models.Model): name = models.CharField(max_length=200) website = models.URLField() city = models.CharField(max_length=20, blank=True) country = models.CharField(max_length=20, default='USA') def __str__(self): return self.name class Book(models.Model): CATEGORY_CHOICES = [ ('S', 'Scinece&Tech'), ('F', 'Fiction'), ('B', 'Biography'), ('T', 'Travel'), ('O', 'Other') ] title = models.CharField(max_length=200) category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, default='S') num_pages = models.PositiveIntegerField(default=100) price = models.DecimalField(max_digits=10, decimal_places=2,validators=[MaxValueValidator(1000), MinValueValidator(0)]) publisher = models.ForeignKey(Publisher, related_name='books', on_delete=models.CASCADE) description = models.TextField(blank=True) num_reviews = models.PositiveIntegerField(default=0) def __str__(self): return self.title class Member(User): STATUS_CHOICES = [ (1, 'Regular member'), (2, 'Premium Member'), (3, 'Guest Member'), ] status = models.IntegerField(choices=STATUS_CHOICES, default=1) address = models.CharField(max_length=300, blank=True) city = models.CharField(max_length=20, default='Windsor') province = models.CharField(max_length=2, default='ON') last_renewal = models.DateField(default=timezone.now) auto_renew = models.BooleanField(default=True) borrowed_books = models.ManyToManyField(Book, blank=True) image = models.ImageField(upload_to='media', blank=True) externalURL = models.URLField(blank=True) def url(self): if self.externalURL: return self.externalURL else: return os.path.join('/', settings.MEDIA_URL, os.path.basename(str(self.image))) def image_tag(self): return mark_safe('<img src="{}" width="150" height="150" />'.format(self.url())) image_tag.short_description = 'Image' def url(self): # returns a URL for either internal stored or external image url if self.externalURL: return self.externalURL else: # is this the best way to do this?? return os.path.join('/', settings.MEDIA_URL, os.path.basename(str(self.image))) def image_tag(self): # used in the admin site model as a "thumbnail" return mark_safe('<img src="{}" width="50" height="50" />'.format(self.url())) image_tag.short_description = 'Image' class Order(models.Model): ORDER_CHOICES = [ (0, 'Purchase'), (1, 'Borrow') ] books = models.ManyToManyField(Book) member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='books') order_type = models.IntegerField(choices=ORDER_CHOICES, default=1) order_date = models.DateField(default=timezone.now) def __str__(self): return str(self.id) def total_items(self): return self.books.count() class Review(models.Model): reviewer = models.EmailField() book = models.ForeignKey(Book, on_delete=models.CASCADE) rating = models.PositiveIntegerField() comments = models.TextField(blank=True) date = models.DateField(default=timezone.now) def __str__(self): return str(self.id)
// Given a number N and a bit number K, check if Kth index bit of N is set or not. A bit is called set if it is 1. Position of set bit '1' should be indexed starting with 0 from LSB side in binary representation of the number. // Note: Index is starting from 0. You just need to return true or false, driver code will take care of printing "Yes" and "No". // Example 1: // Input: // N = 4 // K = 0 // Output: // No // Explanation: // Binary representation of 4 is 100, in which 0th index bit from LSB is not set. So, return false. // Example 2: // Input: // N = 4 // K = 2 // Output: // Yes // Explanation: // Binary representation of 4 is 100, in which 2nd index bit from LSB is set. So, return true. // Example 3: // Input: // N = 500 // K = 3 // Output: // No // Explanation: // Binary representation of 500 is 111110100, in which 3rd index bit from LSB is not set. So, return false. // Your task: // You don't have to read input or print anything. Your task is to complete the function checkKthbit that takes n and k as parameters and returns either true(if kth bit is set) or false(if kth bit is not set). // Expected Time Complexity: O(1). // Expected Auxiliary Space: O(1). // Constraints: // 1 โ‰ค N โ‰ค 109 // 0 โ‰ค K โ‰ค 31 bool checkKthBit(int n, int k) { return ((n >> k) & 1) == 1; }
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/foundation.dart'; part 'qr_scan_event.dart'; part 'qr_scan_state.dart'; class QRScanBloc extends Bloc<QRScanEvent, QRScanState> { QRScanBloc() : super(const QRScanState()) { on<QRScanOnDetectEvent>(_onQRScanOnDetect); on<QRScanTryAgainEvent>(_onQRScanTryAgain); } Future<void> _onQRScanOnDetect( QRScanOnDetectEvent event, Emitter<QRScanState> emit, ) async { emit(state.copyWith( status: QRScanStatus.inProcess, displayValue: event.displayValue, )); debugPrint(state.displayValue.toString()); try { await Future.delayed(const Duration(milliseconds: 1200)); if (state.displayValue.contains(RegExp(r'^\d+$'))) { emit(state.copyWith( displayValue: int.parse(state.displayValue).toString(), inProcessMsg: 'Validating the Relevent Bicycle', )); // call bicycle api and check the state } else { emit(state.copyWith( errorMsg: '_Bad State : Cannot Validate QR Code', status: QRScanStatus.failure, )); throw Exception(); } } catch (e) { debugPrint(e.toString()); } } Future<void> _onQRScanTryAgain( QRScanTryAgainEvent event, Emitter<QRScanState> emit, ) async { emit(state.copyWith( displayValue: '', errorMsg: 'Null', inProcessMsg: 'Validating the\nQR Code', status: QRScanStatus.initial, )); } }
import { Box, Tooltip } from "@chakra-ui/react" import { FC, PropsWithChildren, useEffect, useRef, useState } from "react" import CopyToClipboard from "react-copy-to-clipboard" import { useOnClickOutside } from "../hooks" interface CopyTooltipProps extends PropsWithChildren { copyValue: string prompt?: string message?: string autoDismiss?: boolean onClick?: () => void } export const CopyTooltip: FC<CopyTooltipProps> = ({ copyValue, prompt = "Click to copy", message = "Copied", autoDismiss = true, children, onClick, }) => { const [visible, setVisible] = useState(false) const timeoutIdRef = useRef<ReturnType<typeof setTimeout>>() const clickOutsideRef = useRef<HTMLDivElement>(null) useOnClickOutside(clickOutsideRef, () => setVisible(false)) useEffect(() => { if (autoDismiss && visible) { timeoutIdRef.current = setTimeout(() => setVisible(false), 2500) } return () => { clearTimeout(timeoutIdRef.current) } }, [autoDismiss, visible]) return ( <Tooltip label={visible ? message : prompt} isOpen={visible || undefined}> <Box ref={clickOutsideRef}> {!onClick && ( <CopyToClipboard text={copyValue} onCopy={() => setVisible(true)}> {children} </CopyToClipboard> )} {onClick && <Box onClick={onClick}>{children}</Box>} </Box> </Tooltip> ) }
import React, { useContext, useRef, useState } from "react"; import { AuthContext } from "@/context/AuthContext"; import classNames from "classnames"; import styles from '@/app/posts/postspage.module.scss'; import { db, storage } from "@/firebase/config"; import { v4 as uuid } from 'uuid'; import { Timestamp, doc, setDoc } from "firebase/firestore"; import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage"; function NewPost() { const [text, setText] = useState(""); const [file, setFile] = useState(null); const { user } = useContext(AuthContext); const refPreview = useRef(); const handleUpload = (e)=>{ console.log("file: ",e.target); setFile(e.target.files[0]); if(e.target.files[0].type.includes("image")){ var reader = new FileReader(); reader.onload = function (e) { refPreview.current.children[1].src = e.target.result; refPreview.current.style.display='flex'; }; reader.readAsDataURL(e.target.files[0]); } else{ refPreview.current.children[1].src = "/file.png"; refPreview.current.style.display='flex'; } } const handleCancel = (e)=>{ setFile(null); refPreview.current.children[1].src=""; refPreview.current.style.display='none'; } const handlePost = async() => { try{ const postId = uuid(); if(file){ const storageRef = ref(storage, uuid()); uploadBytesResumable(storageRef, file).then(() => { getDownloadURL(storageRef).then( async(downloadURL) => { await setDoc(doc(db, "posts", user.uid),{ [postId]:{ text, posterId: user.uid, postDate: Timestamp.now(), like: {}, comment: {}, date: Timestamp.now(), img: downloadURL, } }, {merge: true}); }); }); } else{ await setDoc(doc(db, "posts", user.uid),{ [postId]:{ text, posterId: user.uid, postDate: Timestamp.now(), like: {}, comment: {}, date: Timestamp.now(), } }, {merge: true}); } } catch (err ){ } setText(""); setFile(null); refPreview.current.children[1].src=""; refPreview.current.style.display='none'; }; return ( <> <div className={styles.newPostContainer}> <div className={styles.newPost}> <div className={styles.postTitle}> <img src={user?user.photoURL :"/user.png"} style={{width:"50px", height:"50px", borderRadius:"50%", objectFit:"cover"}}/> <div className={styles.postInfo}> <div className={styles.name}>{user.displayName}</div> </div> </div> <textarea onChange={e=>setText(e.target.value)} value={text} placeholder="ๅœจๆƒณ็”š้บผ?"></textarea> <div className={styles.previewbox} style={{display: "none"}} ref={refPreview}> <div className={styles.previewInfo}> <span>{ file && file.name}</span> <button className={styles.close_btn} onClick={handleCancel}>X</button> </div> <img style={{height:"250px", width:"100%", objectFit:"cover"}}></img> </div> <div className={styles.btnList}> <input type="file" style={{display: "none"}} accept="image/*" id="file" onChange={handleUpload}/> <label className={classNames(styles.btn,styles.pointer,styles.bc_gray)} htmlFor="file"> <img src="/img.png" alt="" /> ๅŠ ๅ…ฅๅœ–็‰‡ </label> { (text || file) ? <button className={classNames(styles.btn,styles.pointer,styles.bc_blue)} onClick={handlePost}>็™ผๅธƒ</button> : <button className={classNames(styles.btn,styles.bc_gray)} >็™ผๅธƒ</button> } </div> </div> </div> </> ); } export default NewPost;
import { type FC } from "react"; import Sidebar from "./Sidebar"; import Topbar from "./Topbar"; interface ILayoutProps { children: React.ReactNode; } const Layout: FC<ILayoutProps> = ({ children }) => { return ( <div className="min-w-screen flex relative w-full h-full bg-white"> <Sidebar /> <div className="w-5/6 h-full flex flex-col"> <Topbar /> <div className="w-full flex-1 overflow-y-auto">{children}</div> </div> </div> ); }; export default Layout;
// Different data types and attributes example class DataTypeAttributes extends HTMLElement { // Return list of attributes static get observedAttributes() { return ['text', 'integer', 'number', 'date', 'boolean']; } // Callback function that the browser calls to inform the custom element that one of its // attributes has changed. attributeChangedCallback(name, oldValue, newValue) { // Update the information this._updateInfo(); } // Public method to set the text attribute to something random setRandomText() { // Set character list const charList = 'abcdefghijklmnopqrstuvwxyz'; // Set text list let textList = []; // For each character for (let count = 0; count < 10; count++) { // Add random character to text list textList.push(charList.charAt(Math.random() * charList.length)); } // Set text attribute this.setAttribute('text', textList.join('')); } // Public method to set the integer attribute to something random setRandomInteger() { // Make a random integer const randomInteger = Math.floor(Math.random() * 1000000); // Set integer attribute this.setAttribute('integer', randomInteger.toString()); } // Public method to set the number attribute to something random setRandomNumber() { // Make a random number const randomNumber = (Math.random() * 1000000); // Set number attribute this.setAttribute('number', randomNumber.toFixed(4)); } // Public method to set the date attribute to something random setRandomDate() { // Create random date const randomDate = new Date((new Date()) - Math.floor(Math.random() * 10000000000)); // Set date attribute this.setAttribute('date', randomDate.toISOString()); } // Public method to switch the boolean attribute switchBoolean() { // If the attribute exists if (this.hasAttribute('boolean') === true) { // Remove the attribute this.removeAttribute('boolean'); } else { // Add the attribute (without a value) this.setAttribute('boolean', ''); } } // Get text method _getText() { // Get text attribute value const textValue = this.getAttribute('text'); // If nothing then return default if (!textValue) return ''; // Return the text value return textValue; } // Get integer method _getInteger() { // Get integer attribute value const integerValue = this.getAttribute('integer'); // If nothing then return default if (!integerValue) return 0; // Convert into an integer const integer = parseInt(integerValue); // If not a valid number if (isNaN(integer) === true) return 0; // Return the integer return integer; } // Get number method _getNumber() { // Get number attribute value const numberValue = this.getAttribute('number'); // If nothing then return default if (!numberValue) return 0; // Convert into a number const number = parseFloat(numberValue); // If not a valid number if (isNaN(number) === true) return 0; // Return the number return number; } // Get date method _getDate() { // Get date attribute value const dateValue = this.getAttribute('date'); // If nothing then return default if (!dateValue) return null; // Parse the ISO date into milliseconds const dateMilliseconds = Date.parse(dateValue); // Convert into a date const date = new Date(dateMilliseconds); // Return the date return date; } // Get boolean method _getBoolean() { // If has attribute then return true value if (this.hasAttribute('boolean') === true) return true; // Otherwise return false value return false; } // Update the text information _updateInfo() { // Get current values const text = this._getText(); const integer = this._getInteger(); const number = this._getNumber(); const date = this._getDate(); const boolean = this._getBoolean(); // Set HTML this.innerHTML = ` <b>text = ${text}</b><br> <b>integer = ${integer}</b><br> <b>number = ${number}</b><br> <b>date = ${date}</b><br> <b>boolean = ${boolean}</b><br> `; } } // Tell the browser about the new tag and the class it is linked to customElements.define('data-type-attributes', DataTypeAttributes);
package domain; public class Employee extends Person implements Worker, Comparable { protected int no; protected int year; public Employee(int no, String firstName, String lastName) { super(firstName, lastName); this.no = no; } public Employee(int no, String firstName, String lastName, int year) { super(firstName, lastName); this.no = no; this.year = year; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getYear() { return year; } @Override public String toString() { return "Employee: No - " + no + ", Year - " + year + ", First Name - " + firstName + ", Last Name - " + lastName; } @Override public int hashCode() { System.out.println("hashCode() on Employee with no: " + no); return no; } @Override public boolean equals(Object obj) { System.out.println("equals() on Employee with no: " + no); if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Employee other = (Employee) obj; System.out.println("equals() on Employee with no: " + this + " other Employee with no: " + obj); return no == other.no; } @Override public void work() { System.out.println("Employee is working!"); } @Override public double calculateSalary() { return year * BASE_SALARY; } @Override public int compareTo(Object o) { Employee other = (Employee) o; return Integer.compare(no, other.no); // We can use the code instead of it: // int result = Integer.compare(no, other.no); // if (no == other.no) { // result = 0; // } else if (no < other.no) { // result = -1; // } else { // result = 1; // } // return result; } // @Override // public int compareTo(Object o) { // Employee other = (Employee) o; // return lastName.compareTo(other.lastName); // } }
package TOML; # ------------------------------------------------------------------- # TOML - Parser for Tom's Obvious, Minimal Language. # # Copyright (C) 2013 Darren Chamberlain <darren@cpan.org> # ------------------------------------------------------------------- use 5.008005; use strict; use warnings; use Exporter 'import'; our ($VERSION, @EXPORT, @_NAMESPACE, $PARSER); use B; use Carp qw(croak); use TOML::Parser 0.03; $VERSION = "0.97"; @EXPORT = qw(from_toml to_toml); $PARSER = TOML::Parser->new(inflate_boolean => sub { $_[0] }); sub to_toml { my $stuff = shift; local @_NAMESPACE = (); _to_toml($stuff); } sub _to_toml { my ($stuff) = @_; if (ref $stuff eq 'HASH') { my $res = ''; my @keys = sort keys %$stuff; for my $key (grep { ref $stuff->{$_} ne 'HASH' } @keys) { my $val = $stuff->{$key}; $res .= "$key = " . _serialize($val) . "\n"; } for my $key (grep { ref $stuff->{$_} eq 'HASH' } @keys) { my $val = $stuff->{$key}; local @_NAMESPACE = (@_NAMESPACE, $key); $res .= sprintf("[%s]\n", join(".", @_NAMESPACE)); $res .= _to_toml($val); } return $res; } else { croak("You cannot convert non-HashRef values to TOML"); } } sub _serialize { my $value = shift; my $b_obj = B::svref_2object(\$value); my $flags = $b_obj->FLAGS; return $value if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV? my $type = ref($value); if (!$type) { return string_to_json($value); } elsif ($type eq 'ARRAY') { return sprintf('[%s]', join(", ", map { _serialize($_) } @$value)); } elsif ($type eq 'SCALAR') { if (defined $$value) { if ($$value eq '0') { return 'false'; } elsif ($$value eq '1') { return 'true'; } else { croak("cannot encode reference to scalar"); } } croak("cannot encode reference to scalar"); } croak("Bad type in to_toml: $type"); } my %esc = ( "\n" => '\n', "\r" => '\r', "\t" => '\t', "\f" => '\f', "\b" => '\b', "\"" => '\"', "\\" => '\\\\', "\'" => '\\\'', ); sub string_to_json { my ($arg) = @_; $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g; $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg; return '"' . $arg . '"'; } sub from_toml { my $string = shift; local $@; my $toml = eval { $PARSER->parse($string) }; return wantarray ? ($toml, $@) : $toml; } 1; __END__ =encoding utf-8 =for stopwords versa =head1 NAME TOML - Parser for Tom's Obvious, Minimal Language. =head1 SYNOPSIS use TOML qw(from_toml to_toml); # Parsing toml my $toml = slurp("~/.foo.toml"); my $data = from_toml($toml); # With error checking my ($data, $err) = from_toml($toml); unless ($data) { die "Error parsing toml: $err"; } # Creating toml my $toml = to_toml($data); =head1 DESCRIPTION C<TOML> implements a parser for Tom's Obvious, Minimal Language, as defined at L<https://github.com/mojombo/toml>. C<TOML> exports two subroutines, C<from_toml> and C<to_toml>, =head1 FAQ =over 4 =item How change how to de-serialize? You can change C<$TOML::PARSER> for change how to de-serialize. example: use TOML; use TOML::Parser; local $TOML::PARSER = TOML::Parser->new( inflate_boolean => sub { $_[0] eq 'true' ? \1 : \0 }, ); my $data = TOML::from_toml('foo = true'); =back =head1 FUNCTIONS =over 4 =item from_toml C<from_toml> transforms a string containing toml to a perl data structure or vice versa. This data structure complies with the tests provided at L<https://github.com/mojombo/toml/tree/master/tests>. If called in list context, C<from_toml> produces a (C<hash>, C<error_string>) tuple, where C<error_string> is C<undef> on non-errors. If there is an error, then C<hash> will be undefined and C<error_string> will contains (scant) details about said error. =item to_toml C<to_toml> transforms a perl data structure into toml-formatted string. =back =head1 SEE ALSO L<TOML::Parser> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA =head1 AUTHOR Darren Chamberlain <darren@cpan.org> =head1 CONTRIBUTORS =over 4 =item Tokuhiro Matsuno <tokuhirom@cpan.org> =item Matthias Bethke <matthias@towiski.de> =item Sergey Romanov <complefor@rambler.ru> =item karupanerura <karupa@cpan.org> =back
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MusicWebApp1.Models; namespace MusicWebApp1.Controllers { [Route("api/[controller]")] [ApiController] public class ArtistController : ControllerBase { private readonly MusicApiContext _context; public ArtistController(MusicApiContext context) { _context = context; } // GET: api/Artist [HttpGet] public async Task<ActionResult<IEnumerable<Artist>>> GetArtists() { if (_context.Artists == null) { return NotFound(); } return await _context.Artists.ToListAsync(); } // GET: api/Artist/5 [HttpGet("{id}")] public async Task<ActionResult<Artist>> GetArtist(int id) { if (_context.Artists == null) { return NotFound(); } var artist = await _context.Artists.FindAsync(id); if (artist == null) { return NotFound(); } return artist; } // PUT: api/Artist/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> PutArtist(int id, Artist artist) { if (id != artist.Id) { return BadRequest(); } _context.Entry(artist).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ArtistExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Artist // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public async Task<ActionResult<Artist>> PostArtist(Artist artist) { if (_context.Artists == null) { return Problem("Entity set 'MusicApiContext.Artists' is null."); } _context.Artists.Add(artist); await _context.SaveChangesAsync(); return CreatedAtAction("GetArtist", new { id = artist.Id }, artist); } // DELETE: api/Artist/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteArtist(int id) { if (_context.Artists == null) { return NotFound(); } var artist = await _context.Artists.FindAsync(id); if (artist == null) { return NotFound(); } _context.Artists.Remove(artist); await _context.SaveChangesAsync(); return NoContent(); } private bool ArtistExists(int id) { return (_context.Artists?.Any(e => e.Id == id)).GetValueOrDefault(); } } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstclear_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ataboada <ataboada@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/05/08 18:54:14 by ataboada #+# #+# */ /* Updated: 2023/10/06 17:35:41 by ataboada ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /** * @brief Deletes and frees the given element and every successor of that * element, using the function โ€™delโ€™ and free(3). Finally, the pointer to the * list must be set to NULL. * @param lst The address of a pointer to an element. * @param del The address of the function used to delete the content of the * element. * @return Nothing. */ void ft_lstclear(t_list **lst, void (*del)(void *)) { t_list *temp; if (!lst || !del || !*(lst)) { return ; } while (*lst) { temp = (*lst)->next; ft_lstdelone(*lst, del); *lst = temp; } lst = 0; }
๏ปฟ// (C) 2024 FOTEC Forschungs- und Technologietransfer GmbH // Das Forschungsunternehmen der Fachhochschule Wiener Neustadt // // Kontakt biss@fotec.at / www.fotec.at // // Erstversion vom 15.11.2023 10:55 // Entwickler Mandl Matthias (MMa) // Projekt IXchange using System; using System.Linq; using System.Threading.Tasks; using Biss.Apps.Attributes; using Biss.Apps.Enum; using Biss.Apps.ViewModel; using Biss.Dc.Server; using ConnectivityHost.Helper; using IXchange.Service.AppConnectivity.DataConnector; using IXchange.Service.AppConnectivity.Helper; namespace ConnectivityHost.BaseApp.ViewModel { /// <summary> /// <para>Viewmodel fรผrs Nachricht versenden</para> /// Klasse VmMessage. (C) 2021 FOTEC Forschungs- und Technologietransfer GmbH /// </summary> [ViewName("ViewMessage")] public class VmMessage : VmProjectBase { /// <summary> /// Design Instanz fรผr XAML d:DataContext="{x:Static viewmodels:VmMessage.DesignInstance}" /// </summary> public static VmMessage DesignInstance = new VmMessage(); /// <summary> /// VmMessage /// </summary> public VmMessage() : base("Nachricht") { View.ShowFooter = false; View.ShowHeader = true; View.ShowBack = true; View.ShowMenu = false; } #region Properties /// <summary> /// Send via Push Command /// </summary> public VmCommand CmdSend { get; set; } = null!; /// <summary> /// Nachrichten Text /// </summary> public VmEntry TitleEntry { get; set; } = new(EnumVmEntryBehavior.Instantly, "รœberschrift"); /// <summary> /// Nachrichten Text /// </summary> public VmEntry MessageEntry { get; set; } = new(EnumVmEntryBehavior.Instantly, "Nachricht"); /// <summary> /// Daten fรผrs Versenden der Nachricht. /// </summary> public SendMessageData Data { get; set; } = new(); /// <summary> /// Dc Connection /// </summary> public IDcConnections DcConnections { get; set; } = null!; /// <summary> /// Server Remote Calls /// </summary> public IServerRemoteCalls ServerRemoteCalls { get; set; } = null!; #endregion /// <summary> /// Wird aufgerufen sobald die View initialisiert wurde /// </summary> /// <param name="args"></param> /// <returns></returns> public override Task OnActivated(object? args = null) { if (args is SendMessageData data) { Data = data; if (Data.SendVia == SendViaEnum.Email) { TitleEntry.Title = "Betreff"; } } TitleEntry.ValidateFunc = Validate; MessageEntry.ValidateFunc = Validate; View.BusyClear(); base.OnActivated(args); return Task.CompletedTask; } /// <summary> /// Commands Initialisieren (aufruf im Kostruktor von VmBase) /// </summary> #pragma warning disable CA1506 protected override void InitializeCommands() #pragma warning restore CA1506 { CmdSend = new VmCommand("Senden", async () => { switch (Data.SendVia) { case SendViaEnum.Dc: var successes = 0; var fails = 0; var currentConnectedDeviceIds = DcConnections.GetClients(); foreach (var tableDevice in Data.Devices) { if (currentConnectedDeviceIds.All(x => x.DeviceId != tableDevice.Id)) { fails++; continue; } try { await ((ServerRemoteCalls) ServerRemoteCalls).SendMessage(MessageEntry.Value, TitleEntry.Value, tableDevice.Id, null).ConfigureAwait(true); successes++; } catch (Exception) { fails++; } } _ = await MsgBox.Show($"Es kamen {successes} Benachrichtigungen an und {fails} nicht an!").ConfigureAwait(true); break; case SendViaEnum.Push: var tokens = Data.Devices.Where(x => !string.IsNullOrWhiteSpace(x.DeviceToken)).Select(x => x.DeviceToken).ToList(); var success = 0; var fail = 0; if (tokens.Any()) { if (tokens.Count > 500) { #pragma warning disable CS0618 // Type or member is obsolete var chunks = tokens.Split(500); #pragma warning restore CS0618 // Type or member is obsolete foreach (var chunk in chunks) { var result = await Push.SendMessageToDevices(TitleEntry.Value, MessageEntry.Value, chunk).ConfigureAwait(true); success += result.SuccessCount; fail += result.FailureCount; } } else { var result = await Push.SendMessageToDevices(TitleEntry.Value, MessageEntry.Value, tokens).ConfigureAwait(true); success = result.SuccessCount; fail = result.FailureCount; } _ = await MsgBox.Show($"Es kamen {success} Benachrichtigungen an und {fail} nicht an!").ConfigureAwait(true); } break; } await Nav.Back().ConfigureAwait(true); }, () => !string.IsNullOrWhiteSpace(TitleEntry.Value) && !string.IsNullOrWhiteSpace(MessageEntry.Value)); } private (string, bool) Validate(string value) { if (string.IsNullOrWhiteSpace(value)) { return ("Darf nicht leer sein!", true); } CmdSend.CanExecute(); return ("", true); } } }
import Link from "next/link" import { Button } from "./ui/button" import { Card } from "./ui/card" const FeatureSection = () => { return ( <section id="features" className="container py-8 space-y-6 rounded-lg md:py-12 lg:py-24" > <div className="mx-auto flex max-w-[58rem] flex-col items-center space-y-4 text-center"> <h2 className="font-heading text-3xl leading-[1.1] sm:text-3xl md:text-6xl"> Features </h2> <p className="max-w-[85%] leading-normal text-muted-foreground sm:text-lg sm:leading-7"> We provide comprehensive computer repair, updating, and troubleshooting services to individuals and businesses. </p> </div> <div className="mx-auto grid justify-center gap-4 sm:grid-cols-2 md:max-w-[64rem] md:grid-cols-3"> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-12 h-12 lucide lucide-shield-alert" > <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path> <path d="M12 8v4"></path> <path d="M12 16h.01"></path> </svg> <div className="space-y-2"> <h3 className="font-bold">Virus Removal</h3> <p className="text-sm text-muted-foreground"> Viruses, malware, and spyware from your computer to ensure it&apos;s running smoothly and securely. </p> </div> </div> </Card> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-12 h-12 lucide lucide-download" > <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path> <polyline points="7 10 12 15 17 10"></polyline> <line x1="12" x2="12" y1="15" y2="3"></line> </svg> <div className="space-y-2"> <h3 className="font-bold">Software Installation</h3> <p className="text-sm text-muted-foreground"> Install and configure software programs, productivity tools, antivirus software, and multimedia apps. </p> </div> </div> </Card> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-12 h-12 lucide lucide-screen-share" > <path d="M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3"></path> <path d="M8 21h8"></path> <path d="M12 17v4"></path> <path d="m17 8 5-5"></path> <path d="M17 3h5v5"></path> </svg> <div className="space-y-2"> <h3 className="font-bold">Remote Support</h3> <p className="text-sm text-muted-foreground"> We provide remote support to diagnose and fix your computer issues without the need for an in-person visit. </p> </div> </div> </Card> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg viewBox="0 0 24 24" className="w-12 h-12 fill-current"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="lucide lucideLaptop" > <path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"></path> </svg>{" "} </svg> <div className="space-y-2"> <h3 className="font-bold">Operating System Updates</h3> <p className="text-sm text-muted-foreground"> Upgrade your operating system to the latest version, ensuring you have access to the latest features and security updates. </p> </div> </div> </Card> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-12 h-12 lucide lucideWrench" > <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path> </svg> <div className="space-y-2"> <h3 className="font-bold">System Optimization</h3> <p className="text-sm text-muted-foreground"> We can help you optimize your computer&apos;s performance by cleaning up unnecessary files, tweaking settings to improve speed and efficiency </p> </div> </div> </Card> <Card> <div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-12 h-12 lucide lucide-hard-drive" > <line x1="22" x2="2" y1="12" y2="12"></line> <path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></path> <line x1="6" x2="6.01" y1="16" y2="16"></line> <line x1="10" x2="10.01" y1="16" y2="16"></line> </svg> <div className="space-y-2"> <h3 className="font-bold">Hardware Upgrades</h3> <p className="text-sm text-muted-foreground"> If your computer is running slowly or need more storage space, we can upgrade your hardware, including RAM, hard drives, and graphics cards </p> </div> </div> </Card> </div> <div className="mx-auto text-center md:max-w-[58rem]"> <p className="leading-normal text-muted-foreground sm:text-lg sm:leading-7"> Troubleshoot can help you with a wide range of computer problems, including hardware issues, software installation, virus removal, and system optimization. </p> </div> <div className="mx-auto text-center md:max-w-[58rem]"> <Button><Link href={"/faq"}> Check out FAQ</Link></Button> </div> </section> ) } export default FeatureSection
import User from "../models/userModel.js"; import bcrypt from "bcryptjs"; import generateToken from "../utils/jwtToken.js"; import sendEmail from "../utils/sendEmail.js"; import { sendVerificationCode } from "../utils/sendEmailSignUp.js"; import generateVerificationCode from "../utils/VerificationCode.js"; import { sendOTPNo } from "../utils/SendOtpPhoneNo.js"; // import crypto from "crypto" // ___________________________Sign Up________________________ // const generateVerificationCode = () => { // return Math.random().toString(36).substr(2, 6).toUpperCase(); // }; const signUp = async (req, res) => { try { const { firstName, lastName, email, password, phoneNumber, dob, gender } = req.body; const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(409).json({ message: 'Email is already registered' }); } if (!req.file) { return res.status(400).json({ message: 'Please upload your image' }); } const avatarPath = req.file.path; const encPassword = await bcrypt.hash(password, 12); // Generate a verification code for email const verificationCode = generateVerificationCode(); const verificationCodeExpiresAt = new Date(Date.now() + 120000); // 120,000 milliseconds = 2 minute (adjust as needed) // Generate a verification code for phone number const isVerificationCode = generateVerificationCode(); const isVerificationCodeExpiresAt = new Date(Date.now() + 120000); // 900,000 milliseconds = 15 minute (adjust as needed) // console.log('verificationCode', verificationCode); const newUser = new User({ firstName, lastName, email, password: encPassword, phoneNumber, dob, gender, avatar: avatarPath, verified: false, //for email verificationCode, verificationCodeExpiresAt, isVerified: false, //for Phone No isVerificationCode, isVerificationCodeExpiresAt, }); // console.log('newUser', newUser); await newUser.save(); // Send the verification code to the user's email // console.log('email, verificationCode', email, verificationCode); await sendVerificationCode(email, verificationCode); await sendOTPNo(phoneNumber, isVerificationCode) return res.status(201).json({ success: true, message: "User created successfully. Please verify your Phone No.", email, }); } catch (error) { console.error('Error in signUp:', error); return res.status(500).json({ message: 'Internal server error' }); } }; export default signUp; export const verifyCode = async (req, res) => { try { console.log('req.body', req.body) const { email, verificationCode } = req.body; // const user = await User.findOne({ email }); const user = await User.findOne({ verificationCode }); console.log('verificationCode', verificationCode); console.log('user.verificationCode', user?.verificationCode); if (!user) { return res.status(404).json({ message: 'User not found' }); } // Check if the verification code has expired if (user.verificationCodeExpiresAt < new Date()) { return res.status(400).json({ message: 'Verification code has expired' }); } if (user.verificationCode === verificationCode) { // Update the user's record to mark it as verified await User.findByIdAndUpdate(user._id, { verified: true }); user.verificationCode = undefined; user.verificationCodeExpiresAt = undefined; await user.save(); return res.status(200).json({ message: 'Verification successful' }); } else { return res.status(400).json({ message: 'Invalid verification code' }); } } catch (error) { console.error('Error in verifyCode:', error); return res.status(500).json({ message: 'Internal server error' }); } }; export const resendVerificationCode = async (req, res) => { try { const { email } = req.body; const user = await User.findOne({ email }); console.log("๐Ÿš€ ~ Resend user:", user) if (!user) { return res.status(404).json({ message: 'User not found' }); } if (user.verified) { return res.status(400).json({ message: 'User is already verified' }); } // Check if the verification code has expired if (user.verificationCodeExpiresAt && user.verificationCodeExpiresAt < new Date()) { // Generate a new verification code const verificationCode = generateVerificationCode(); console.log('New verificationCode', verificationCode); // Update the user's verification code and expiration time in the database user.verificationCode = verificationCode; user.verificationCodeExpiresAt = new Date(Date.now() + 60000); // 60,000 milliseconds = 1 minute (adjust as needed) await user.save(); // Send the new verification code to the user's email await sendVerificationCode(email, verificationCode); return res.status(200).json({ message: 'Verification code resent successfully' }); } else { return res.status(400).json({ message: 'Verification code is still valid' }); } } catch (error) { console.error('Error in resendVerificationCode:', error); return res.status(500).json({ message: 'Internal server error' }); } }; // verify phone number export const verifyCodePhoneNo = async (req, res) => { try { const { phoneNumber, isVerificationCode } = req.body; console.log('isVerificationCode', isVerificationCode) // const user = await User.findOne({ email }); const user = await User.findOne({ isVerificationCode }); console.log('isVerificationCode', isVerificationCode); console.log('user.isVerificationCode', user?.isVerificationCode); if (!user) { return res.status(404).json({ message: 'User not found' }); } // Check if the verification code has expired if (user.isVerificationCodeExpiresAt < new Date()) { return res.status(400).json({ message: 'Verification code has expired' }); } if (user.isVerificationCode === isVerificationCode) { // Update the user's record to mark it as verified await User.findByIdAndUpdate(user._id, { isVerified: true }); user.isVerificationCode = undefined; user.isVerificationCodeExpiresAt = undefined; await user.save(); return res.status(200).json({ message: 'Verification successful' }); } else { return res.status(400).json({ message: 'Invalid verification code' }); } } catch (error) { console.error('Error in verifyCode:', error); return res.status(500).json({ message: 'Internal server error' }); } }; export const resendOtpNo = async (req, res) => { try { const { email, phoneNumber } = req.body; console.log('email', email); console.log('phoneNumber', phoneNumber); const user = await User.findOne({ email }); console.log('user', user); if (!user) { return res.status(404).json({ message: 'User not found' }); } if (user.isVerified) { return res.status(400).json({ message: 'User is already verified' }); } // Check if the verification code has expired if (user.isVerificationCodeExpiresAt && user.isVerificationCodeExpiresAt < new Date()) { const isVerificationCode = generateVerificationCode(); console.log('New isVerificationCode', isVerificationCode); // Update the user's verification code and expiration time in the database user.isVerificationCode = isVerificationCode; user.isVerificationCodeExpiresAt = new Date(Date.now() + 120000) // 900000 milliseconds = 15 minutes (adjust as needed) await user.save(); // Send the new verification code to the user's phone number await sendVerificationCode(phoneNumber, isVerificationCode); return res.status(200).json({ message: 'Verification code resent successfully' }); } else { return res.status(400).json({ message: 'Verification code is still valid' }); } } catch (error) { console.error('Error in resendOtpNo:', error); return res.status(500).json({ message: 'Internal server error' }); } }; // const signUp = async (req, res) => { // try { // const { firstName, lastName, email, password, dob, gender } = req.body; // const existingUser = await User.findOne({ email }); // if (existingUser) { // return res.status(409).json({ message: 'Email is already registered' }); // } // if (!req.file) { // return res.status(400).json({ message: 'Please upload your image' }); // } // const avatarPath = req.file.path; // const encPassword = await bcrypt.hash(password, 12); // const newUser = new User({ // firstName, // lastName, // email, // password: encPassword, // dob, // gender, // avatar: avatarPath, // }); // await newUser.save(); // return res.status(201).json({ message: 'User created successfully' }); // } catch (error) { // console.error('Error in signUp:', error); // return res.status(500).json({ message: 'Internal server error' }); // } // } // export default signUp; // ___________________________Login________________________ export const userLogin = async (req, res) => { try { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) { return res.status(404).json({ message: 'User not found' }); } const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return res.status(400).json({ message: 'Invalid email or password' }); } if (!user.verified) { return res.status(401).json({ message: "Account not verified. Please verify your email first." }); } // if (!user.phoneNumber || !user.isVerified) { // return res.status(401).json({ message: "Account not verified. Please verify your PhoneNo first." }); // // await res.status(201).json({ message: "Account not verified. Please verify your PhoneNo first." }); // } const token = generateToken(email); res.status(200).json({ message: 'User signed in successfully . Please verify your PhoneNo first.', token, user }); } catch (error) { console.error('Error in signIn User:', error); res.status(500).json({ message: 'Internal server error' }); } }; // ___________________________Forget password email________________________ export const forgotPassword = async (req, res, next) => { try { const { email } = req.body; const user = await User.findOne({ email }); if (!user) { return res.status(404).json({ message: 'User not found' }); } const resetToken = generateToken(email); user.resetPasswordToken = resetToken; user.resetPasswordExpire = Date.now() + 3600000; await user.save(); const verifyUrl = `${process.env.FRONTEND_URL}/password/reset/${resetToken}`; const message = `Your password reset token is ttemp :- \n\n${verifyUrl}\n\nIf you have not requested this email, please ignore it.`; await sendEmail({ email: user.email, subject: 'My App Password Reset', message, }); res.status(200).json({ success: true, message: `Email sent to ${user.email} successfully`, }); } catch (error) { console.error('Error in forgotPassword:', error); res.status(500).json({ message: 'Failed to send email' }); } }; // ___________________________Reset Password________________________ export const resetPassword = async (req, res, next) => { try { const { token } = req.params; const { password, confirmPassword } = req.body; const user = await User.findOne({ resetPasswordToken: token, }); if (!user) { return res.status(400).json({ message: 'Invalid or expired reset token' }); } const encPassword = await bcrypt.hash(password, 12); // Update the user's password and clear the reset token fields user.password = encPassword; user.resetPasswordToken = undefined; user.resetPasswordExpire = undefined; await user.save(); // Respond with a success message res.status(200).json({ success: true, message: 'Password reset successful' }); } catch (error) { console.error('Error in resetPassword:', error); res.status(500).json({ message: 'Failed to reset password' }); } }; // ___________________________User Auth________________________ export const userAuth = (req, res) => { res.status(200).json({ message: 'Authentication Successfully', user: req.user }); }; // ___________________________Update Password________________________ // export const updatePassword = async (req, res, next) => { // try { // const user = await User.findById(req.user._id); // const isPasswordMatched = await bcrypt.compare( // req.body.oldPassword.toString(), // user.password.toString() // ); // if (!isPasswordMatched) { // return res.status(404).json({ message: 'Old password is incorrect' }); // } // if (req.body.newPassword !== req.body.confirmPassword) { // return res.status(400).json({ message: 'Passwords do not match' }); // } // const encPassword = await bcrypt.hash(req.body.newPassword, 12); // user.password = encPassword; // await user.save(); // res.status(200).json({ success: true, message: 'Password updated successfully' }); // } catch (error) { // console.error('Error in updatePassword:', error); // res.status(500).json({ message: 'Failed to update password' }); // } // }; export const updatePassword = async (req, res, next) => { try { const user = await User.findById(req.user._id); console.log('user update', user); console.log('req.body', req.body) console.log("req.body.oldPassword", req.body.oldPassword) console.log("user.password", user.password) const isPasswordMatched = await bcrypt.compare(req.body.oldPassword, user.password,); // const isPasswordMatched = await bcrypt.compare( // req.body.oldPassword.toString(), // user.password.toString() // ); console.log('isPasswordMatched', isPasswordMatched) if (!isPasswordMatched) { return res.status(404).json({ message: 'Old password is incorrect' }); } if (req.body.newPassword !== req.body.confirmPassword) { return res.status(400).json({ message: 'Password do not match' }); } // Password bcrypt const encPassword = await bcrypt.hash(req.body.newPassword, 12); // user.password = req.body.newPassword; user.password = encPassword; await user.save(); res.status(200).json({ success: true, message: 'Password updated successfully' }); } catch (error) { console.error('Error in updatePassword:', error); res.status(500).json({ message: 'Failed to update password' }); } }; // ___________________________Update Profile________________________ export const updateProfile = async (req, res) => { try { // Find the user by ID const userId = req.user.id; console.log(" updateProfile ~ userId:", userId) const user = await User.findById(userId); if (!user) { return res.status(404).json({ message: 'User not found' }); } // Update the user's avatar if provided if (req.file) { user.avatar = req.file.path; } console.log(" updateProfile ~ req.file:", req.file) // Save the updated user to the database await user.save(); res.status(200).json({ message: 'Profile updated successfully' }); } catch (error) { console.error('Error in updateProfile:', error); res.status(500).json({ message: 'Internal server error' }); } }; // ___________________________Update User Info________________________ export const updateUserInfo = async (req, res) => { try { const { firstName, lastName, dob, gender, phoneNumber } = req.body; // Find the user by ID const userId = req.user.id; const user = await User.findById(userId); if (!user) { return res.status(404).json({ message: 'User not found' }); } // Update the user's firstName, lastName, dob, and gender user.firstName = firstName; user.lastName = lastName; user.phoneNumber = phoneNumber; user.email = email; user.dob = dob; user.gender = gender; // Save the updated user to the database await user.save(); res.status(200).json({ message: 'User Info updated successfully' }); } catch (error) { console.error('Error in update user info:', error); res.status(500).json({ message: 'Internal server error' }); } }; // ___________________________Logout________________________ export const logout = (req, res) => { res.clearCookie('token'); // Clear the token cookie res.status(200).json({ message: 'Logged out successfully' }); };
import { createContext, useContext } from 'react' import { NOTIFICATION_TYPES, NO_NOTIFICATION_STATE, handleAxiosError, NOTIFICATION_TIMEOUT, ERROR_NOTIFICATION_TIMEOUT, } from '@/features/notification' /** * The context object for the notification state. * * @typedef {Object} NotificationContextObject */ const NotificationContext = createContext(NO_NOTIFICATION_STATE) export default NotificationContext /** * The reducer function for the notification state. * * @function notificationReducer * @param {Object} state - The current state of the notification. * @param {Object} action - The action object to apply to the state. * @param {string} action.type - The type of the action. * @param {Object} action.payload - The payload of the action. * @param {string} action.payload.type - The type of the notification (e.g. 'info', 'warning', 'error'). * @param {string} action.payload.message - The message to display in the notification. * @param {string} action.payload.details - Optional details to display in the notification. * @param {Error} action.payload.error - Optional error object to include in the notification. * @param {number} action.payload.timeoutId - Optional ID of the timeout for the notification. * @returns {Object} The new state of the notification. */ export const notificationReducer = (state, action) => { switch (action.type) { case 'notification/setNotification': return { type: action.payload.type, message: action.payload.message, details: action.payload.details, error: action.payload.error, timeoutId: action.payload.timeoutId, } case 'notification/setErrorNotification': return { type: action.payload.type, message: action.payload.message, details: action.payload.details, error: action.payload.error, timeoutId: action.payload.timeoutId, } case 'notification/removeNotification': return NO_NOTIFICATION_STATE default: return state } } /** * A hook that returns the current notification state from the notification context. * * @function useNotificationValue * @returns {Object} The current notification state from the notification context. * @throws {Error} If used outside of an NotificationContextProvider. */ export const useNotificationValue = () => { const context = useContext(NotificationContext) return context.notification } /** * A hook that returns the dispatch function from the notification context. * * @function useNotificationDispatch * @returns {Function} The dispatch function from the notification context. */ export const useNotificationDispatch = () => { const context = useContext(NotificationContext) return context.dispatch } /** * A hook that returns the dispatch function from the notification context. * * @function useNotificationDispatch * @returns {Function} The dispatch function from the notification context. * @throws {Error} If used outside of an NotificationContextProvider. */ export const useSetNotification = () => { const dispatch = useNotificationDispatch() const notificationValue = useNotificationValue() const setNotification = ({ type, message, details, timeoutInSeconds = NOTIFICATION_TIMEOUT, }) => { if (notificationValue.timeoutId) { clearTimeout(notificationValue.timeoutId) } const timeoutId = setTimeout(() => { dispatch({ type: 'notification/removeNotification' }) }, timeoutInSeconds * 1000) return { type: 'notification/setNotification', payload: { type, message, details, error: null, timeoutId, }, } } return setNotification } /** * A hook that returns the setErrorNotification function, which can be used to * set an error notification. * * @function useSetErrorNotification * @returns {Function} The setErrorNotification function. */ export const useSetErrorNotification = () => { const dispatch = useNotificationDispatch() const notificationValue = useNotificationValue() const setErrorNotification = ({ error, message, details, timeoutInSeconds = ERROR_NOTIFICATION_TIMEOUT, }) => { if (notificationValue.timeoutId) { clearTimeout(notificationValue.timeoutId) } const timeoutId = setTimeout(() => { dispatch({ type: 'notification/removeNotification' }) }, timeoutInSeconds * 1000) const payload = handleAxiosError(error, message, details) payload.type = NOTIFICATION_TYPES.ERROR payload.timeoutId = timeoutId return { type: 'notification/setNotification', payload: payload, } } return setErrorNotification } /** * Returns an action object to remove the current notification from the notification state. * * @function removeNotification * @returns {Object} An action object to remove the current notification. */ export const removeNotification = () => { return { type: 'notification/removeNotification', } } /** * A hook that returns the `removeNotification` function, which can be used to remove the current notification from the notification state. * * @function useRemoveNotification * @returns {Function} The `removeNotification` function. */ export const useRemoveNotification = () => { return removeNotification }
""" https://docs.python.org/3/library/sqlite3.html Run this as a standalone Python module. How-to guides for further reading: How to use placeholders to bind values in SQL queries How to adapt custom Python types to SQLite values How to convert SQLite values to custom Python types How to use the connection context manager How to create and use row factories Explanation for in-depth background on transaction control. """ import sqlite3 con = sqlite3.connect("tutorial.db") # IMPLICITLY CREATES DB IF DOESN'T ALREADY EXIST. # In order to execute SQL statements and fetch results from SQL queries, we will need to use a database cursor. Call con.cursor() to create the Cursor: cur = con.cursor() # create a database table called "movie" with columns for title, release year, and review score. Thanks to the flexible typing feature of SQLite, specifying the data types is optional try: cur.execute("CREATE TABLE movie(title, year, score)") except: pass # verify that the new table has been created by querying the "sqlite_master" table built-in to SQLite, which should now contain an entry for the movie table definition res = cur.execute("SELECT name FROM sqlite_master") print(res.fetchone()) # fetch the resulting row. # look for a table that doesn't exist. res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'") print(res.fetchone()) # add 2 rows of data to the table # INSERT statement implicitly opens a transaction, which needs to be committed before changes are saved in the database cur.execute(""" INSERT INTO movie VALUES ('Monty Python and the Holy Grail', 1975, 8.2), ('And Now for Something Completely Different', 1971, 7.5) """) con.commit() # verify that the data was inserted correctly by executing a SELECT query. res = cur.execute("SELECT score FROM movie") print(res.fetchall() ) # fetch all rows. # insert three more rows by calling cur.executemany(...) data = [ ("Monty Python Live at the Hollywood Bowl", 1982, 7.9), ("Monty Python's The Meaning of Life", 1983, 7.5), ("Monty Python's Life of Brian", 1979, 8.0), ] cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data) con.commit() # Remember to commit the transaction after executing INSERT. # Notice that ? placeholders are used to bind data to the query. Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks (see How to use placeholders to bind values in SQL queries for more details). # We can verify that the new rows were inserted by executing a SELECT query, this time iterating over the results of the query: for row in cur.execute("SELECT year, title FROM movie ORDER BY year"): print(row) # Finally, verify that the database has been written to disk by calling con.close() to close the existing connection, opening a new one, creating a new cursor, then querying the database: con.close() new_con = sqlite3.connect("tutorial.db") new_cur = new_con.cursor() res = new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC") title, year = res.fetchone() print(f'The highest scoring Monty Python movie is {title!r}, released in {year}') new_con.close()
import { YouTrackIssue, YouTrackUser, YouTrackWorkItem } from '../types/YouTrackApi.types' export interface YouTrackApi { /** * ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ ัะฟะธัะพะบ ั€ะฐะฝะตะต ะทะฐะณั€ัƒะถะตะฝะฝั‹ั… ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะตะน */ get users(): YouTrackUser[] /** * ะžะฑะฝะพะฒะธั‚ัŒ ัะฟะธัะพะบ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะตะน */ fetchUsers(): Promise<void> /** * ะŸะพะปัƒั‡ะธั‚ัŒ ัะฟะธัะพะบ ะทะฐะดะฐั‡ */ get issues(): YouTrackIssue[] /** * ะžะฑะฝะพะฒะธั‚ัŒ ัะฟะธัะพะบ ะทะฐะดะฐั‡ */ fetchIssues(): Promise<void> /** * ะะฐะนั‚ะธ ะทะฐะดะฐั‡ะธ ะฟะพ ะฝะฐะทะฒะฐะฝะธัŽ ะฟั€ะพะตะบั‚ะฐ (ะฝัƒะถะฝะพ ะดะปั ะฐะฒั‚ะพะบะพะผะฟะปะธั‚ะฐ) * @param partialProjectName */ findIssuesByProject(partialProjectName: string): YouTrackIssue[] /** * ะžะฑะฝะพะฒะธั‚ัŒ ัะฟะธัะพะบ ะฒั€ะตะผะตะฝะฝั‹ั… ะทะฐะฟะธัะตะน */ fetchWorkItems(): Promise<void> /** * ะŸะพะปัƒั‡ะธั‚ัŒ ะฒั€ะตะผะตะฝะฝั‹ะต ะทะฐะฟะธัะธ ะฟะพ id ะทะฐะดะฐั‡ะธ * @param issueid */ getWorkitemsFromIssue(issueid: string): YouTrackWorkItem[] }
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <h1>Signup Form</h1> <form onsubmit="signup(); return false "> <label for="firstName">First Name</label> <input type="text" id="firstName" required> <br> <label for="lastName">Last Name</label> <input type="text" id="lastName" required> <br> <label for="email">Email</label> <input type="email" id="email" required> <br> <label for="password">Password</label> <input type="password" id="password" required> <br> <label for="repeatPassword">Repeat Password</label> <input type="password" id="repeatPassword" required> <br> <input type="submit" value="Signup"> </form> <p id="message"></p> <br> <br> <script> function signup() { var firstName = document.getElementById('firstName').value; var lastName = document.getElementById('lastName').value; var email = document.getElementById('email').value; var password = document.getElementById('password').value; var repeatPassword = document.getElementById('repeatPassword').value; if (password !== repeatPassword) { document.querySelector("#message").innerHTML = 'Passwords do not match, please try again'; return; } axios.post('https://signup-app2.herokuapp.com/signup', { firstName, lastName, email, password, }) .then(function (response) { console.log(response.data); document.querySelector("#message").innerHTML = response.data.message; }) .catch(function (error) { console.log(error.response.data); document.querySelector("#message").innerHTML = error.response.data.message; }); } </script> <!-- //1. UNIFORM RESOURSE: // GET /user/:userID to get single user // GET /users to get all users // POST /user to create single user // POST /users to create multiple user // PUT /user:userID to modify single user // PUT /users to modify multiple user // DELETE /user:userID to delete single user // DELETE /users to delete multipls user // GET /post/:postID to get single post // GET /posts to get all posts // POST /post to create single post // POST /posts to create multiple posts // PUT /post/:postID to modify single post // PUT /posts to modify multiple posts // DELETE /post/:postID to delete single post // DELETE /posts to delete multipls posts // GET /group/:groupID to get single group // GET /groups to get all groups // POST /group to create single group // POST /groups to create multiple groups // PUT /group/:groupID to modify single group // PUT /groups to modify multiple groups // DELETE /group/:postID to delete single group // DELETE /groups to delete multipls groups // don't use these // GET /get-user // POST /create-user // 2.CLIENT AND SERVER SHOULD BE SEPARATE // 3.STATE LESS // 4.CACHEABLE // 5.LAYERED SYSTEM --> </body> </html>
#pragma once #include <memory> #include <my_cpp_utils/json_formatter.h> #include <spdlog/sinks/daily_file_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> namespace utils { class Logger { private: inline static std::shared_ptr<spdlog::logger>& GetSingletoneInstance() { static std::shared_ptr<spdlog::logger> logger; return logger; } public: inline static void Init( const std::filesystem::path& logFilePath, spdlog::level::level_enum level = spdlog::level::level_enum::info) { auto& logger = GetSingletoneInstance(); if (logger) throw std::runtime_error("Logger is already initialized"); std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::stderr_color_sink_mt>()); sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_mt>(logFilePath.string(), 23, 59)); logger = std::make_shared<spdlog::logger>("global", begin(sinks), end(sinks)); logger->set_level(level); // Set the pattern // [%Y-%m-%d %H:%M:%S.%e] is the timestamp // [%l] is the log level // [%t] is the thread ID // %v is the actual log message logger->set_pattern("[%H:%M:%S.%e] [%l] [%t] %v"); } inline static spdlog::logger& GetInstance() { auto& logger = GetSingletoneInstance(); if (!logger) throw std::runtime_error("Logger is not initialized. Use Logger::init()"); return *logger; } }; } // namespace utils #define MY_LOG(severity, fmt_string, ...) \ utils::Logger::GetInstance().severity(fmt::format(fmt_string __VA_OPT__(, ) __VA_ARGS__)) #define MY_FMT(fmt_string, ...) fmt::format(fmt_string, __VA_ARGS__)
package john.LOGIN_SYSTEM.forgetpassword; import jakarta.servlet.http.HttpSession; import john.LOGIN_SYSTEM.common.components.PasswordStrength; import john.LOGIN_SYSTEM.common.components.VerificationCode; import john.LOGIN_SYSTEM.common.components.email.EmailService; import john.LOGIN_SYSTEM.common.components.email.TransactionType; import john.LOGIN_SYSTEM.common.response.ResponseLayer; import john.LOGIN_SYSTEM.common.response.ResponseTerminal; import john.LOGIN_SYSTEM.common.response.ResponseType; import john.LOGIN_SYSTEM.forgetpassword.token.CodeToken; import john.LOGIN_SYSTEM.forgetpassword.token.CodeTokenService; import john.LOGIN_SYSTEM.repository.entity.user.UserEntity; import john.LOGIN_SYSTEM.repository.entity.user.UserRepository; import john.LOGIN_SYSTEM.session.SessionService; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional; @Service class ForgetPasswordService { private final UserRepository userRepository; private final BCryptPasswordEncoder passwordEncoder; private final PasswordStrength passwordStrength; private final VerificationCode verification; private final EmailService emailService; private final ResponseTerminal terminal; private final SessionService redisSession; private final CodeTokenService tokenService; @Autowired public ForgetPasswordService(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder, PasswordStrength passwordStrength, VerificationCode verification, EmailService email, ResponseTerminal terminal, SessionService redisSession, CodeTokenService tokenService) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.passwordStrength = passwordStrength; this.verification = verification; this.emailService = email; this.terminal = terminal; this.redisSession = redisSession; this.tokenService = tokenService; } // VERIFY USER ACCOUNT IF EXIST // Check input formats // Check provided email if account exist // Proceed to next method for password match public ResponseLayer verifyAccountFirst(String email, HttpSession session) { var userEmail = userRepository.findByEmail(email); if (userEmail.isEmpty()) { return new ResponseLayer( false, "Invalid email", HttpStatus.NOT_FOUND); } if (!userEmail.get().isEnabled()) { return new ResponseLayer( false, "Account is locked", HttpStatus.BAD_REQUEST); } UserEntity user = userEmail.get(); CodeToken token = verificationCode(user); // send verification code via email emailService.sendEmail(user.getUsername(), user.getEmail(), token.getVerificationCode(), TransactionType.RESET_PASSWORD); // generate entry session for reset password int EXPIRATION_IN_MINUTES = 5; redisSession.setSession(session, "verification-code", token.getVerificationCode(), EXPIRATION_IN_MINUTES); redisSession.setSession(session, "user-id", user.getId().toString()); terminal.status(ResponseType.ACCOUNT_EXIST); return new ResponseLayer(true, "Account exist", HttpStatus.OK); } // Generate verification code private CodeToken verificationCode(UserEntity user) { CodeToken token = new CodeToken(user.getId()); verification.generateVerificationCode(token); return token; } // VERIFICATION PROCESS public ResponseLayer matchVerification(String userInput, HttpSession session) { String verificationCode = (String) redisSession.getSession(session, "verification-code"); CodeToken verification = tokenService.handleExpiration(verificationCode); // Expired. remove session attributes if (verification == null) { redisSession.removeSession(session, "verification-code"); redisSession.removeSession(session, "user-id"); return new ResponseLayer(false, "Verification code expired", HttpStatus.BAD_REQUEST); } // Invalid input if (!userInput.equals(verification.getVerificationCode())) { return new ResponseLayer(false, "Invalid verification code", HttpStatus.BAD_REQUEST); } tokenService.deleteVerificationCode(verification); return new ResponseLayer(true, "Verified. Proceed to change-password", HttpStatus.OK); } // VALIDATE USER INPUTS FIRST BEFORE RESET PASSWORD // Check password strength // Check password if same as previous // Save new password; Return false if SYSTEM error persist public ResponseLayer resetPassword(ObjectId userId, String newPassword) { // Password strength // Retrieve account from database var checkNewPassword = passwordStrength.checkPassword(newPassword); Optional <UserEntity> checkUser = userRepository.findById(userId); if (!checkNewPassword.isSuccess()) { return checkNewPassword; } else if (checkUser.isEmpty()) { return new ResponseLayer(false, "User not found", HttpStatus.NOT_FOUND); } // Instantiate user account into variable UserEntity user = checkUser.get(); // Return false if new password is same as the previous one if (passwordEncoder.matches(user.getSalt() + newPassword, user.getPassword())) { return new ResponseLayer( false, "Provided password is the same as previous", HttpStatus.BAD_REQUEST); } // Perform password hashing before saving String hashedPassword = passwordEncoder.encode(user.getSalt() + newPassword); // Update user password if (userRepository.updatePassword(user, hashedPassword).isPresent()) { return new ResponseLayer( true, "Password reset successfully", HttpStatus.OK); } else { return new ResponseLayer( false, "Password reset fail", HttpStatus.SERVICE_UNAVAILABLE); } } }
import { HelmetProvider } from 'react-helmet-async'; import { Routes, Route } from 'react-router-dom'; import HistoryRouter from '../history-route/history-route'; import browserHistory from '../../browser-history'; import ScrollToTop from '../scroll-to-top/scroll-to-top'; import Main from '../../pages/main/main'; import Login from '../../pages/login/login'; import Favorites from '../../pages/favorites/favorites'; import Offer from '../../pages/offer/offer'; import NotFound from '../../pages/not-found/not-found'; import PrivateRoute from '../private-route/private-route'; import { AppRoute } from '../../constants'; function App(): JSX.Element { return ( <HelmetProvider> <HistoryRouter history={browserHistory}> <ScrollToTop /> <Routes> <Route index element={<Main />} /> <Route path={AppRoute.Login} element={<Login />} /> <Route path={AppRoute.Favorites} element={ <PrivateRoute> <Favorites /> </PrivateRoute> } /> <Route path={AppRoute.Offer} element={<Offer />} /> <Route path="*" element={<NotFound />} /> </Routes> </HistoryRouter> </HelmetProvider> ); } export default App;
<script> import { writable } from 'svelte/store' import H2 from 'components/H2/H2.svelte' import Input from 'components/Input/Input.svelte' import ButtonBurgerShape from 'components/ButtonBurgerShape/ButtonBurgerShape.svelte' import RecipeCard from 'components/RecipeCard/RecipeCard.svelte' import { getRandomInt, getRandomNItems } from 'services/random.service' let recipes = [] let ingredient = '' let noRecipeFound = false const listOfTotalRecipes = writable([]) const inputIngredient = writable('') export const getRandomRecipes = n => { const randomPage = ingredient ? getRandomInt(10) : getRandomInt(50) const url = ingredient ? `api/puppy/?q=${ingredient}&p=${randomPage}` : `api/puppy/?p=${randomPage}` fetch(url) .then(res => res.json()) .then(data => { const listOfRecipes = data && data.results.length > 0 && getRandomNItems(data.results, n) noRecipeFound = !listOfRecipes listOfTotalRecipes.set(listOfRecipes) }) .catch(err => { throw Error(err) }) } listOfTotalRecipes.subscribe(value => { recipes = value }) const handleChange = event => { inputIngredient.set(event.target.value) } inputIngredient.subscribe(value => { ingredient = value }) </script> <style> .container { display: flex; flex-direction: row; width: 100%; } .group-container { display: flex; flex-direction: column; align-items: center; } .button-container { display: flex; flex-direction: row; } .global-container { display: flex; flex-direction: column; flex-wrap: wrap; justify-content: center; align-items: center; margin: 20px 0; } .not-found { margin: 10px; color: #EE6663; } </style> <div class="container"> <Input label={'Une envie de...'} onChange={handleChange}/> <div class="group-container"> <H2 title="...Combien voulez vous de propositions ?"/> <div class="button-container"> <ButtonBurgerShape className="with-marge" onClick={() => getRandomRecipes(1)} text="1"/> <ButtonBurgerShape className="with-marge" onClick={() => getRandomRecipes(5)} text="5"/> <ButtonBurgerShape onClick={() => getRandomRecipes(10)} text="10"/> </div> </div> </div> {#if recipes.length > 0} <div class="global-container"> {#each recipes as recipe} <RecipeCard title={recipe.title} href={recipe.href} ingredients={recipe.ingredients} src={recipe.thumbnail}/> {/each} </div> {/if} {#if noRecipeFound} <div class="not-found"> Dรฉsolรฉ, nous n&apos;avons trouvรฉ aucune recette qui correspond :&apos;( </div> {/if}
package com.ntumart.dipapp.api.controllers; import com.ntumart.dipapp.api.repository.InterestRepository; import com.ntumart.dipapp.api.service.InterestService; import com.ntumart.dipapp.exceptions.EmptyFileException; import com.ntumart.dipapp.exceptions.ProductNotFoundException; import com.ntumart.dipapp.models.Interest; import java.io.IOException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/v1/user") public class InterestController { @Autowired InterestService interestService; @Autowired InterestRepository interestRepository; @RequestMapping( value = "/addinterest", method = RequestMethod.POST, produces = {"application/json"}) @ResponseBody public ResponseEntity<String> addInterest(@RequestBody Interest interest) { try { interestService.addInterest(interest); System.out.println("Received Interest object: " + interest); return ResponseEntity.ok("Interest Added Successfully"); } catch (EmptyFileException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File is empty"); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Error uploading the file"); } } @GetMapping("/interest/{userID}") public ResponseEntity<List<Object>> userID(@PathVariable int userID) throws ProductNotFoundException { List<Object> interest = interestRepository.userID(userID); if (interest == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(interest); } @GetMapping("/{userID}/checkInterest") public ResponseEntity<String> checkCategory(@PathVariable int userID) { Interest interest = interestRepository.checkCategory(userID); if (interest == null) { return ResponseEntity.notFound().build(); } if (interest.getCategory1() == null || interest.getCategory1().isEmpty()) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Categories is empty"); } else { // } else if(interest.getCategory2() == null || interest.getCategory2().isEmpty()){ // return ResponseEntity.ok("4 Categories is not selected"); // } else if(interest.getCategory3() == null || interest.getCategory3().isEmpty()){ // return ResponseEntity.ok("3 Categories is not selected"); // } else if(interest.getCategory4() == null || interest.getCategory4().isEmpty()){ // return ResponseEntity.ok("2 Categories is not selected"); // } else if(interest.getCategory5() == null || interest.getCategory5().isEmpty()){ // return ResponseEntity.ok("1 Categories is not selected"); // } else { return ResponseEntity.status(HttpStatus.FOUND).body("No issue"); } } @GetMapping("/checking/{userID}") public ResponseEntity<Interest> getInterestByUserID(@PathVariable int userID) throws ProductNotFoundException { Interest interest = interestService.getInterestByUserID(userID); return ResponseEntity.ok(interest); } @PostMapping("/updateInterest/{userID}") public ResponseEntity<String> updateInterest( @PathVariable int userID, @RequestParam(value = "category1") String category1, @RequestParam(value = "category2") String category2, @RequestParam(value = "category3") String category3, @RequestParam(value = "category4") String category4, @RequestParam(value = "category5") String category5) throws IOException, ProductNotFoundException { interestService.updateInterest(userID, category1, category2, category3, category4, category5); return ResponseEntity.ok("Interest Updated Successfully"); } }
/** * The starting point of the application. * * @author Eric Sundqvist * @author Mats Loock * @version 1.0.0 */ import express from 'express' import helmet from 'helmet' import logger from 'morgan' import { router } from './routes/router.js' import { connectDB } from './config/mongoose.js' try { await connectDB() const app = express() // Set various HTTP headers to make the application little more secure (https://www.npmjs.com/package/helmet). app.use(helmet()) // Set up a morgan logger using the dev format for log entries. app.use(logger('dev')) // Parse requests of the content type application/json. app.use(express.json()) // Register routes. app.use('/', router) // Error handler. app.use(function (err, req, res, next) { err.status = err.status || 500 if (req.app.get('env') !== 'development') { console.log(err) if (err.status === 409) { return res.status(err.status).send() } else { if (err.status === 500) err.message = 'An unexpected condition was encountered.' if (err.status === 400) { err.message = 'The request cannot or will not be processed due to something that is perceived to be a client error (for example, validation error).' } return res.status(err.status).json({ status: err.status, message: err.message }) } } // Development only! // Only providing detailed error in development. return res.status(err.status).json({ status: err.status, message: err.message, cause: err.cause ? { status: err.cause.status, message: err.cause.message, stack: err.cause.stack } : null, stack: err.stack }) }) // Starts the HTTP server listening for connections. app.listen(process.env.PORT, () => { console.log(`Server running at http://localhost:${process.env.PORT}`) console.log('Press Ctrl-C to terminate...') }) } catch (err) { console.error(err) process.exitCode = 1 }
import { useState } from 'react'; import { useDispatch } from 'react-redux'; import * as productActions from '../actions/productsActions'; const AddProductForm = () => { const [visible, setVisible] = useState(false); const [name, setName] = useState(''); const [price, setPrice] = useState(0); const [quantity, setQuantity] = useState(0); const dispatch = useDispatch(); const resetForm = () => { setName(''); setPrice(0); setQuantity(0); setVisible(!visible); }; const handleClick = (e) => { e.preventDefault(); resetForm(); }; const onFormSubmit = async (product) => { dispatch(productActions.productAdded(product, resetForm)); }; const handleFormSubmit = (e) => { try { e.preventDefault(); onFormSubmit({ title: name, price, quantity }); } catch (err) { console.error(err); } }; const formVisible = visible ? 'add-form visible' : 'add-form'; return ( <div className={formVisible}> <p> <a className="button add-product-button" href="#/" onClick={handleClick} > Add A Product </a> </p> <> <h3>Add Product</h3> <form onSubmit={handleFormSubmit}> <div className="input-group"> <label htmlFor="product-name">Product Name</label> <input type="text" id="product-name" value={name} onChange={({ target }) => setName(target.value)} /> </div> <div className="input-group"> <label htmlFor="product-price">Price</label> <input type="text" id="product-price" value={price} onChange={({ target }) => setPrice(target.value)} /> </div> <div className="input-group"> <label htmlFor="product-quantity">Quantity</label> <input type="text" id="product-quantity" value={quantity} onChange={({ target }) => setQuantity(target.value)} /> </div> <div className="actions form-actions"> <a href="#/" type="submit" className="button" onClick={handleFormSubmit} > Add </a> <a href="#/" className="button" onClick={handleClick}> Cancel </a> </div> </form> </> </div> ); }; export default AddProductForm;
# IOTA - Em uma declaraรงรฃo de constantes, o identificador IOTA representa nรบmeros sequenciais nรฃo tipados. ```GO package main import "fmt" const ( x = iota y = iota z = iota ) func main() { fmt.Println(x, y, z) } OUTPUT: 0, 1, 2 ``` - Podemos descartar valores ````GO package main import "fmt" const ( a = iota _ = iota c = iota x = iota _ = iota z = iota ) func main() { fmt.Println(a, c, x, z) } OUTPUT: 0, 2, 3, 5 package main import "fmt" const ( a = iota * 10 _ c x _ z ) func main() { fmt.Println(a, c, x, z) } OUTPUT: 0, 20, 30, 50 ````
"use server"; import { RegisterSchema } from "@/schemas/registerSchema"; import * as z from "zod"; import bcrypt from "bcryptjs"; import { db } from "@/lib/db"; import { getUserbyEmail } from "@/data/auth/user"; export const register = async (values:z.infer<typeof RegisterSchema>) => { const validatedFields = RegisterSchema.safeParse(values); if(!validatedFields.success) { return {error: "Invalid Fields!"}; } const {email, password, name} = validatedFields.data; const hashedPassword = await bcrypt.hash(password, 10); const existingUser = await getUserbyEmail(email); if(existingUser) { return {error: "Email already in use!"}; } await db.user.create({ data:{ name, email, password: hashedPassword, } }); return {success: "Account created!"}; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../34_ERC721_en/IERC165.sol"; /** * @dev ERC1155 standard interface contract, realizes the function of EIP1155 * See: https://eips.ethereum.org/EIPS/eip-1155[EIP]. */ interface IERC1155 is IERC165 { /** * @dev single-type token transfer event * Released when `value` tokens of type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** * @dev multi-type token transfer event * ids and values are arrays of token types and quantities transferred */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev volume authorization event * Released when `account` authorizes all tokens to `operator` */ event ApprovalForAll( address indexed account, address indexed operator, bool approved ); /** * @dev Released when the URI of the token of type `id` changes, `value` is the new URI */ event URI(string value, uint256 indexed id); /** * @dev Balance inquiry, returns the position of the token of `id` type owned by `account` */ function balanceOf( address account, uint256 id ) external view returns (uint256); /** * @dev Batch balance inquiry, the length of `accounts` and `ids` arrays have to wait. */ function balanceOfBatch( address[] calldata accounts, uint256[] calldata ids ) external view returns (uint256[] memory); /** * @dev Batch authorization, authorize the caller's tokens to the `operator` address. * Release the {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Batch authorization query function, if the authorization address `operator` is authorized by `account`, return `true` * See {setApprovalForAll} function. */ function isApprovedForAll( address account, address operator ) external view returns (bool); /** * @dev Secure transfer, transfer `amount` unit `id` type token from `from` to `to`. * Release {TransferSingle} event. * Require: * - If the caller is not a `from` address but an authorized address, it needs to be authorized by `from` * - `from` address must have enough open positions * - If the receiver is a contract, it needs to implement the `onERC1155Received` method of `IERC1155Receiver` and return the corresponding value */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev Batch security transfer * Release {TransferBatch} event * Require: * - `ids` and `amounts` are of equal length * - If the receiver is a contract, it needs to implement the `onERC1155BatchReceived` method of `IERC1155Receiver` and return the corresponding value */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; }
ๅ‘้€š้“ไธญๅŠ ๅ…ฅไธ€ไธช็ป„็ป‡ ----------- > ๅŽŸๆ–‡้“พๆŽฅ๏ผšhttps://hyperledger-fabric.readthedocs.io/en/latest/channel_update_tutorial.html > ๆ็คบ๏ผš็กฎไฟๆ‚จๅทฒๆŒ‰็…ง Install Samples, Binaries and Docker Images ๅ’Œ ย Prerequisites ๆ–‡็ซ ๆ‰€่ฟฐไธ‹่ฝฝไบ†็›ธๅบ”็š„ docker ้•œๅƒๅ’ŒไบŒ่ฟ›ๅˆถๆ–‡ไปถใ€‚็‰นๅˆซๆ˜ฏ๏ผŒๆ‚จ็š„ fabric-samples ๆ–‡ไปถๅคน็‰ˆๆœฌๅฟ…้กปๅŒ…ๅซ eyfn.sh ่„šๆœฌ(first-network ๆ–‡ไปถๅคนไธญ)ๅŠๅ…ถ็›ธๅ…ณ่„šๆœฌใ€‚ ๆœฌ็ฏ‡ๆ•™็จ‹ๆ˜ฏๆž„ๅปบ็ฌฌไธ€ไธช fabric ็ฝ‘็ปœๆ•™็จ‹็š„ๆ‰ฉๅฑ•๏ผŒๅนถๆผ”็คบๅ‘ BYFN ็ฝ‘็ปœไธญ่‡ชๅŠจ็”Ÿๆˆ็š„ๅบ”็”จ้ข‘้“๏ผˆmychannel๏ผ‰ไธญๆทปๅŠ ๆ–ฐ็ป„็ป‡-- Org3ใ€‚่ฟ™้‡Œๅฐฑๅ‡่ฎพๆ‚จๅฏน BYFN ็ฝ‘็ปœ๏ผŒๅŒ…ๆ‹ฌไธŠ่ฟฐๅฎž็”จ็จ‹ๅบ็š„็”จๆณ•ๅ’ŒๅŠŸ่ƒฝ้ƒฝๅทฒ็ปๅๅˆ†ไบ†่งฃใ€‚ > ่ฏ‘่€…ๆณจ๏ผšBYFN ็ฝ‘็ปœ๏ผŒๅณ ๆž„ๅปบ็ฌฌไธ€ไธช fabric ็ฝ‘็ปœ ๆ•™็จ‹ๅปบ็ซ‹็š„ Fabric ็ฝ‘็ปœใ€‚BYFN ไธบ build your first networkย  ็š„็ผฉๅ†™ใ€‚ ่™ฝ็„ถ่ฟ™้‡Œๆˆ‘ไปฌๅชๅ…ณๆณจๆ–ฐ็ป„็ป‡็š„้›†ๆˆ๏ผŒไฝ†ๅœจๆ‰ง่กŒๅ…ถไป–้€š้“้…็ฝฎๆ›ดๆ–ฐๆ—ถ๏ผŒไพ‹ๅฆ‚ๆ›ดๆ–ฐไฟฎๆ”น็ญ–็•ฅ(modification policies )ๆˆ–ๆ›ดๆ”นๆ‰น้‡ๅคงๅฐ(altering batch size)๏ผŒไนŸๅฏไปฅ้‡‡็”จ็›ธๅŒ็š„ๆ–นๆณ•ใ€‚ๅฆ‚ๆžœๆƒณ่ฆไบ†่งฃๆœ‰ๅ…ณ้€š้“้…็ฝฎๆ›ดๆ–ฐ็š„่ฟ‡็จ‹ๅ’Œๅฏ่ƒฝๆ€ง็š„ๆ›ดๅคšๅ†…ๅฎน๏ผŒ่ฏทๆŸฅ็œ‹ๆ›ดๆ–ฐ้€š้“้…็ฝฎ ่ฟ™็ฏ‡ๆ–‡็ซ ใ€‚่ฟ˜ๆœ‰ไธ€ไธช่ฆๆณจๆ„็š„็‚นๆ˜ฏ๏ผŒ่ฟ™้‡Œๆผ”็คบ็š„้ข‘้“้…็ฝฎๆ›ดๆ–ฐ้€šๅธธๆ˜ฏ็ป„็ป‡็ฎก็†ๅ‘˜๏ผˆ่€Œไธๆ˜ฏ้“พ็ ๆˆ–ๅบ”็”จ็จ‹ๅบๅผ€ๅ‘ไบบๅ‘˜๏ผ‰็š„่ดฃไปปใ€‚ > ๆ็คบ๏ผšๅœจ็ปง็ปญไธ‹้ขๅ†…ๅฎนไน‹ๅ‰๏ผŒ่ฏท็กฎไฟ่‡ชๅŠจๅŒ– byfn.sh ่„šๆœฌๅœจๆ‚จ็š„่ฎก็ฎ—ๆœบไธŠ่ฟ่กŒๆ—ถๆฒกๆœ‰้”™่ฏฏใ€‚ๅฆ‚ๆžœไฝ ๅฐ†ไบŒ่ฟ›ๅˆถๆ–‡ไปถๅ’Œ็›ธๅ…ณๅทฅๅ…ท๏ผˆcryptogen๏ผŒconfigtxgen ็ญ‰๏ผ‰ๅฏผๅ‡บๅˆฐ PATH ๅ˜้‡ไธญ๏ผŒๅฏไปฅ็›ธๅบ”ๅœฐไฟฎๆ”นๅ‘ฝไปค่€Œไธ็”จไผ ้€’ๅฎŒๅ…จ้™ๅฎš็š„่ทฏๅพ„ใ€‚ # ๅฏๅŠจ็Žฏๅขƒ ๆˆ‘ไปฌๅฐ†ๅœจๆ‚จ็š„ๆœฌๅœฐๅ…‹้š†็š„ Fabric-samples ไธญ็š„ๅญ็›ฎๅฝ• first-network ไธ‹่ฟ›่กŒๆ“ไฝœ๏ผŒๅฟซๅŽปๅˆ‡ๆขๅˆฐ่ฏฅ็›ฎๅฝ•ๅงใ€‚ๅฆๅค–๏ผŒๅ†ๆ‰“ๅผ€ไธ€ไบ›้ขๅค–็š„็ปˆ็ซฏไปฅๆ–นไพฟไฝฟ็”จใ€‚ ้ฆ–ๅ…ˆ๏ผŒไฝฟ็”จ byfn.sh ่„šๆœฌๆฅๆธ…็†ไธ‹็Žฏๅขƒใ€‚่ฟ™ไธชๅ‘ฝไปคๅฐ†็ปˆๆญขๆ‰€ๆœ‰ๆดปๅŠจๆˆ–่ฟ‡ๆ—ถ็š„ docker ๅฎนๅ™จๅนถๅˆ ้™คไปฅๅ‰็”Ÿๆˆ็š„ๆ–‡ไปถใ€‚ๅ…ถๅฎžๆ‰ง่กŒ้€š้“้…็ฝฎๆ›ดๆ–ฐไปปๅŠก๏ผŒๆ˜ฏๆ— ้œ€ๅ…ณ้—ญ Fabric ็ฝ‘็ปœ็š„๏ผŒไฝ†ๆ˜ฏไธบไบ†ๆœฌๆ•™็จ‹ๆ‰ง่กŒ็š„้กบๅˆฉ๏ผŒๆˆ‘ไปฌไปŽๅˆๅง‹็Šถๆ€่ฟ›่กŒๆ“ไฝœใ€‚ๅ› ๆญค๏ผŒ่ฎฉๆˆ‘ไปฌ่ฟ่กŒไปฅไธ‹ๅ‘ฝไปคๆฅๆธ…็†ไปฅๅ‰็š„ๆ‰€ๆœ‰็Žฏๅขƒ๏ผš ```bash ./byfn.sh down ``` ๆŽฅไธ‹ๆฅ๏ผŒ็”Ÿๆˆ BYFN ็ฝ‘็ปœ้ป˜่ฎค้œ€่ฆ็š„ๆ–‡ไปถ๏ผš ```bash ./byfn.sh generate ``` ๆœ€ๅŽ๏ผŒไฝฟ็”จๅœจ CLI ๅฎนๅ™จไธญ็š„ๆ‰ง่กŒ็š„่„šๆœฌๅฏๅŠจ็ฝ‘็ปœ๏ผš ```bash ./byfn.sh up ``` ็Žฐๅœจ๏ผŒไฝ ็š„ๆœบๅ™จไธŠ่ฟ่กŒไบ†ไธ€ไธชๅนฒๅ‡€็š„ BYFNใ€‚ๆŽฅไธ‹ๆฅ๏ผŒๆ‚จๆœ‰ไธคๆก่ทฏๅฏไปฅ่ตฐใ€‚้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌๆไพ›ไธ€ไธชๅฎŒๅ…จๆณจ้‡Š็š„่„šๆœฌ๏ผŒๅฎƒๅฐ†ๆ‰ง่กŒ้…็ฝฎไบคๆ˜“ๆ›ดๆ–ฐไปฅๅฐ† Org3 ๅŠ ๅ…ฅ็ฝ‘็ปœใ€‚ๆญคๅค–๏ผŒๆˆ‘ไปฌๅฐ†ๅฑ•็คบไธ€ไธช็›ธๅŒ่ฟ‡็จ‹็š„โ€œๆ‰‹ๅŠจโ€็‰ˆๆœฌ๏ผŒๅฑ•็คบๆฏไธชๆญฅ้ชค๏ผŒๅนถ่งฃ้‡ŠๅฎƒๅฎŒๆˆ็š„ๅ†…ๅฎนใ€‚๏ผˆๅ› ไธบๆˆ‘ไปฌๅœจๆ‰‹ๅŠจๆ‰ง่กŒไน‹ๅ‰๏ผŒ่ฟ˜ไผšๅ‘ๆ‚จๅฑ•็คบๅฆ‚ไฝ•ๅ…ณ้—ญ็ฝ‘็ปœ๏ผŒๆ‰€ไปฅๆ‚จไนŸๅฏไปฅๅ…ˆ่ฟ่กŒ่‡ชๅŠจ่„šๆœฌ๏ผŒ็„ถๅŽๅ†ๆ‰‹ๅŠจ่ฟ่กŒๆฏไธชๆญฅ้ชค๏ผ‰ # ไฝฟ็”จ่„šๆœฌๅฐ† Org3 ๅŠ ๅ…ฅ Channel ๅœจ first-network ็›ฎๅฝ•ไธ‹ ๆ‰ง่กŒไปฅไธ‹ๅ‘ฝไปค๏ผš ```bash ./eyfn.sh up ``` ็œ‹ไธ€็œ‹่พ“ๅ‡บๅฎนใ€‚ๅฐ†็œ‹ๅˆฐๆทปๅŠ ไบ† Org3 ๅŠ ๅฏ†่ต„ๆ–™๏ผŒๅˆ›ๅปบ้…็ฝฎๆ›ดๆ–ฐๅนถๅฏนๅ…ถ็ญพๅ๏ผŒ็„ถๅŽๅฎ‰่ฃ…ไบ†้“พ็ ไปฅไพฟๅ…่ฎธ Org3 ๆ‰ง่กŒๅธๆœฌๆŸฅ่ฏขใ€‚ ๅฆ‚ๆžœไธ€ๅˆ‡้กบๅˆฉ๏ผŒๆœ€็ปˆไฝ ๅฐ†็œ‹ๅˆฐไปฅไธ‹ไฟกๆฏ๏ผš ```text ``` ้€š่ฟ‡ๆ‰ง่กŒไปฅไธ‹ๅ‘ฝไปค๏ผˆ่€Œไธๆ˜ฏ./byfn.sh up๏ผ‰๏ผŒeyfn.sh ๅฏไปฅไธŽ byfn.sh ไฝฟ็”จ็›ธๅŒ็š„ Node.js ้“พ็ ๅ’Œๆ•ฐๆฎๅบ“้€‰้กน๏ผš ```bash ./byfn.sh up -c testchannel -s couchdb -l node ``` ```bash ./eyfn.sh up -c testchannel -s couchdb -l node ``` ๅฆ‚ๆžœๆƒณ่ฆไป”็ป†็ ”็ฉถ่ฟ™ไธช่ฟ‡็จ‹๏ผŒๅฐฑ็œ‹็œ‹ๆŽฅไธ‹ๆฅ้ƒจๅˆ†๏ผŒๅฐ†ๅ‘ๅฑ•็คบ่ฟ›่กŒ้€š้“ๆ›ดๆ–ฐ็š„ๆฏไธชๅ‘ฝไปคไปฅๅŠๅฎƒ็š„ไฝœ็”จใ€‚ # ๆ‰‹ๅŠจๅฐ† Org3 ๅŠ ๅ…ฅ้€š้“ > ๆ็คบ๏ผšไธ‹้ข็š„ๆญฅ้ชคๆ˜ฏๆŠŠ cli ๅ’Œ Org3cli ๅฎนๅ™จไธญ็š„ CORE_LOGGING_LEVEL ่ฎพ็ฝฎไธบ DEBUGใ€‚ > > cli ๅฎนๅ™จ ๅœจ first-network/docker-compose-cli.yaml ไธญ๏ผŒไฟฎๆ”นไปฃ็ ๅฆ‚ไธ‹๏ผš > > ```yaml > cli: > container_name: cli > image: hyperledger/fabric-tools:$IMAGE_TAG > tty: true > stdin_open: true > environment: > - GOPATH=/opt/gopath > - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock > #- CORE_LOGGING_LEVEL=INFO > - CORE_LOGGING_LEVEL=DEBUG > ``` > > Org3cli ๅฎนๅ™จ ๅœจ first-network/docker-compose-cli.yaml ไธญ๏ผŒไฟฎๆ”นไปฃ็ ๅฆ‚ไธ‹๏ผš > > ```yaml > Org3cli: > container_name: Org3cli > image: hyperledger/fabric-tools:$IMAGE_TAG > tty: true > stdin_open: true > environment: > - GOPATH=/opt/gopath > - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock > #- CORE_LOGGING_LEVEL=INFO > - CORE_LOGGING_LEVEL=DEBUG > ``` ๅฆ‚ๆžœๆ‚จไฝฟ็”จ่ฟ‡ eyfn.sh ่„šๆœฌ๏ผŒๅˆ™้œ€่ฆๅ…ณ้—ญ็ฝ‘็ปœใ€‚ๆ‰ง่กŒไธ‹้ขๅ‘ฝไปค๏ผš ```bash ./eyfn.sh down ``` ่ฟ™ๅฐ†ๅ…ณ้—ญ็ฝ‘็ปœ๏ผŒๅˆ ้™คๆ‰€ๆœ‰ๅฎนๅ™จๅนถๆ’คๆถˆๆˆ‘ไปฌไธบๆทปๅŠ  Org3 ๆ‰€ๅš็š„ๅทฅไฝœใ€‚ ็ฝ‘็ปœๅ…ณ้—ญๅŽ๏ผŒๆŽฅไธ‹ๆฅ้‡ๅฏ็ฝ‘็ปœ๏ผš ```bash ./byfn.sh generate ``` ๆŽฅ็€ๆ‰ง่กŒ๏ผš ```bash ./byfn.sh up ``` ่ฟ™ๅฐ†ไฝฟๆ‚จ็š„็ฝ‘็ปœๆขๅคๅˆฐๆ‰ง่กŒ eyfn.sh ่„šๆœฌไน‹ๅ‰็š„็Šถๆ€ใ€‚ ็Žฐๅœจๆˆ‘ไปฌๅ‡†ๅค‡ๆ‰‹ๅŠจๆทปๅŠ  Org3 ไบ†ใ€‚้ฆ–ๅ…ˆ๏ผŒ็ฌฌไธ€ๆญฅ๏ผŒๆˆ‘ไปฌ้œ€่ฆ็”Ÿๆˆ Org3 ็š„ๅŠ ๅฏ†่ต„ๆ–™ใ€‚ ## ็”Ÿๆˆ Org3 ๅŠ ๅฏ†่ต„ๆ–™ ๅœจๅฆไธ€ไธช็ปˆ็ซฏไธญ๏ผŒไปŽ first-network ๅˆ‡ๆขๅˆฐ org3-artifacts ็›ฎๅฝ•ไธญ: ```bash cd org3-artifacts ``` ่ฟ™้‡Œๆœ‰ไธคไธช yaml ๆ–‡ไปถ๏ผšorg3-crypto.yaml ๅ’Œ configtx.yamlใ€‚้ฆ–ๅ…ˆ๏ผŒไธบ Org3 ็”ŸๆˆๅŠ ๅฏ†ๆๆ–™๏ผš ```bash ../../bin/cryptogen generate --config=./org3-crypto.yaml ``` ๆญคๅ‘ฝไปคไผš่ฏป่ฏปๅ– org3-crypto.yaml ๆ–‡ไปถ๏ผŒ ๅนถๅˆฉ็”จ cryptogen ไธบ Org3 CA ไปฅๅŠ็ป‘ๅฎšๅˆฐๆญค็ป„็ป‡็š„ไธคไธช่Š‚็‚น็”Ÿๆˆๅฏ†้’ฅๅ’Œ่ฏไนฆใ€‚ไธŽ BYFN ๅฎž็Žฐไธ€ๆ ท๏ผŒ่ฟ™ไบ›ๅŠ ๅฏ†่ต„ๆ–™ๅฐ†ๆ”พๅ…ฅๅฝ“ๅ‰ๅทฅไฝœ็›ฎๅฝ•๏ผˆๅœจๆˆ‘ไปฌ็š„็คบไพ‹ไธญไธบ org3-artifacts๏ผ‰ๆ–ฐ็”Ÿๆˆ็š„ crypto-config ๆ–‡ไปถๅคนไธญใ€‚ ็Žฐๅœจไฝฟ็”จ configtxgen ๅทฅๅ…ท๏ผŒๆŠŠ Org3 ็š„้…็ฝฎไฟกๆฏ่พ“ๅ‡บๅˆฐ JSON ๆ–‡ไปถไธญใ€‚ๅฝ“็„ถ๏ผŒๆˆ‘ไปฌๅ…ˆ่ฆ่ฎพ็ฝฎ configtxgen ๅ‘ฝไปค้œ€่ฆๆๅ–้…็ฝฎๆ–‡ไปถ configtx.yaml ็š„ๅทฅไฝœ็›ฎๅฝ•ใ€‚ ```bash export FABRIC_CFG_PATH=$PWD ../../bin/configtxgen -printOrg Org3MSP > ../channel-artifacts/org3.json ``` ไธŠ้ข็š„ๅ‘ฝไปคๅˆ›ๅปบไธ€ไธช JSON ๆ–‡ไปถ - org3.json - ๅนถๅฐ†ๅ…ถ่พ“ๅ‡บๅˆฐ first-network ็›ฎๅฝ•ไธ‹็š„ channel-artifacts ไธญใ€‚ๆญคๆ–‡ไปถๅŒ…ๅซ Org3 ็š„็ญ–็•ฅๅฎšไน‰๏ผŒไปฅๅŠไปฅ base 64 ๆ ผๅผ็š„ไธ‰ไธช้‡่ฆ่ฏไนฆ๏ผš็ฎก็†ๅ‘˜็”จๆˆท่ฏไนฆ๏ผˆ็จๅŽๅฐ†้œ€่ฆๆ‹…ไปป Org3 ็š„็ฎก็†ๅ‘˜๏ผ‰๏ผŒCA ๆ น่ฏไนฆๅ’Œ TLS ๆ น่ฏไนฆใ€‚ๅœจๆŽฅไธ‹ๆฅ็š„ๆญฅ้ชคไธญ๏ผŒๆˆ‘ไปฌไผšๅฐ†ๆญค JSON ๆ–‡ไปถ่ฟฝๅŠ ๅˆฐ้€š้“้…็ฝฎไธญใ€‚ ๆˆ‘ไปฌๆœ€ๅŽ็š„ๅทฅไฝœๆ˜ฏๅฐ† Orderer Org ็š„ MSP ๆๆ–™็งปๆคๅˆฐ Org3 crypto-config ็›ฎๅฝ•ไธญใ€‚็‰นๅˆซๆ˜ฏ Orderer ็š„ TLS ๆ น่ฏไนฆ๏ผŒๅฎƒๅฐ†ๅ…่ฎธ Org3 ๅฎžไฝ“ไธŽ orderer ็ฝ‘็ปœ่Š‚็‚นไน‹้—ด็š„ๅฎ‰ๅ…จ้€šไฟกใ€‚ ```bash cd ../ && cp -r crypto-config/ordererOrganizations org3-artifacts/crypto-config/ ``` ็Žฐๅœจๆˆ‘ไปฌๅ‡†ๅค‡ๅฅฝๆ›ดๆ–ฐ้ข‘้“้…็ฝฎใ€‚ ## ๅ‡†ๅค‡ CLI ็Žฏๅขƒ ๆ›ดๆ–ฐ่ฟ‡็จ‹่ฆไฝฟ็”จ้…็ฝฎ่ฝฌๆขๅ™จๅทฅๅ…ท - configtxlatorใ€‚ๆญคๅทฅๅ…ทๆไพ›ไบ†๏ผš็‹ฌ็ซ‹ไบŽ SDK ็š„ๆ— ็Šถๆ€ REST API๏ผ›ๆไพ› CLI ๅ‘ฝไปค๏ผŒไปฅ็ฎ€ๅŒ– Fabric ็ฝ‘็ปœไธญ็š„้…็ฝฎไปปๅŠก๏ผ›ๅ…่ฎธๆ•ฐๆฎๅœจไธๅŒ็š„ๆ ผๅผไน‹้—ด่ฝปๆพ่ฝฌๆข๏ผˆๅœจๆœฌไพ‹ไธญ๏ผŒๅฆ‚ protobufs ๅ’Œ JSON ไน‹้—ด๏ผ‰๏ผ›ๅฏไปฅๆ นๆฎไธคไธช้€š้“้…็ฝฎไน‹้—ด็š„ๅทฎๅผ‚่ฎก็ฎ—้…็ฝฎๆ›ดๆ–ฐไบ‹ๅŠกใ€‚ ้ฆ–ๅ…ˆ๏ผŒๆ‰ง่กŒ่ฟ›ๅ…ฅ CLI ๅฎนๅ™จใ€‚ไน‹ๅ‰๏ผŒ่ฟ™ไธช CLI ๅฎนๅ™จๅทฒ็ปไฝฟ็”จ BYFN ็š„ crypto-config ้…็ฝฎๆ–‡ไปถๅฏๅŠจไบ†๏ผŒๆˆ‘ไปฌๅฏไปฅ่ฎฟ้—ฎไธคไธชๅŽŸๅง‹่Š‚็‚น็ป„็ป‡ๅ’Œ Orderer ็ป„็ป‡็š„ MSP ่ต„ๆ–™ใ€‚็”ฑไบŽๅผ•ๅฏผ็จ‹ๅบ็š„่บซไปฝๆ˜ฏ Org1 ็š„็ฎก็†ๅ‘˜็”จๆˆท๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆƒณ่ฆไปฅ Org2 ็š„่บซไปฝๆ‰ง่กŒไปปไฝ•ๆญฅ้ชค้ƒฝ้œ€่ฆ่ฎพ็ฝฎ็‰นๅฎš็š„ MSP ็Žฏๅขƒๅ˜้‡ใ€‚ ```bash docker exec -it cli bash ``` ่ฎพ็ฝฎ ORDERER_CA ๅ’Œ CHANNEL_NAME ๅ˜้‡๏ผš ```bash export ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem export CHANNEL_NAME=mychannel ``` ๆฃ€ๆŸฅไธ‹ๅ˜้‡ๆ˜ฏๅฆ่ฎพ็ฝฎๆญฃ็กฎ ```bash echo $ORDERER_CA && echo $CHANNEL_NAME ``` > ๆ็คบ๏ผšๅฆ‚ๆžœๅ› ไธบๆŸไบ›ๅŽŸๅ› ๏ผŒ่ฆ้‡ๅฏ CLI ๅฎนๅ™จ๏ผŒ้‚ฃๅœจ้‡ๅฏๅŽๅฐฑ้œ€่ฆ้‡ๆ–ฐ่ฎพ็ฝฎ่ฟ™ไธคไธช็Žฏๅขƒๅ˜้‡ใ€‚ ## ่Žทๅ–้…็ฝฎ ่ฟ™ไธช CLI ๅฎนๅ™จไธญๅทฒ็ป่ฎพๅฅฝไบ†ไธคไธชๅ…ณ้”ฎ็š„็Žฏๅขƒๅ˜้‡๏ผšORDERER_CA ๅ’Œ CHANNEL_NAMEใ€‚็Žฐๅœจๆˆ‘ไปฌๆฅ่Žทๅ– mychannel ้€š้“ๆœ€ๆ–ฐ็š„้…็ฝฎๅ—ใ€‚ ไธบไป€ไนˆ้œ€่ฆ่Žทๅ–ๆœ€ๆ–ฐ็š„้€š้“้…็ฝฎ๏ผŸ่ฟ™ๆ˜ฏๅ› ไธบ ้€š้“้…็ฝฎๅ…ƒ็ด ๆ˜ฏ็‰ˆๆœฌๅŒ–็š„ใ€‚็‰ˆๆœฌ้žๅธธ้‡่ฆ๏ผŒไธ€ๆ–น้ข๏ผŒๅฎƒๅฏไปฅ้˜ฒๆญข้…็ฝฎ็š„้‡ๅคๆ›ดๆ”น๏ผˆไพ‹ๅฆ‚๏ผŒๆขๅคๅˆฐๅ…ทๆœ‰ๆ—ง CRLs ็š„้€š้“้…็ฝฎ๏ผŒ่ฟ™ๅฐฑๅฏ่ƒฝไผšๅธฆๆฅๅฎ‰ๅ…จ้ฃŽ้™ฉ๏ผ‰ใ€‚ๅฆไธ€ๆ–น้ข๏ผŒๅฎƒๅฏไปฅไฟ่ฏๅนถๅ‘๏ผˆไพ‹ๅฆ‚๏ผŒๅœจๆทปๅŠ ๆ–ฐ็ป„็ป‡ๅŽไฝ ่ฆไปŽ้€š้“ไธญๅˆ ้™ค็ป„็ป‡๏ผŒ็‰ˆๆœฌๆŽงๅˆถๅฐฑๅฏไปฅ้˜ฒๆญขๅˆ ้™คไธคไธช็ป„็ป‡๏ผŒๅชๅˆ ้™คๆƒณ่ฆๅˆ ้™ค็š„็ป„็ป‡๏ผ‰ใ€‚ ```bash peer channel fetch config config_block.pb -o orderer.example.com:7050 -c $CHANNEL_NAME --tls --cafile $ORDERER_CA ``` ไธŠ้ขๅ‘ฝไปคๅฐ†ไบŒ่ฟ›ๅˆถ protobuf ้€š้“้…็ฝฎๅ—ไฟๅญ˜ๅˆฐ config_block.pbใ€‚ๆณจๆ„๏ผŒๅ็งฐๅ’Œๆ–‡ไปถๆ‰ฉๅฑ•ๅๅฏไปฅๆ˜ฏไปปๆ„็š„ใ€‚ไฝ†ๆ˜ฏๅปบ่ฎฎๆŒ‡ๅฎšๅ…ถๆ‰€่กจ็คบ็š„ๅฏน่ฑก็ฑปๅž‹ๅŠ็ผ–็ ๏ผˆprotobuf ๆˆ– JSON๏ผ‰ใ€‚ ๅฝ“ๅ‘ๅ‡บ peer channel fetch ๅ‘ฝไปคๆ—ถ๏ผŒ็ปˆ็ซฏไธญๆœ‰ๅพˆๅคš่พ“ๅ‡บใ€‚ๆฅ็œ‹ไธ‹่พ“ๅ‡บๆ—ฅๅฟ—ไธญ็š„ๆœ€ๅŽไธ€่กŒ๏ผš ```text 2017-11-07 17:17:57.383 UTC [channelCmd] readBlock -> DEBU 011 Received block: 2 ``` ่ฟ™ๅ‘Š่ฏ‰ๆˆ‘ไปฌ mychannel ็š„ๆœ€ๆ–ฐ้…็ฝฎๅ—ๅฎž้™…ไธŠๆ˜ฏๅ— 2๏ผŒ่€Œไธๆ˜ฏๅˆ›ไธ–ๅ—ใ€‚้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒpeer channel fetch config ๅ‘ฝไปค่ฟ”ๅ›žๆŒ‡ๅฎš้€š้“็š„ๆœ€ๆ–ฐ้…็ฝฎๅ—๏ผŒๅœจ่ฟ™ไธชๆกˆไพ‹ไธญๆ˜ฏ็ฌฌไธ‰ไธชๅ—ใ€‚่ฟ™ๆ˜ฏๅ› ไธบ BYFN ่„šๆœฌๅœจไธคไธชๅ•็‹ฌ็š„้€š้“ๆ›ดๆ–ฐไบ‹ๅŠกไธญไธบๆˆ‘ไปฌ็š„ไธคไธช็ป„็ป‡๏ผˆOrg1 ๅ’Œ Org2๏ผ‰ๅฎšไน‰ไบ†้”š่Š‚็‚นใ€‚ ๅ› ๆญค๏ผŒๆˆ‘ไปฌๆœ‰ไปฅไธ‹้…็ฝฎ้กบๅบ๏ผš - 0 ๅ—๏ผšๅˆ›ๅง‹ๅ— (็ฌฌไธ€ไธชๅ—) - 1 ๅ—๏ผšOrg1 ้”š็‚นๅฏน็ญ‰ๆ›ดๆ–ฐ๏ผˆ็ฌฌไบŒไธชๅ—๏ผ‰ - 2 ๅ—๏ผšOrg2 ้”š็‚นๅฏน็ญ‰ๆ›ดๆ–ฐ๏ผˆ็ฌฌไธ‰ไธชๅ—๏ผ‰ ## ๅฐ†้…็ฝฎ่ฝฌๆขไธบ JSON ๆ–‡ไปถๅนถไฟฎๅ‰ช ็Žฐๅœจๆˆ‘ไปฌๅฐ†ไฝฟ็”จ configtxlator ๅทฅๅ…ทๅฐ†ๆญค้€š้“้…็ฝฎๅ—่ฝฌ็ ไธบ JSON ๆ ผๅผใ€‚ๆˆ‘ไปฌ่ฟ˜ๅฟ…้กปๅˆ ้™คๆ‰€ๆœ‰ๅคดไฟกๆฏ(header)ใ€ๅ…ƒๆ•ฐๆฎ(metadata)ใ€ๅˆ›ๅปบ่€…็ญพๅ(creator signatures)็ญ‰ไธ€็ณปๅˆ—ไธŽๆˆ‘ไปฌๆƒณ่ฆไฟฎๆ”น็š„ๅ†…ๅฎนๆ— ๅ…ณ็š„ๆ•ฐๆฎใ€‚ๆˆ‘ไปฌไฝฟ็”จ jq ่ฟ™ไธช่ฏฅๅทฅๅ…ทๆฅๅฎŒๆˆ่ฟ™ไบ›ๆ“ไฝœ๏ผš ```bash configtxlator proto_decode --input config_block.pb --type common.Block | jq .data.data[0].payload.data.config > config.json ``` ไธŠ่ฟฐๅ‘ฝไปคไผšๅœจ first-network ๅ†…็š„ fabric-samples ๆ–‡ไปถๅคนไธญ๏ผŒ็ป™ๆˆ‘ไปฌ็”Ÿๆˆไธ€ไธช็ฒพ็ฎ€็š„ JSON ๆ–‡ไปถ - config.jsonใ€‚ ๅœจไฝ ๆœฌๅœฐ็š„็ผ–่พ‘ๅ™จๆˆ–ๆต่งˆๅ™จไธญๆ‰“ๅผ€่ฟ™ไธชๆ–‡ไปถใ€‚ๅณไฝฟๅœจๅฎŒๆˆๆœฌๆ•™็จ‹ไน‹ๅŽ๏ผŒๆญคๆ–‡ไปถไนŸๅ€ผๅพ—็ ”็ฉถ๏ผŒๅ› ไธบๅฎƒๆญ็คบไบ†ๅบ•ๅฑ‚้…็ฝฎ็ป“ๆž„ๅ’Œๅฏไปฅ่ฟ›่กŒ็š„ๅ…ถไป–็ฑปๅž‹็š„้€š้“ๆ›ดๆ–ฐใ€‚ๆƒณไบ†่งฃๆ›ดๅคš้€š้“้…็ฝฎๆ›ดๆ–ฐ็š„ๅ†…ๅฎน๏ผŒๅฏไปฅ็งปๆญฅ่ฟ™้‡Œใ€‚ > ่ฏ‘่€…ๆณจ๏ผš่ฟ™้‡Œไธไผšๅœจ first-network/fabric-samples ๆ–‡ไปถๅคนไธญ๏ผŒ่€Œๆ˜ฏๅœจ CLI ๅฎนๅ™จไธญใ€‚ๆƒณ่ฆๆŸฅ็œ‹๏ผŒๅฏไปฅ้€š่ฟ‡ไธ‹้ขๅ‘ฝไปค๏ผŒๆ‹ท่ดๅˆฐๅฎนๅ™จๅค–็š„ first-network/fabric-sample/channel-artifacts ไธญ: > cp config.json ./channel-artifacts/ ## ๆทปๅŠ  Org3 ๅŠ ๅฏ†่ต„ๆ–™ > ๆ็คบ๏ผšไธ็ฎกไฝ ๆƒณ่ฆๆ›ดๆ–ฐไป€ไนˆๆ ท็š„้…็ฝฎ๏ผŒๅ…ถๆญฅ้ชค้ƒฝๅ’Œๆˆ‘ไปฌ็›ฎๅ‰ๆ‰ง่กŒ็š„ๆญฅ้ชค็›ธๅŒใ€‚ๆˆ‘ไปฌๅœจๆœฌๆ•™็จ‹ไธญ้‡‡ๅ–่ฟ™ๆ ทๆทปๅŠ ็ป„็ป‡็š„ๆ–นๅผ๏ผŒๅ› ไธบ่ฟ™ไผšๆ˜ฏๆ‚จไผš้‡ๅˆฐ็š„ๆœ€ๅคๆ‚็š„้€š้“้…็ฝฎๆ›ดๆ–ฐๆ–นๅผไน‹ไธ€ใ€‚ ๆˆ‘ไปฌๅฐ†ๅ†ๆฌกไฝฟ็”จ jq ๅทฅๅ…ทๅพ€้€š้“็š„ๅบ”็”จ็จ‹ๅบ็ป„ๅญ—ๆฎตไธญ่ฟฝๅŠ  Org3 ็š„้…็ฝฎ--org3.json ๏ผŒๅนถๅฐ†่พ“ๅ‡บๆ–‡ไปถๅ‘ฝๅไธบ modified_config.jsonใ€‚ ```bash jq -s '.[0] \* {"channel_group":{"groups":{"Application":{"groups": {"Org3MSP":.[1]}}}}}' config.json ./channel-artifacts/org3.json > modified_config.json ``` > ่ฏ‘่€…ๆณจ๏ผšๅฐฑๆ˜ฏๆŠŠ org3.json ไธญ็š„ๅ†…ๅฎน๏ผŒๆ‹ท่ดๅˆฐ config.json ไธญ็š„ channel_group.groups.Application.groups.Org3MSP ๅฑžๆ€งไธญ๏ผŒๅนถๆŠŠๆ–ฐ็š„ config.json ไฟๅญ˜ไธบ modified_config.json ็Žฐๅœจ๏ผŒๅœจ CLI ๅฎนๅ™จไธญ๏ผŒๆˆ‘ไปฌๆœ‰ไธคไธช JSON ๆ–‡ไปถ - config.json ๅ’Œ modified_config.jsonใ€‚ๅˆๅง‹ๆ–‡ไปถ๏ผˆconfig.json๏ผ‰ไป…ๅŒ…ๅซ Org1 ๅ’Œ Org2 ่บซไปฝ่ต„ๆ–™๏ผŒ่€Œโ€œmodifiedโ€ๆ–‡ไปถๅŒ…ๅซๆ‰€ๆœ‰ไธ‰ไธช Orgsใ€‚ๆญคๆ—ถ๏ผŒๅช้œ€้‡ๆ–ฐ็ผ–็ ่ฟ™ไธคไธช JSON ๆ–‡ไปถๅนถ่ฎก็ฎ—ๅขž้‡ๅณๅฏใ€‚ ้ฆ–ๅ…ˆ๏ผŒๅฐ† config.json ่ฝฌๆขไธบ protobuf ๆ ผๅผ็š„ config.pb ย  ๆ–‡ไปถ๏ผš ```bash configtxlator proto_encode --input config.json --type common.Config --output config.pb ``` ๆŽฅไธ‹ๆฅ๏ผŒๅฐ† modified_config.json ่ฝฌไธบ modified_config.pb๏ผš ```bash configtxlator proto_encode --input modified_config.json --type common.Config --output modified_config.pb ``` ็Žฐๅœจไฝฟ็”จ configtxlator ๆฅ่ฎก็ฎ—่ฟ™ไธคไธช้…็ฝฎ protobufs ไน‹้—ด็š„ๅขž้‡ใ€‚ๆญคๅ‘ฝไปคๅฐ†่พ“ๅ‡บๅไธบ org3_update.pb ็š„ๆ–ฐ protobuf ๆ ผๅผๆ–‡ไปถ๏ผš ```bash configtxlator compute_update --channel_id $CHANNEL_NAME --original config.pb --updated modified_config.pb --output org3_update.pb ``` ่ฟ™ไธชๆ–ฐ็š„ org3_update.pb ๆ–‡ไปถ๏ผŒๅŒ…ๅซ Org3 ็š„ๅฎšไน‰ๅ’Œ Org1 ๅŠ Org2 ่ต„ๆ–™็š„้ซ˜็บงๆŒ‡้’ˆใ€‚ๆˆ‘ไปฌๆ”พๅผƒๅฏน Org1 ๅ’Œ Org2 ็š„ MSP ๆๆ–™็š„ๆ‰ฉๅฑ•ๅ’Œ็ญ–็•ฅไฟกๆฏ็š„ไฟฎๆ”น๏ผŒๅ› ไธบ่ฟ™ไบ›ๆ•ฐๆฎๅทฒ็ปๅญ˜ๅœจไบŽ้€š้“็š„ๅˆ›ไธ–ๅ—ไธญใ€‚ๅ› ๆญค๏ผŒๆˆ‘ไปฌๅช้œ€่ฆไธค็ง้…็ฝฎไน‹้—ด็š„ๅขž้‡ใ€‚ ๅœจๆœ€็ปˆๆไบค้€š้“ๆ›ดๆ–ฐไน‹ๅ‰๏ผŒๆˆ‘ไปฌ่ฟ˜้œ€่ฆๆ‰ง่กŒไธ€ไบ›ๆญฅ้ชคใ€‚้ฆ–ๅ…ˆ๏ผŒ่ฎฉๆˆ‘ไปฌๅฐ†ๆญคๅฏน่ฑก่งฃ็ ไธบๅฏ็ผ–่พ‘็š„ JSON ๆ ผๅผๅนถๅฐ†ๅ…ถๅ‘ฝๅไธบ org3_update.json๏ผš ```bash configtxlator proto_decode --input org3_update.pb --type common.ConfigUpdate | jq . > org3_update.json ``` ็Žฐๅœจ๏ผŒๆˆ‘ไปฌๆœ‰ไธ€ไธช่งฃ็ ็š„ๆ›ดๆ–ฐๆ–‡ไปถ - org3_update.json - ๆˆ‘ไปฌ้œ€่ฆๅŒ…่ฃ…ไธ€ไธช envelope ๆถˆๆฏใ€‚่ฟ™ไธ€ๆญฅๅฐ†่ฟ”ๅ›žๆˆ‘ไปฌไน‹ๅ‰ๅ‰ฅ็ฆป็š„ header ๅญ—ๆฎตใ€‚ๆˆ‘ไปฌๅฐ†ๆญคๆ–‡ไปถๅ‘ฝๅไธบ org3_update_in_envelope.json๏ผš ```bash echo '{"payload":{"header":{"channel_header":{"channel_id":"mychannel", "type":2}},"data":{"config_update":'$(cat org3_update.json)'}}}' | jq . > org3_update_in_envelope.json ``` > ่ฏ‘่€…ๆณจ๏ผšๅณๆŠŠ org3_update.json ไธญ็š„ๅ†…ๅฎน๏ผŒๆ”พ็ฝฎๅœจ payload.data.config_update ไธญ๏ผŒๅนถๆŠŠ่ฟ™ไธชๅŒ…ๅซ header ๅญ—ๆฎต็š„ๆ–ฐ json ๅญ˜ๅˆฐ org3_update_in_envelope.json ไธญใ€‚ ๆœ€ๅŽ๏ผŒๆˆ‘ไปฌๅฐ†ๅ†ๆฌกไฝฟ็”จ configtxlator ๅทฅๅ…ทๅฐ†ๆ–ฐ็”Ÿๆˆ็š„ org3_update_in_envelope.json ่ฝฌๆขไธบ Fabric ๆ‰€้œ€็š„ protobuf ๆ ผๅผใ€‚ๆˆ‘ไปฌๅฐ†่ฟ™ไธชๆœ€็ปˆๆ›ดๆ–ฐๅฏน่ฑกๅ‘ฝๅไธบ org3_update_in_envelope.pb ```bash configtxlator proto_encode --input org3_update_in_envelope.json --type common.Envelope --output org3_update_in_envelope.pb ``` ## ็ญพๅๅนถๆไบค้…็ฝฎๆ›ดๆ–ฐ ็ปˆไบŽๅฟซ่ฆ็ป“ๆŸไบ†๏ผ ็Žฐๅœจ๏ผŒๆˆ‘ไปฌ็š„ cli ไธญๆœŸไธญๆœ‰ไธ€ไธช org3_update_in_envelope.pb ๆ–‡ไปถใ€‚ๅœจๆŠŠ่ฟ™ไธช้…็ฝฎๅ†™ๅ…ฅ่ดฆๆœฌไน‹ๅ‰๏ผŒๆˆ‘ไปฌ้œ€่ฆ็ฎก็†ๅ‘˜็”จๆˆท็š„็ญพๅใ€‚ๆˆ‘ไปฌ็š„้€š้“ๅบ”็”จ็จ‹ๅบ็ป„็š„ไฟฎๆ”น็ญ–็•ฅ๏ผˆmod_policy๏ผ‰่ขซ้ป˜่ฎค่ฎพ็ฝฎไบ†โ€œMAJORITY๏ผˆๅคšๆ•ฐ๏ผ‰โ€๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌ้œ€่ฆๅคงๅคšๆ•ฐ็Žฐๆœ‰็š„็ป„็ป‡็ฎก็†ๅ‘˜ๆฅ็ญพๅใ€‚ๅ› ไธบๆˆ‘ไปฌๅชๆœ‰ไธคไธช็ป„็ป‡--Org1 ๅ’Œ Org2--่€Œไธคไธชไธญ็š„ๅคšๆ•ฐๆ˜ฏ 2ใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌ้œ€่ฆ่ฟ™ไธคไธช็ญพๅใ€‚ๅฆ‚ๆžœๆฒกๆœ‰่ฟ™ไธคไธช็ญพๅ๏ผŒๆŽ’ๅบๆœๅŠก(orderering service)ๅฐ†ๅ› ไธๆปก่ถณ่ฟ™ไธช็ญ–็•ฅ่€Œๆ‹’็ปไบคๆ˜“ใ€‚ ้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌๅฐ†ไฝฟ็”จ Org1 ็ฎก็†ๅ‘˜็š„่บซไปฝๅŽป็ญพๅใ€‚ๅ› ไธบ่ฟ™ไธช CLI ๅฎนๅ™จๆ˜ฏไฝฟ็”จ Org1 MSP ๅฏๅŠจ็š„๏ผŒๅ› ๆญคๆˆ‘ไปฌๅช้œ€่ฆๆ‰ง่กŒ peer channel signconfigtx ๅ‘ฝไปค๏ผš ```bash peer channel signconfigtx -f org3_update_in_envelope.pb ``` ๆœ€ๅŽ๏ผŒๆˆ‘ไปฌๆฅๅˆ‡ๆข CLI ๅฎนๅ™จ็š„่บซไปฝไธบ Org2 ็š„็ฎก็†ๅ‘˜่บซไปฝใ€‚่ฆไฟฎๆ”น่ฟ™ไธช่บซไปฝ๏ผŒๅช้œ€่ฆ ไฟฎๆ”นๅ››ไธช็Žฏๅขƒๅ˜้‡ > ๆ็คบ๏ผšๅœจ็ป„็ป‡ไน‹้—ดๅˆ‡ๆข่บซไปฝๆฅ็ญพ็ฝฒ้…็ฝฎไบคๆ˜“๏ผˆๆˆ–ๆ‰ง่กŒไปปไฝ•ๅ…ถไป–ๆ“ไฝœ๏ผ‰ๅนถไธ่ƒฝไปฃ่กจ็œŸๅฎž็š„ Fabric ๆ“ไฝœใ€‚ๆฐธ่ฟœไธ่ฆๆŠŠๆ•ดไธช็ฝ‘็ปœ็š„ๅŠ ๅฏ†่ต„ๆ–™ๅฎ‰่ฃ…ๅœจๅ•ไธชๅฎนๅ™จไธŠๅฏๅŠจใ€‚็›ธๅ๏ผŒ้…็ฝฎๆ›ดๆ–ฐ้œ€่ฆๅฎ‰ๅ…จๅœฐไปŽๅค–ไผ ้€’็ป™ Org2 ็ฎก็†ๅ‘˜่ฟ›่กŒๆฃ€ๆŸฅๅ’Œๆ‰นๅ‡†ใ€‚ ่ฎพ็ฝฎ Org2 ็Žฏๅขƒๅ˜้‡๏ผš ```bash # ไฝ ๅฏไปฅไธ€ๆฌกๆ€งๆ‰ง่กŒไธ‹้ข่ฟ™ไบ›ๅ‘ฝไปค export CORE_PEER_LOCALMSPID="Org2MSP" export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp export CORE_PEER_ADDRESS=peer0.org2.example.com:7051 ``` ๆœ€ๅŽ๏ผŒๆˆ‘ไปฌๅฐ†ๆ‰ง่กŒ peer channel update ๅ‘ฝไปคใ€‚ Org2 ็ฎก็†ๅ‘˜็ญพๅๅœจๆญคๅ‘ฝไปคไธญไผš่ขซ้™„ๅธฆ่ฐƒ็”จ๏ผŒๅ› ๆญคๆ— ้œ€ๅ†ๆฌกๆ‰‹ๅŠจ็ญพๅ protobuf ๆ–‡ไปถ๏ผš > ๆ็คบ๏ผšๆŽฅไธ‹ๆฅ่ฆ่ฟ›่กŒ็š„ orderer ๆœๅŠกๆ›ดๆ–ฐ่ฐƒ็”จๅฐ†่ฟ›่กŒไธ€็ณปๅˆ—็ณป็ปŸ็ญพๅๅ’Œ็ญ–็•ฅๆฃ€ๆŸฅใ€‚ๅ› ๆญค, ๆ‚จๅฏ่ƒฝไผšๅ‘็Žฐๆฃ€ๆŸฅ orderer ่Š‚็‚น็š„ๆ—ฅๅฟ—ๆตไผšๅพˆๆœ‰็”จใ€‚ๅœจๅฆไธ€ไธช shell ็ซฏๆ‰ง่กŒ docker logs -f orderer.example.com ๅ‘ฝไปคๆฅๆŸฅ็œ‹ orderer ่Š‚็‚นๆ—ฅๅฟ—ใ€‚ ๆ‰ง่กŒๆ›ดๆ–ฐ่ฐƒ็”จ๏ผš ```bash peer channel update -f org3_update_in_envelope.pb -c $CHANNEL_NAME -o orderer.example.com:7050 --tls --cafile $ORDERER_CA ``` ๅฆ‚ๆžœๆ›ดๆ–ฐๅทฒๆˆๅŠŸๆไบค๏ผŒๅบ”่ฏฅไผš็œ‹ๅˆฐ็ฑปไผผไบŽไปฅไธ‹ๅ†…ๅฎน็š„ๆถˆๆฏๆ็คบ๏ผš ```text 2018-02-24 18:56:33.499 UTC [msp/identity] Sign -> DEBU 00f Sign: digest: 3207B24E40DE2FAB87A2E42BC004FEAA1E6FDCA42977CB78C64F05A88E556ABA ``` ่ฟ˜ๅฐ†็œ‹ๅˆฐๆˆ‘ไปฌ็š„้…็ฝฎไบ‹ๅŠก็š„ๆไบค๏ผš ``` 2018-02-24 18:56:33.499 UTC [channelCmd] update -> INFO 010 Successfully submitted channel update ``` ้€š้“ๆ›ดๆ–ฐ่ฐƒ็”จๆˆๅŠŸไผšๅ‘้€š้“ไธญๆ‰€ๆœ‰็š„่Š‚็‚น่ฟ”ๅ›žไธ€ไธชๆ–ฐๅ— - ๅ— 5ใ€‚ๅฆ‚ๆžœไฝ ่ฟ˜่ฎฐๅพ—็š„่ฏ๏ผŒๅ— 0-2 ๆ˜ฏๅˆๅง‹้€š้“้…็ฝฎ๏ผŒ่€Œๅ— 3 ๅ’Œ 4 ๆ˜ฏ mycc ้“พ็ ็š„ๅฎžไพ‹ๅŒ–ๅ’Œ่ฐƒ็”จใ€‚ๅ› ๆญค๏ผŒๅ— 5 ็”จไฝœๆœ€ๆ–ฐ็š„้€š้“้…็ฝฎ๏ผŒๅ…ถไธญๅœจ้€š้“ไธŠๅฎšไน‰ไบ† Org3ใ€‚ ๆฃ€ๆŸฅ peer0.org1.example.com ็š„ๆ—ฅๅฟ—๏ผˆๅœจๅฆไธ€ไธช็ปˆ็ซฏ๏ผ‰๏ผš ```bash docker logs -f peer0.org1.example.com ``` ๅฆ‚ๆžœๆƒณ่ฆๆฃ€ๆŸฅๆ–ฐ้…็ฝฎๅ—ๅ†…ๅฎน๏ผŒ่ฏทๆŒ‰็…งไธŠ้ข็š„ๆผ”็คบ่ฟ‡็จ‹ๆฅ่Žทๅ–ๅ’Œ่งฃ็ ๆ–ฐ้…็ฝฎๅ—ใ€‚ ## ้…็ฝฎ้ข†ๅฏผ่Š‚็‚น้€‰ไธพ > ๆ็คบ๏ผšๅœจๆœฌๆ•™็จ‹ไธญ๏ผŒๆญค้ƒจๅˆ†ไฝœไธบไธ€่ˆฌๅ‚่€ƒ็”จไบŽ็†่งฃ้ข†ๅฏผ่€…้€‰ไธพ่ฎพ็ฝฎใ€‚ๆญค็คบไพ‹้ป˜่ฎคไธบๅŠจๆ€้ข†ๅฏผ่€…้€‰ไธพ๏ผŒ่ฏฅ้€‰ไธพๆ˜ฏๅœจ peer-base.yaml ไธญไธบ็ฝ‘็ปœไธญ็š„ๆ‰€ๆœ‰่Š‚็‚น่ฎพ็ฝฎ็š„ใ€‚ ๆ–ฐๅŠ ๅ…ฅ็š„่Š‚็‚น้ƒฝๆ˜ฏไฝฟ็”จๅˆ›ๅง‹ๅ—ๅฏๅŠจ็š„ใ€‚ไฝ†ๅˆ›ๅง‹ๅ—ไธญๅนถไธๅŒ…ๅซ่ขซๆ–ฐๆทปๅŠ ๅˆฐ้€š้“้…็ฝฎๆ›ดๆ–ฐไธญ็ป„็ป‡็š„ไฟกๆฏใ€‚ๆ‰€ไปฅ๏ผŒ่ฟ™ไบ›ๆ–ฐ่Š‚็‚นๆ— ๆณ•้ชŒ่ฏๅ…ถไป–่Š‚็‚นไปŽไป–ไปฌ่‡ชๅทฑ็š„็ป„็ป‡่ฝฌๅ‘่ฟ‡ๆฅ็š„ๅ—๏ผŒ็›ดๅˆฐไป–ไปฌ่Žทๅพ—ๅฐ†็ป„็ป‡ๆทปๅŠ ๅˆฐ้ข‘้“็š„้…็ฝฎไบ‹ๅŠกใ€‚ๅ› ๆญค๏ผŒๆ–ฐๅŠ ๅ…ฅ็š„่Š‚็‚นๅฟ…้กปๅ…ทๆœ‰ไปฅไธ‹้…็ฝฎไน‹ไธ€๏ผŒไปฅไพฟๅฎƒไปฌไปŽ orderer ๆœๅŠกๆŽฅๆ”ถๅ—๏ผš 1ใ€่ฆไฝฟ็”จ้™ๆ€้ข†ๅฏผๆจกๅผ๏ผŒ่ฏทๅฐ†่Š‚็‚น้…็ฝฎไธบ็ป„็ป‡้ข†ๅฏผ่€…๏ผš ```bash CORE_PEER_GOSSIP_USELEADERELECTION=false CORE_PEER_GOSSIP_ORGLEADER=true ``` > ๆ็คบ๏ผšๅฏนไบŽๆทปๅŠ ๅˆฐ้€š้“็š„ๆ‰€ๆœ‰ๆ–ฐ่Š‚็‚น๏ผŒๆญค้…็ฝฎๅฟ…้กป็›ธๅŒใ€‚ 2ใ€่ฆไฝฟ็”จๅŠจๆ€้ข†ๅฏผ่€…้€‰ไธพ๏ผŒ่ฏทๅฐ†่Š‚็‚น้…็ฝฎไธบไฝฟ็”จ้ข†ๅฏผ่€…้€‰ไธพ๏ผš ```bash CORE_PEER_GOSSIP_USELEADERELECTION=true CORE_PEER_GOSSIP_ORGLEADER=false ``` > ๆ็คบ๏ผš็”ฑไบŽๆ–ฐๆทปๅŠ ็š„็ป„็ป‡็š„่Š‚็‚นๅฐ†ๆ— ๆณ•ๅฝขๆˆๆˆๅ‘˜่ง†ๅ›พ๏ผˆmembership view๏ผ‰๏ผŒๆญค้€‰้กนไธŽ้™ๆ€้…็ฝฎ็ฑปไผผ๏ผŒๅ› ไธบๆฏไธช่Š‚็‚นๅฐ†ๅผ€ๅง‹ๅฎฃ็งฐ่‡ชๅทฑๆ˜ฏ้ข†ๅฏผ่€…ใ€‚ไฝ†ๆ˜ฏ๏ผŒไธ€ๆ—ฆไป–ไปฌๆ›ดๆ–ฐไบ†ๅฐ†็ป„็ป‡ๆทปๅŠ ๅˆฐ้€š้“็š„้…็ฝฎไบ‹ๅŠก๏ผŒ็ป„็ป‡ไธญๅฐ†ๅชๆœ‰ไธ€ไธชๆดป่ทƒ็š„้ข†ๅฏผ่€…ใ€‚ๅ› ๆญค๏ผŒๅฆ‚ๆžœๆ‚จๆœ€็ปˆๅธŒๆœ›็ป„็ป‡็š„่Š‚็‚นไฝฟ็”จ้ข†ๅฏผ่€…้€‰ไธพ๏ผŒๅปบ่ฎฎไฝฟ็”จๆญค้€‰้กนใ€‚ ## ๆŠŠ Org3 ๅŠ ๅ…ฅ้€š้“ ๆญคๆ—ถ๏ผŒ้€š้“้…็ฝฎๅทฒๆ›ดๆ–ฐไธบๅŒ…ๅซๆˆ‘ไปฌ็š„ๆ–ฐ็ป„็ป‡--Org3 - ๆ„ๅ‘ณ็€ไธŽๅ…ถๅ…ณ่”็š„่Š‚็‚น็ŽฐๅœจๅฏไปฅๅŠ ๅ…ฅ mychannelใ€‚ ้ฆ–ๅ…ˆ๏ผŒ่ฎฉๆˆ‘ไปฌๅฏๅŠจไธบ Org3 ็‰นๅฎš็š„ CLI ๅฎนๅ™จใ€‚ ๆ‰“ๅผ€ไธ€ไธชๆ–ฐ็š„็ปˆ็ซฏ๏ผŒๅœจ first-network ็›ฎๅฝ•ไธ‹๏ผŒๅฏๅŠจ Org3 ๅฎนๅ™จ๏ผš ```bash docker-compose -f docker-compose-org3.yaml up -d ``` ่ฟ™ไธช compose ๆ–‡ไปถๅทฒ้…็ฝฎๅœจๆˆ‘ไปฌ็š„ๅˆๅง‹็ฝ‘็ปœไธญ๏ผŒๅ› ๆญคไธคไธช่Š‚็‚นๅ’Œ CLI ๅฎนๅ™จๅฐ†่ƒฝๅคŸไฝฟ็”จ็Žฐๆœ‰่Š‚็‚นๅ’Œ oredrer ่Š‚็‚น่ฟ›่กŒ้€šไฟกใ€‚็Žฐๅœจๅทฒ็ป่ฟ่กŒไบ†ไธ‰ไธชๅฎนๅ™จ๏ผŒๆˆ‘ไปฌๆฅ่ฟ›ๅ…ฅ Org3 ็š„ CLI ๅฎนๅ™จ๏ผš ```bash docker exec -it Org3cli bash ``` ๅฐฑๅƒๆˆ‘ไปฌๅฏนๅˆๅง‹ CLI ๅฎนๅ™จๆ‰€ๅš็š„้‚ฃๆ ท๏ผŒ่ฎพ็ฝฎไธคไธชๅ…ณ้”ฎ็Žฏๅขƒๅ˜้‡๏ผšORDERER_CA ๅ’Œ CHANNEL_NAME๏ผš ```bash export ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem export CHANNEL_NAME=mychannel ``` ๆฃ€ๆŸฅไปฅ็กฎไฟๅทฒๆญฃ็กฎ่ฎพ็ฝฎๅ˜้‡๏ผš ```bash echo $ORDERER_CA && echo $CHANNEL_NAME ``` ็Žฐๅœจๆˆ‘ไปฌๅ‘ orderer ๆœๅŠกๅ‘่ตท่ฏทๆฑ‚ๆฅ่Žทๅ– mychannel ็š„ๅˆ›ไธ–ๅ—ใ€‚็”ฑไบŽๆˆ‘ไปฌๆˆๅŠŸๅœฐๆ›ดๆ–ฐไบ†้€š้“๏ผŒorderer ๆœๅŠก่ƒฝๅคŸ้ชŒ่ฏ่ฟ™ไธช่ฏทๆฑ‚ไธญ็š„ Org3 ็ญพๅใ€‚ๅฆ‚ๆžœ Org3 ๆฒกๆœ‰ๆˆๅŠŸๆ›ดๆ–ฐๅ…ฅ้€š้“้…็ฝฎไธญ๏ผŒorderer ๆœๅŠกๅˆ™ไผšๆ‹’็ปๆญค่ฏทๆฑ‚ใ€‚ ไฝฟ็”จ peer channel fetch ๅ‘ฝไปค่Žทๅ–ๅ—๏ผš ```bash peer channel fetch 0 mychannel.block -o orderer.example.com:7050 -c $CHANNEL_NAME --tls --cafile $ORDERER_CA ``` ่ฏทๆณจๆ„๏ผŒๆˆ‘ไปฌไผ ้€’ 0 ่ฟ™ไธชๅ‚ๆ•ฐ๏ผŒ่กจๅๆˆ‘ไปฌ่ฆ่Žทๅ–่ดฆๆœฌไธญ็š„็ฌฌไธ€ไธชๅŒบๅ—๏ผˆๅณๅˆ›ๅง‹ๅ—๏ผ‰ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅชๆ˜ฏ ไฝฟ็”จ peerย channelย fetchย config ๅ‘ฝไปค๏ผŒๆˆ‘ไปฌไผš่Žทๅ–็ฌฌ 5 ไธชๅŒบๅ—--ๅฎšไน‰ไบ† Org3 ้…็ฝฎๆ›ดๆ–ฐ็š„ๅŒบๅ—ใ€‚ไฝ†ๆ˜ฏ๏ผŒๆˆ‘ไปฌไธ่ƒฝไปŽไธ‹ๆธธๅŒบๅ—ๆฅๅผ€ๅง‹ๆˆ‘ไปฌ็š„ๅธๆœฌ - ๆˆ‘ไปฌๅฟ…้กปไปŽๅ— 0 ๅผ€ๅง‹ใ€‚ ๆ‰ง่กŒ peer channel join ๅ‘ฝไปคๅนถไผ ๅ…ฅ genesis ๅ— - mychannel.block๏ผš ```bash peer channel join -b mychannel.block ``` ๅฆ‚ๆžœ่ฆๅŠ ๅ…ฅ Org3 ็š„็ฌฌไบŒไธช่Š‚็‚น๏ผŒ่ฏท้‡ๆ–ฐ่ฎพ็ฝฎ TLS ๅ’Œ ADDRESS ๅ˜้‡ๅนถๆ‰ง่กŒ peerย channelย joinย command ๏ผš ```bash export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org3.example.com/peers/peer1.org3.example.com/tls/ca.crt export CORE_PEER_ADDRESS=peer1.org3.example.com:7051 peer channel join -b mychannel.block ``` ## ๅ‡็บงๅ’Œ่ฐƒ็”จ Chaincode ๆœฌๆ•™็จ‹ๆœ€ๅŽไธ€ๅ—ๅ†…ๅฎนๅฐฑๆ˜ฏๆ›ดๆ–ฐ้“พ็ ็š„็‰ˆๆœฌ๏ผŒๅนถๆ›ดๆ–ฐ่ƒŒไนฆ็ญ–็•ฅ๏ผˆๆŠŠ Org3 ๅŒ…ๅซ่ฟ›ๅŽป๏ผ‰ใ€‚้ฉฌไธŠๅฐฑ่ฆๅ‡็บง้“พ็ ๏ผŒๅ› ๆญคๆˆ‘ไปฌๅฏไปฅๆ”พ็›ดๆŽฅๅผƒๅฎ‰่ฃ…็ฌฌ 1 ็‰ˆ้“พ็ ็š„ๆญฅ้ชคใ€‚ๆˆ‘ไปฌๅชๅ…ณๆณจ Org3 ๅฐ†ๆˆไธบ่ƒŒไนฆ็ญ–็•ฅไธ€้ƒจๅˆ†็š„ๆ–ฐ็‰ˆๆœฌ๏ผŒๅ› ๆญคๆˆ‘ไปฌๅฐ†็›ดๆŽฅ่ทณ่ฝฌๅˆฐ้“พ็ ็š„็ฌฌ 2 ็‰ˆใ€‚ ๅœจ Org3 ็š„ CLI ๅฎนๅ™จไธญๆ‰ง่กŒ๏ผš ```bash peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/ ``` ๅฆ‚ๆžœ่ฆๅœจ Org3 ็š„็ฌฌไบŒไธช่Š‚็‚นไธŠๅฎ‰่ฃ…้“พ็ ๏ผŒๅฐฑ้œ€่ฆ็›ธๅบ”ๅœฐไฟฎๆ”น็Žฏๅขƒๅ˜้‡๏ผŒๅนถ้‡ๆ–ฐๆ‰ง่กŒ่ฏฅๅ‘ฝไปคใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒ็ฌฌไบŒๆฌกๅฎ‰่ฃ…ไธๆ˜ฏๅผบๅˆถ่ฆๆฑ‚็š„๏ผŒๅ› ไธบๆ‚จๅช้œ€่ฆๅœจ้‚ฃไบ›ๅฐ†ไฝœไธบ่ƒŒไนฆ่Š‚็‚นๆˆ–ไปฅๅ…ถไป–ๆ–นๅผไธŽ่ดฆๆœฌๆœ‰ๆŽฅๅฃๅ…ณ็ณป็š„่Š‚็‚นไธŠๅฎ‰่ฃ…้“พไปฃ็ (ไพ‹ๅฆ‚๏ผŒไป…ๆŸฅ่ฏข๏ผ‰ใ€‚่Š‚็‚นไปๅฐ†่ฟ่กŒ้ชŒ่ฏ้€ป่พ‘๏ผŒๅนถๅœจๆฒกๆœ‰่ฟ่กŒ้“พ็ ๅฎนๅ™จ็š„ๆƒ…ๅ†ตไธ‹ๅ……ๅฝ“ๆไบค่€…ใ€‚ ็Žฐๅœจ๏ผŒๅ›žๅˆฐๆœ€ๅผ€ๅง‹็š„ CLI ๅฎนๅ™จ๏ผŒๅนถๅœจ Org1 ๅ’Œ Org2 ็š„่Š‚็‚นไธŠๅฎ‰่ฃ…ๆ–ฐ็‰ˆๆœฌ้“พ็ ใ€‚ไน‹ๅ‰๏ผŒๆˆ‘ไปฌไฝฟ็”จ Org2 ็ฎก็†ๅ‘˜่บซไปฝๆไบคไบ†้ข‘้“ๆ›ดๆ–ฐ่ฐƒ็”จ๏ผŒๅ› ๆญคๅฎนๅ™จไป็„ถไปฃ่กจ็€ peer0.org2๏ผŒๆˆ‘ไปฌ็›ดๆŽฅๅฎ‰่ฃ…๏ผš ```bash peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/ ``` ็„ถๅŽ๏ผŒๅˆ‡ๆขๅˆฐ peer0.org1 ็š„่บซไปฝ๏ผš ```bash export CORE_PEER_LOCALMSPID="Org1MSP" export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp export CORE_PEER_ADDRESS=peer0.org1.example.com:7051 ``` ๅ†ๆฌกๅฎ‰่ฃ…๏ผš ```bash peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/ ``` ็Žฐๅœจๆˆ‘ไปฌๅ‡†ๅค‡ๅ‡็บง้“พ็ ไบ†ใ€‚ๅฏนๅบ•ๅฑ‚ๆบไปฃ็ ๆฒกๆœ‰ๅšไปปไฝ•ไฟฎๆ”น๏ผŒๆˆ‘ไปฌๅชๆ˜ฏๅœจ mychannel ไธŠ็š„้“พ็  mycc ้‡Œ้ข๏ผŒๅฐ† Org3 ๆทปๅŠ ๅˆฐ ็š„่ƒŒไนฆๆ”ฟ็ญ–ไธญใ€‚ > ๆ็คบ๏ผšๆปก่ถณ้“พ็ ๅฎžไพ‹ๅŒ–็ญ–็•ฅ็š„ไปปไฝ•่บซไปฝ้ƒฝๅฏไปฅๅ‘ๅ‡บๅ‡็บง่ฐƒ็”จใ€‚้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒ่ฟ™ไบ›่บซไปฝๆ˜ฏ้€š้“็ฎก็†ๅ‘˜ใ€‚ ๆ‰ง่กŒๅ‡็บงๅ‘ฝไปค๏ผš ```bash peer chaincode upgrade -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -v 2.0 -c '{"Args":["init","a","90","b","210"]}' -P "OR ('Org1MSP.peer','Org2MSP.peer','Org3MSP.peer')" ``` ๅœจไธŠ้ข็š„ๅ‘ฝไปคไธญ๏ผŒ้€š่ฟ‡ v ๆ ‡ๅฟ—ๆŒ‡ๅฎšๆˆ‘ไปฌ็š„ๆ–ฐ็‰ˆๆœฌใ€‚่ƒŒไนฆ็ญ–็•ฅๅทฒ่ขซไฟฎๆ”นไธบ -Pโ€œOR๏ผˆ'Org1MSP.peer'๏ผŒ'Org2MSP.peer'๏ผŒ'Org3MSP.peer'๏ผ‰โ€๏ผŒๅๆ˜ ไบ†็ญ–็•ฅไธญๆทปๅŠ ไบ† Org3ใ€‚ๆœ€ๅŽๅฐฑๆ˜ฏๆˆ‘ไปฌ็š„ๅ‡ฝๆ•ฐ่ฏทๆฑ‚ๆž„้€ ๏ผˆไฝฟ็”จ c ๆ ‡ๅฟ—ๆŒ‡ๅฎš๏ผ‰ใ€‚ ไธŽๅฎžไพ‹ๅŒ–่ฐƒ็”จไธ€ๆ ท๏ผŒ้“พ็ ๅ‡็บง้œ€่ฆไฝฟ็”จ init ๆ–นๆณ•ใ€‚ๅฆ‚ๆžœๆ‚จ็š„้“พ็ ้œ€่ฆๅฐ†ๅ‚ๆ•ฐไผ ้€’็ป™ init ๆ–นๆณ•๏ผŒ้‚ฃไนˆๆ‚จ้œ€่ฆๅœจๆญคๅค„ๆ‰ง่กŒๆญคๆ“ไฝœใ€‚ ๅ‡็บง่ฐƒ็”จๅ‘่ดฆๆœฌไธญๆทปๅŠ ไบ†ไธ€ไธชๆ–ฐๅ— - ๅ— 6 ๏ผŒๆฅๅ…่ฎธ Org3 ็š„่Š‚็‚นๅœจ่ƒŒไนฆ้˜ถๆฎตๆ‰ง่กŒไบคๆ˜“ใ€‚ๅ›žๅˆฐ Org3 CLI ๅฎนๅ™จ๏ผŒๆˆ‘ไปฌๆฅๆŸฅ่ฏขไธ‹ a ็š„ๅ€ผ๏ผŒ่ฟ™้œ€่ฆ่Šฑไธ€ไบ›ๆ—ถ้—ด๏ผŒๅ› ไธบ้œ€่ฆไธบ็›ฎๆ ‡่Š‚็‚นๆž„ๅปบ้“พไปฃ็ ้•œๅƒ๏ผŒๅนถไธ”้“พ็ ๅฎนๅ™จ้œ€่ฆๅฏๅŠจ๏ผš ```bash peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}' ``` ๆˆ‘ไปฌๅบ”่ฏฅ็œ‹ๅˆฐ่ฟ”ๅ›žไธบ Query Result๏ผš90ใ€‚ ็Žฐๅœจๅ‘ๅ‡บไธ€ไธช่ฐƒ็”จ๏ผŒๅฐ† 10 ไปŽ a ่ฝฌ็งปๅˆฐ b๏ผš ```bash peer chaincode invoke -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -c '{"Args":["invoke","a","b","10"]}' ``` ๆœ€ๅŽๆŸฅ่ฏขไธ€ๆฌก๏ผš ```bash peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}' ``` ๆˆ‘ไปฌๅบ”่ฏฅ็œ‹ๅˆฐ Query Result๏ผš80 ็š„ๅ“ๅบ”๏ผŒ่ฟ™ๅฐฑๅ‡†็กฎๅœฐๅๆ˜ ไบ†่ฟ™ไธช chaincode ็Šถๆ€็š„ๆ›ดๆ–ฐใ€‚ # ๆ€ป็ป“ ้€š้“้…็ฝฎๆ›ดๆ–ฐ่ฟ‡็จ‹็กฎๅฎž้žๅธธๅคๆ‚๏ผŒไฝ†ๆ˜ฏๆญฅ้ชคไธญๆ–นๆณ•่ฟ˜ๆ˜ฏๆœ‰ไบ›้€ป่พ‘็š„ใ€‚ๆœ€ๅŽไนŸๅฐฑๆ˜ฏ็”Ÿๆˆ protobuf ไบŒ่ฟ›ๅˆถๆ ผๅผ่กจ็คบ็š„ delta ไบ‹ๅŠกๅฏน่ฑก๏ผŒ็„ถๅŽ่Žทๅ–ๅฟ…้œ€ๆ•ฐ้‡็š„็ฎก็†ๅ‘˜็ญพๅ๏ผŒไปฅไพฟ้€š้“้…็ฝฎๆ›ดๆ–ฐไบ‹ๅŠกๆปก่ถณ้€š้“็š„ไฟฎๆ”น็ญ–็•ฅใ€‚ ๆˆ‘ไปฌๅฎŒๆˆ่ฟ™ๆ ท็š„ๅŠŸ่ƒฝ๏ผŒไธป่ฆๅฐฑ็”จๅˆฐไบ† configtxlator ๅ’Œ jq ๅทฅๅ…ทไปฅๅŠๅพˆๅคš็š„ peerย channel ๅ‘ฝไปคใ€‚
package seq_cmd import ( "fmt" "strconv" "time" "github.com/lunfardo314/proxima/ledger" "github.com/lunfardo314/proxima/ledger/transaction" "github.com/lunfardo314/proxima/ledger/txbuilder" "github.com/lunfardo314/proxima/proxi/glb" "github.com/lunfardo314/proxima/sequencer/factory/commands" "github.com/lunfardo314/proxima/util" "github.com/spf13/cobra" ) func initSeqWithdrawCmd() *cobra.Command { seqSendCmd := &cobra.Command{ Use: "withdraw <amount>", Aliases: util.List("send"), Short: `withdraw tokens from sequencer to the target lock`, Args: cobra.ExactArgs(1), Run: runSeqWithdrawCmd, } seqSendCmd.InitDefaultHelpCmd() return seqSendCmd } const ownSequencerCmdFee = 500 func runSeqWithdrawCmd(_ *cobra.Command, args []string) { glb.InitLedgerFromNode() walletData := glb.GetWalletData() glb.Assertf(walletData.Sequencer != nil, "can't get own sequencer ID") glb.Infof("sequencer ID (source): %s", walletData.Sequencer.String()) glb.Infof("wallet account is: %s", walletData.Account.String()) targetLock := glb.MustGetTarget() amount, err := strconv.ParseUint(args[0], 10, 64) glb.AssertNoError(err) glb.Infof("amount: %s", util.GoTh(amount)) glb.Infof("querying wallet's outputs..") walletOutputs, err := getClient().GetAccountOutputs(walletData.Account, func(_ *ledger.OutputID, o *ledger.Output) bool { return o.NumConstraints() == 2 }) glb.AssertNoError(err) glb.Infof("will be using %d tokens as tag-along fee. Outputs in the wallet:", ownSequencerCmdFee) for i, o := range walletOutputs { glb.Infof("%d : %s : %s", i, o.ID.StringShort(), util.GoTh(o.Output.Amount())) } prompt := fmt.Sprintf("withdraw %s from %s to the target %s?", util.GoTh(amount), walletData.Sequencer.StringShort(), targetLock.String()) if !glb.YesNoPrompt(prompt, false) { glb.Infof("exit") return } cmdConstr, err := commands.MakeSequencerWithdrawCommand(amount, targetLock.AsLock()) glb.AssertNoError(err) transferData := txbuilder.NewTransferData(walletData.PrivateKey, walletData.Account, ledger.TimeNow()). WithAmount(ownSequencerCmdFee). WithTargetLock(ledger.ChainLockFromChainID(*walletData.Sequencer)). MustWithInputs(walletOutputs...). WithSender(). WithConstraint(cmdConstr) txBytes, err := txbuilder.MakeSimpleTransferTransaction(transferData) glb.AssertNoError(err) txStr := transaction.ParseBytesToString(txBytes, transaction.PickOutputFromListFunc(walletOutputs)) glb.Verbosef("---- request transaction ------\n%s\n------------------", txStr) glb.Infof("submitting the transaction...") err = getClient().SubmitTransaction(txBytes) glb.AssertNoError(err) if glb.NoWait() { return } txid, err := transaction.IDFromTransactionBytes(txBytes) glb.AssertNoError(err) glb.ReportTxInclusion(txid, time.Second) }
import React, { useContext, useState, useEffect, useRef } from "react"; import { useNavigate } from "react-router-dom"; import axios from "axios"; // mui import { Stack, Typography, Grid, TextField, Button, Box, Toolbar, Paper, Autocomplete } from "@mui/material"; import LoadingButton from "@mui/lab/LoadingButton"; import { SyncAlt } from "@mui/icons-material"; // contexts import AdminContext from "../../contexts/AdminContext"; // constants import { AUTH_ADMIN_ROUTE, PROFILE_ROUTE } from "../../constants/routes"; import { ADMIN_NEW_DOCUMENT_ENDPOINT } from "../../constants/endpoints"; // components import Footer from "../../components/Footer"; import Loader from "../../components/Loader"; const NewDocuments = () => { const formRef = useRef(null); const navigate = useNavigate(); const { user, isProfileComplete, documents, collections, collection, setCollection } = useContext(AdminContext); const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (!user) navigate(AUTH_ADMIN_ROUTE); }, [user, navigate]); const handleNewDocument = (e) => { e.preventDefault(); const form = e.target; const data = {}; const formData = new FormData(form); formData.forEach((value, key) => (data[key] = value)); try { setIsLoading(true); axios .post(ADMIN_NEW_DOCUMENT_ENDPOINT, { name: collection, data }) .then((res) => { alert(data.title + " uploaded successfully!"); setIsLoading(false); }) .catch((err) => { console.log(err); setIsLoading(false); }); } catch (err) { console.log(err); } }; return ( <Box component="main" sx={{ backgroundColor: (theme) => (theme.palette.mode === "light" ? theme.palette.grey[100] : theme.palette.grey[900]), flexGrow: 1, height: "100vh", overflow: "auto", }} > {isLoading ? <Loader /> : null} <Toolbar /> {isProfileComplete(user) ? ( <Grid container spacing={2} sx={{ p: 2 }}> <Grid item xs={12}> <Paper sx={{ p: 2, display: "flex", flexDirection: "column" }}> <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={2} mb={2}> <Typography component="h2" variant="h6" color="primary" gutterBottom> New Document </Typography> <Autocomplete disablePortal sx={{ minWidth: 200 }} options={collections} value={collection} onChange={(e, value) => setCollection(value)} renderInput={(params) => <TextField {...params} label="Search Collections" />} /> </Stack> <form onSubmit={handleNewDocument} ref={formRef}> <Grid container spacing={2}> {documents.length && Object.keys(documents[0]).map((key) => ( <Grid key={key} item xs={12} sm={6} md={4} lg={3}> <TextField multiline maxRows={4} name={key} label={key} fullWidth variant="outlined" /> </Grid> ))} </Grid> <Stack spacing={2} direction="row" justifyContent={"space-between"} sx={{ display: "flex", mt: 2 }}> <LoadingButton loading={isLoading} type="submit" variant="contained" startIcon={<SyncAlt />}> Upload </LoadingButton> </Stack> </form> </Paper> </Grid> </Grid> ) : ( <Stack py={16} spacing={2} alignItems="center" justifyContent="center"> <Typography component="p" variant="h4" align="center" color="error"> Profile Incomplete! </Typography> <Typography component="p" variant="body1" align="center" color="text.secondary"> Update your profile with all the necessary details to become a document/service provider! </Typography> <Button onClick={() => navigate(PROFILE_ROUTE)} sx={{ width: "fit-content" }} variant="contained"> Update Profile </Button> </Stack> )} <Footer /> </Box> ); }; export default NewDocuments;
/* eslint-disable @typescript-eslint/no-explicit-any */ "use client"; import dynamic from "next/dynamic"; import { FC } from "react"; const Chart = dynamic(() => import("react-apexcharts"), { ssr: false }); type TCurve = | "smooth" | "straight" | "stepline" | "smooth" | "straight" | "stepline"; type Props = { id: string | "bar-chart"; series: any | undefined; type?: "bar" | any; colors?: Array<string>; className?: string; dropShadowColor?: string; strokeColor?: Array<string>; height?: number | string; width?: number | string; stacked?: boolean; plotOptions?: boolean; showGrid?: boolean; categories?: Array<string>; label?: Array<string>; curve?: TCurve | TCurve[]; showDownloads?: boolean; }; export const CustomChart: FC<Props> = ({ type, colors, id, series, className, height, showGrid, label, categories, curve, showDownloads, stacked, }) => { const yaxisOptions = { show: true, labels: { show: true, style: { colors: "grey", fontSize: "13px", fontWeight: 100, fontFamily: "Outfit", }, formatter: (value: any) => { return type !== "line" && type !== "area" && value > 0 ? value : value; }, }, axisBorder: { show: false, }, axisTicks: { show: false, }, }; const options = { chart: { id: id, toolbar: { show: true, tools: { download: showDownloads ? true : false, selection: false, zoom: false, zoomin: false, zoomout: false, pan: false, reset: false, }, }, selection: { enabled: true, stroke: {}, }, background: "#FFF", dropShadow: { enabled: true, blur: 5, opacity: 0.2, color: "grey", }, stacked: stacked, }, labels: label, xaxis: { categories: categories || [], labels: { show: true, style: { fontFamily: `Outfit`, color: "grey", fontWeight: 300, }, }, axisBorder: { show: false, }, axisTicks: { show: false, }, }, yaxis: yaxisOptions, fill: { colors: colors, }, states: { hover: { filter: { type: "none" }, }, active: { filter: { type: "none" }, }, }, grid: { show: showGrid ?? true, borderColor: `${"#EAEAEA"}`, yaxis: { lines: { show: true, }, }, xaxis: { lines: { show: false, }, tooltip: { enabled: false, }, labels: { show: true, style: { fontSize: "13px", fontWeight: "300", fontFamily: "Outfit", }, }, }, }, dataLabels: { enabled: false, }, tooltip: { enabled: true, shared: false, show: false, style: { fontSize: "12px", fontFamily: "Outfit", background: "green", }, x: { show: false, }, y: { show: true, formatter: function (value: number) { return `${value}`; }, }, marker: { show: false }, theme: "dark", }, stroke: { show: true, colors: colors, curve: curve, }, colors: colors, }; return ( <Chart options={options} series={series} type={type} height={height ?? 300} width={"100%"} className={className} /> ); };
/* * Copyright (c) 2010 International Health Terminology Standards Development * Organisation * * 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 org.ihtsdo.project.wizard; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.HashMap; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.ihtsdo.wizard.I_fastWizard; /** * The Class SimpleTextCollector. * * @author Guillermo Reynoso */ public class SimpleTextCollector extends JPanel implements I_fastWizard { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 4533413277239846148L; /** * Instantiates a new simple text collector. */ public SimpleTextCollector() { initComponents(); } /** * Inits the components. */ private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents label1 = new JLabel(); textField1 = new JTextField(); //======== this ======== setLayout(new GridBagLayout()); ((GridBagLayout)getLayout()).columnWidths = new int[] {0, 0, 0, 0, 0}; ((GridBagLayout)getLayout()).rowHeights = new int[] {15, 0, 0, 0, 0}; ((GridBagLayout)getLayout()).columnWeights = new double[] {0.0, 0.0, 1.0, 0.0, 1.0E-4}; ((GridBagLayout)getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 1.0E-4}; //---- label1 ---- label1.setText("text"); add(label1, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); add(textField1, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables /** The label1. */ private JLabel label1; /** The text field1. */ private JTextField textField1; /** The key. */ private String key; // JFormDesigner - End of variables declaration //GEN-END:variables /* (non-Javadoc) * @see org.ihtsdo.wizard.I_fastWizard#getData() */ @Override public HashMap<String, Object> getData() throws Exception { if (textField1.getText().trim().equals("")){ throw new Exception ("The name cannot be null."); } HashMap<String, Object> res=new HashMap<String, Object>(); res.put(key, textField1.getText()); return res; } /* (non-Javadoc) * @see org.ihtsdo.wizard.I_fastWizard#setKey(java.lang.String) */ @Override public void setKey(String key) { this.key=key; } /** * Sets the label. * * @param strLabel the new label */ public void setLabel(String strLabel){ label1.setText(strLabel); } }
// // LoginViewController.swift // CBDS Calculator // // Created by Zhang Sheng on 7/23/20. // Copyright ยฉ 2020 Sheng Zhang. All rights reserved. // import UIKit import FirebaseAuth class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var backgroundImage: UIImageView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var welcomeLabel: UILabel! @IBOutlet weak var dontHaveAnAccountLabel: UILabel! @IBOutlet weak var signUpNowButton: UIButton! @IBOutlet weak var emailImage: UIImageView! @IBOutlet weak var passwordImage: UIImageView! @IBOutlet weak var forgetYourPassword: UIButton! @IBOutlet weak var guestLoginButton: UIButton! @IBOutlet weak var statisticsLabel: UIStackView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. emailTextField.delegate = self passwordTextField.delegate = self self.statisticsLabel.layer.borderWidth = 2.0 self.statisticsLabel.layer.cornerRadius = 8 self.spinner.isHidden = true self.spinner.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { emailTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { emailTextField.resignFirstResponder() passwordTextField.resignFirstResponder() return true } @IBAction func signUpNowTapped(_ sender: UIButton) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController vc.modalTransitionStyle = .flipHorizontal vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true) } @IBAction func loginTapped(_ sender: UIButton) { emailTextField.resignFirstResponder() passwordTextField.resignFirstResponder() let error = validateEmailandPassword(emailTextField: emailTextField, passwordTextField: passwordTextField) if error != nil { // show pop up alert message showAlert(title: "Login Failed", message: error!, view: self) } else { // Validate the user email and password using Firebase Auth let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) Auth.auth().signIn(withEmail: email, password: password) { (result, errorFromFirebase) in if let errorFromFirebase = errorFromFirebase { // show pop up alert message showAlert(title: "Login Failed", message: errorFromFirebase.localizedDescription, view: self) } else { // Transition to the NavigationController UIView.animate(withDuration: 1.5, animations: { self.backgroundImage.alpha = 0.2 self.loginButton.alpha = 0.2 self.welcomeLabel.alpha = 0.2 self.dontHaveAnAccountLabel.alpha = 0.2 self.signUpNowButton.alpha = 0.2 self.emailImage.alpha = 0.2 self.passwordImage.alpha = 0.2 self.emailTextField.alpha = 0.2 self.passwordTextField.alpha = 0.2 self.forgetYourPassword.alpha = 0.2 self.guestLoginButton.alpha = 0.2 self.statisticsLabel.alpha = 0.2 self.spinner.isHidden = false self.spinner.startAnimating() }, completion: { done in if done { self.transitionToNavigationController() } }) } } } } @IBAction func guestLoginTapped(_ sender: UIButton) { // Transition to the NavigationController UIView.animate(withDuration: 1.5, animations: { self.backgroundImage.alpha = 0.2 self.loginButton.alpha = 0.2 self.welcomeLabel.alpha = 0.2 self.dontHaveAnAccountLabel.alpha = 0.2 self.signUpNowButton.alpha = 0.2 self.emailImage.alpha = 0.2 self.passwordImage.alpha = 0.2 self.emailTextField.alpha = 0.2 self.passwordTextField.alpha = 0.2 self.forgetYourPassword.alpha = 0.2 self.guestLoginButton.alpha = 0.2 self.statisticsLabel.alpha = 0.2 self.spinner.isHidden = false self.spinner.startAnimating() }, completion: { done in if done { self.transitionToNavigationController() } }) } private func transitionToNavigationController() { let vc = self.storyboard?.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController vc.modalTransitionStyle = .coverVertical vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true) } @IBAction func resetPassword(_ sender: UIButton) { showForgetYourPasswordAlert() } private func showForgetYourPasswordAlert() { let alert = UIAlertController(title: "Reset Your Password", message: "Please enter your email address below. We will send you an email to reset your password", preferredStyle: .alert) alert.addTextField { textField in textField.placeholder = "Email" } let send = UIAlertAction(title: "Send", style: .default) { _ in if let emailTextField = alert.textFields?.first, let email = emailTextField.text { Auth.auth().sendPasswordReset(withEmail: email, completion: nil) } } let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(send) alert.addAction(cancel) present(alert, animated: true, completion: nil) } }
// 199 https://leetcode.com/problems/binary-tree-right-side-view/ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ function TreeNode(val, left, right) { this.val = (val===undefined ? 0 : val) this.left = (left===undefined ? null : left) this.right = (right===undefined ? null : right) } /** * @param {TreeNode} root * @return {number[]} */ // idea: collect the last value of each level const rightSideView = function(root) { const result = []; if (root === null) { return result; } const nodeQueue = [root]; while (nodeQueue.length > 0) { const currentLevelSize = nodeQueue.length; result.push(nodeQueue[0].val); for (let i = 0; i < currentLevelSize; i++) { const shiftedNode = nodeQueue.shift(); const { left, right } = shiftedNode; if (right !== null) { nodeQueue.push(right); } if (left !== null) { nodeQueue.push(left); } } } return result; }; const node15 = new TreeNode(15); const node7 = new TreeNode(7); const node20 = new TreeNode(20, node15, node7); const node9 = new TreeNode(9); const root = new TreeNode(3, node9, node20); const result = rightSideView(root); console.log(result);
/// adult : false /// gender : 0 /// id : 3234630 /// known_for_department : "Acting" /// name : "Sangeeth Shobhan" /// original_name : "Sangeeth Shobhan" /// popularity : 214.068 /// profile_path : "/7Vox31bH7XmgPNJzMKGa4uGyjW8.jpg" /// known_for : [{"adult":false,"backdrop_path":"/jBnnkkXRZ0pV3Tw31Z2ALO638wA.jpg","id":1187075,"title":"MAD","original_language":"te","original_title":"MAD","overview":"Set in an engineering college and revolves around the antics of the students there, primarily the boys, who get a kick out of torturing the hostel warden.","poster_path":"/nDpOmgBfQZwOpFBcgokQGqd74r1.jpg","media_type":"movie","genre_ids":[35,10749,18],"popularity":8.388,"release_date":"2023-10-06","video":false,"vote_average":7,"vote_count":4},{"adult":false,"backdrop_path":"/1jof3bGVg67HLmvRHfTzqb2IODO.jpg","id":138179,"name":"Oka Chinna Family Story","original_language":"te","original_name":"เฐ’เฐ• เฐšเฐฟเฐจเฑเฐจ Family Story","overview":"Mahesh and his mother embark on an adventurous journey filled with hilarious situations as they try to make quick money to repay a huge loan.","poster_path":"/u1Tq2Qqb1oUJ6WSzVJqWk03LzEl.jpg","media_type":"tv","genre_ids":[35,10751],"popularity":7.198,"first_air_date":"2021-11-19","vote_average":7.5,"vote_count":2,"origin_country":["IN"]}] class MovieProfileModel { MovieProfileModel({ bool? adult, num? gender, num? id, String? knownForDepartment, String? name, String? originalName, num? popularity, String? profilePath, List<KnownFor>? knownFor,}){ _adult = adult; _gender = gender; _id = id; _knownForDepartment = knownForDepartment; _name = name; _originalName = originalName; _popularity = popularity; _profilePath = profilePath; _knownFor = knownFor; } MovieProfileModel.fromJson(dynamic json) { _adult = json['adult']; _gender = json['gender']; _id = json['id']; _knownForDepartment = json['known_for_department']; _name = json['name']; _originalName = json['original_name']; _popularity = json['popularity']; _profilePath = json['profile_path']; if (json['known_for'] != null) { _knownFor = []; json['known_for'].forEach((v) { _knownFor?.add(KnownFor.fromJson(v)); }); } } bool? _adult; num? _gender; num? _id; String? _knownForDepartment; String? _name; String? _originalName; num? _popularity; String? _profilePath; List<KnownFor>? _knownFor; MovieProfileModel copyWith({ bool? adult, num? gender, num? id, String? knownForDepartment, String? name, String? originalName, num? popularity, String? profilePath, List<KnownFor>? knownFor, }) => MovieProfileModel( adult: adult ?? _adult, gender: gender ?? _gender, id: id ?? _id, knownForDepartment: knownForDepartment ?? _knownForDepartment, name: name ?? _name, originalName: originalName ?? _originalName, popularity: popularity ?? _popularity, profilePath: profilePath ?? _profilePath, knownFor: knownFor ?? _knownFor, ); bool? get adult => _adult; num? get gender => _gender; num? get id => _id; String? get knownForDepartment => _knownForDepartment; String? get name => _name; String? get originalName => _originalName; num? get popularity => _popularity; String? get profilePath => _profilePath; List<KnownFor>? get knownFor => _knownFor; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['adult'] = _adult; map['gender'] = _gender; map['id'] = _id; map['known_for_department'] = _knownForDepartment; map['name'] = _name; map['original_name'] = _originalName; map['popularity'] = _popularity; map['profile_path'] = _profilePath; if (_knownFor != null) { map['known_for'] = _knownFor?.map((v) => v.toJson()).toList(); } return map; } } /// adult : false /// backdrop_path : "/jBnnkkXRZ0pV3Tw31Z2ALO638wA.jpg" /// id : 1187075 /// title : "MAD" /// original_language : "te" /// original_title : "MAD" /// overview : "Set in an engineering college and revolves around the antics of the students there, primarily the boys, who get a kick out of torturing the hostel warden." /// poster_path : "/nDpOmgBfQZwOpFBcgokQGqd74r1.jpg" /// media_type : "movie" /// genre_ids : [35,10749,18] /// popularity : 8.388 /// release_date : "2023-10-06" /// video : false /// vote_average : 7 /// vote_count : 4 class KnownFor { KnownFor({ bool? adult, String? backdropPath, num? id, String? title, String? originalLanguage, String? originalTitle, String? overview, String? posterPath, String? mediaType, List<num>? genreIds, num? popularity, String? releaseDate, bool? video, num? voteAverage, num? voteCount,}){ _adult = adult; _backdropPath = backdropPath; _id = id; _title = title; _originalLanguage = originalLanguage; _originalTitle = originalTitle; _overview = overview; _posterPath = posterPath; _mediaType = mediaType; _genreIds = genreIds; _popularity = popularity; _releaseDate = releaseDate; _video = video; _voteAverage = voteAverage; _voteCount = voteCount; } KnownFor.fromJson(dynamic json) { _adult = json['adult']; _backdropPath = json['backdrop_path']; _id = json['id']; _title = json['title']; _originalLanguage = json['original_language']; _originalTitle = json['original_title']; _overview = json['overview']; _posterPath = json['poster_path']; _mediaType = json['media_type']; _genreIds = json['genre_ids'] != null ? json['genre_ids'].cast<num>() : []; _popularity = json['popularity']; _releaseDate = json['release_date']; _video = json['video']; _voteAverage = json['vote_average']; _voteCount = json['vote_count']; } bool? _adult; String? _backdropPath; num? _id; String? _title; String? _originalLanguage; String? _originalTitle; String? _overview; String? _posterPath; String? _mediaType; List<num>? _genreIds; num? _popularity; String? _releaseDate; bool? _video; num? _voteAverage; num? _voteCount; KnownFor copyWith({ bool? adult, String? backdropPath, num? id, String? title, String? originalLanguage, String? originalTitle, String? overview, String? posterPath, String? mediaType, List<num>? genreIds, num? popularity, String? releaseDate, bool? video, num? voteAverage, num? voteCount, }) => KnownFor( adult: adult ?? _adult, backdropPath: backdropPath ?? _backdropPath, id: id ?? _id, title: title ?? _title, originalLanguage: originalLanguage ?? _originalLanguage, originalTitle: originalTitle ?? _originalTitle, overview: overview ?? _overview, posterPath: posterPath ?? _posterPath, mediaType: mediaType ?? _mediaType, genreIds: genreIds ?? _genreIds, popularity: popularity ?? _popularity, releaseDate: releaseDate ?? _releaseDate, video: video ?? _video, voteAverage: voteAverage ?? _voteAverage, voteCount: voteCount ?? _voteCount, ); bool? get adult => _adult; String? get backdropPath => _backdropPath; num? get id => _id; String? get title => _title; String? get originalLanguage => _originalLanguage; String? get originalTitle => _originalTitle; String? get overview => _overview; String? get posterPath => _posterPath; String? get mediaType => _mediaType; List<num>? get genreIds => _genreIds; num? get popularity => _popularity; String? get releaseDate => _releaseDate; bool? get video => _video; num? get voteAverage => _voteAverage; num? get voteCount => _voteCount; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['adult'] = _adult; map['backdrop_path'] = _backdropPath; map['id'] = _id; map['title'] = _title; map['original_language'] = _originalLanguage; map['original_title'] = _originalTitle; map['overview'] = _overview; map['poster_path'] = _posterPath; map['media_type'] = _mediaType; map['genre_ids'] = _genreIds; map['popularity'] = _popularity; map['release_date'] = _releaseDate; map['video'] = _video; map['vote_average'] = _voteAverage; map['vote_count'] = _voteCount; return map; } }
package me.shu.exercise.zookeeper; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ใ€ŠZooKeeper ไบ‹ไปถ็ฑปๅž‹่ฏฆ่งฃใ€‹ * * @author nileader/nileader@gmail.com * */ public class AllZooKeeperWatcher implements Watcher { private static final Logger LOG = LoggerFactory .getLogger(AllZooKeeperWatcher.class); AtomicInteger seq = new AtomicInteger(); private static final int SESSION_TIMEOUT = 10000; private static final String CONNECTION_STRING = "hk-ubuntu.cloudapp.net:2181"; private static final String ZK_PATH = "/shu/test"; private static final String CHILDREN_PATH = "/shu/test/data"; private ZooKeeper zk = null; private CountDownLatch connectedSemaphore = new CountDownLatch(1); /** * ๅˆ›ๅปบZK่ฟžๆŽฅ * * @param connectString * ZKๆœๅŠกๅ™จๅœฐๅ€ๅˆ—่กจ * @param sessionTimeout * Session่ถ…ๆ—ถๆ—ถ้—ด */ public void createConnection(String connectString, int sessionTimeout) { this.releaseConnection(); try { zk = new ZooKeeper(connectString, sessionTimeout, this); LOG.info("ๅผ€ๅง‹่ฟžๆŽฅZKๆœๅŠกๅ™จ"); connectedSemaphore.await(); } catch (Exception e) { e.printStackTrace(); } } /** * ๅ…ณ้—ญZK่ฟžๆŽฅ */ public void releaseConnection() { if (this.zk != null) { try { this.zk.close(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * ๅˆ›ๅปบ่Š‚็‚น * * @param path * ่Š‚็‚นpath * @param data * ๅˆๅง‹ๆ•ฐๆฎๅ†…ๅฎน * @return */ public boolean createPath(String path, String data) { try { this.zk.exists(path, true); LOG.info("่Š‚็‚นๅˆ›ๅปบๆˆๅŠŸ, Path: " + this.zk.create(path, // data.getBytes(), // Ids.OPEN_ACL_UNSAFE, // CreateMode.PERSISTENT) + ", content: " + data); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * ่ฏปๅ–ๆŒ‡ๅฎš่Š‚็‚นๆ•ฐๆฎๅ†…ๅฎน * * @param path * ่Š‚็‚นpath * @return */ public String readData(String path, boolean needWatch) { try { return new String(this.zk.getData(path, needWatch, null)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * ๆ›ดๆ–ฐๆŒ‡ๅฎš่Š‚็‚นๆ•ฐๆฎๅ†…ๅฎน * * @param path * ่Š‚็‚นpath * @param data * ๆ•ฐๆฎๅ†…ๅฎน * @return */ public boolean writeData(String path, String data) { try { LOG.info("ๆ›ดๆ–ฐๆ•ฐๆฎๆˆๅŠŸ๏ผŒpath๏ผš" + path + ", stat: " + this.zk.setData(path, data.getBytes(), -1)); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * ๅˆ ้™คๆŒ‡ๅฎš่Š‚็‚น * * @param path * ่Š‚็‚นpath */ public void deleteNode(String path) { try { if (this.zk.exists(path, true) != null) { this.zk.delete(path, -1); LOG.info("ๅˆ ้™ค่Š‚็‚นๆˆๅŠŸ๏ผŒpath๏ผš" + path); } } catch (Exception e) { e.printStackTrace(); } } /** * ๅˆ ้™คๆŒ‡ๅฎš่Š‚็‚น * * @param path * ่Š‚็‚นpath */ public Stat exists(String path, boolean needWatch) { try { return this.zk.exists(path, needWatch); } catch (Exception e) { return null; } } /** * ่Žทๅ–ๅญ่Š‚็‚น * * @param path * ่Š‚็‚นpath */ private List<String> getChildren(String path, boolean needWatch) { try { return this.zk.getChildren(path, needWatch); } catch (Exception e) { return null; } } public void deleteAllTestPath() { this.deleteNode(CHILDREN_PATH); this.deleteNode(ZK_PATH); } @Test public void all() throws InterruptedException { AllZooKeeperWatcher sample = new AllZooKeeperWatcher(); sample.createConnection(CONNECTION_STRING, SESSION_TIMEOUT); // ๆธ…็†่Š‚็‚น sample.deleteAllTestPath(); if (sample.createPath(ZK_PATH, System.currentTimeMillis() + "")) { // ่ฏปๅ–ๆ•ฐๆฎ sample.readData(ZK_PATH, true); // ่ฏปๅ–ๅญ่Š‚็‚น sample.getChildren(ZK_PATH, true); // ๆ›ดๆ–ฐๆ•ฐๆฎ sample.writeData(ZK_PATH, System.currentTimeMillis() + ""); // ๅˆ›ๅปบๅญ่Š‚็‚น sample.createPath(CHILDREN_PATH, System.currentTimeMillis() + ""); } // ๆธ…็†่Š‚็‚น sample.deleteAllTestPath(); sample.releaseConnection(); } /** * ๆ”ถๅˆฐๆฅ่‡ชServer็š„Watcher้€š็ŸฅๅŽ็š„ๅค„็†ใ€‚ */ @Override public void process(WatchedEvent event) { if (event == null) { return; } // ่ฟžๆŽฅ็Šถๆ€ KeeperState keeperState = event.getState(); // ไบ‹ไปถ็ฑปๅž‹ EventType eventType = event.getType(); // ๅ—ๅฝฑๅ“็š„path String path = event.getPath(); String logPrefix = "ใ€Watcher-" + this.seq.incrementAndGet() + "ใ€‘"; LOG.info(logPrefix + "ๆ”ถๅˆฐWatcher้€š็Ÿฅ"); LOG.info(logPrefix + "่ฟžๆŽฅ็Šถๆ€:\t" + keeperState.toString()); LOG.info(logPrefix + "ไบ‹ไปถ็ฑปๅž‹:\t" + eventType.toString()); if (KeeperState.SyncConnected == keeperState) { // ๆˆๅŠŸ่ฟžๆŽฅไธŠZKๆœๅŠกๅ™จ if (EventType.None == eventType) { LOG.info(logPrefix + "ๆˆๅŠŸ่ฟžๆŽฅไธŠZKๆœๅŠกๅ™จ"); connectedSemaphore.countDown(); } else if (EventType.NodeCreated == eventType) { LOG.info(logPrefix + "่Š‚็‚นๅˆ›ๅปบ"); this.exists(path, true); } else if (EventType.NodeDataChanged == eventType) { LOG.info(logPrefix + "่Š‚็‚นๆ•ฐๆฎๆ›ดๆ–ฐ"); LOG.info(logPrefix + "ๆ•ฐๆฎๅ†…ๅฎน: " + this.readData(ZK_PATH, true)); } else if (EventType.NodeChildrenChanged == eventType) { LOG.info(logPrefix + "ๅญ่Š‚็‚นๅ˜ๆ›ด"); LOG.info(logPrefix + "ๅญ่Š‚็‚นๅˆ—่กจ๏ผš" + this.getChildren(ZK_PATH, true)); } else if (EventType.NodeDeleted == eventType) { LOG.info(logPrefix + "่Š‚็‚น " + path + " ่ขซๅˆ ้™ค"); } } else if (KeeperState.Disconnected == keeperState) { LOG.info(logPrefix + "ไธŽZKๆœๅŠกๅ™จๆ–ญๅผ€่ฟžๆŽฅ"); } else if (KeeperState.AuthFailed == keeperState) { LOG.info(logPrefix + "ๆƒ้™ๆฃ€ๆŸฅๅคฑ่ดฅ"); } else if (KeeperState.Expired == keeperState) { LOG.info(logPrefix + "ไผš่ฏๅคฑๆ•ˆ"); } LOG.info("--------------------------------------------"); } }
import { useTheme } from "next-themes"; import React, { useEffect, useRef, useState } from "react"; import { IoMdAdd } from "react-icons/io"; import { GrPowerReset } from "react-icons/gr"; import { MdOutlineCancel } from "react-icons/md"; import { AiOutlineCopy } from "react-icons/ai"; import toast, { Toaster } from "react-hot-toast"; import { palette } from "./tailwindColorPalette"; import { useOutsideClick } from "hooks/useOutsideClick"; import styles from "./styles.module.css"; import { FaRandom } from "react-icons/fa"; export const GenerateBoxShadow = React.forwardRef((props, ref) => { let defaultBoxShadow = { id: new Date().getTime(), horizontalOffset: 0, verticalOffset: 20, blur: 20, spread: 10, color: "#00000024", }; const [boxShadow, setBoxShadow] = useState([defaultBoxShadow]); const [activeShadow, setActiveShadow] = useState(null); const [modal, setModal] = useState(false); const boxRef = useRef(); useOutsideClick(boxRef, () => setModal(false)); const generateShadow = () => { let final = []; boxShadow.forEach((el) => { let temp = `${el.horizontalOffset}px ` + `${el.verticalOffset}px ` + `${el.blur}px ` + `${el.spread}px ` + `${el.color}`; temp = el.inset ? `inset ${temp}` : temp; final.push(temp); }); return final.join(","); }; const onChangeHandler = (action, data) => { switch (action) { case "horizontalOffset": findAndUpdateValue("horizontalOffset", data); break; case "verticalOffset": findAndUpdateValue("verticalOffset", data); break; case "blur": findAndUpdateValue("blur", data); break; case "spread": findAndUpdateValue("spread", data); break; case "inset": findAndUpdateValue("inset", data); break; case "color": findAndUpdateValue("color", data); break; case "delete": handleShadowDelete(data); break; case "color-button": // open modal setActiveShadow(data); setModal(true); break; case "color-select": handleColorSelect(data); break; default: break; } }; const handleColorSelect = (selectedColor) => { // let data = { ...activeShadow, updatedValue: selectedColor, }; findAndUpdateValue("color", data); setActiveShadow(null); setModal(false); }; const handleShadowDelete = (shadowElement) => { let temp = boxShadow.filter((el) => el.id !== shadowElement.id); setBoxShadow(temp); }; const addShadowLayer = () => { // box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; let temp = [...boxShadow]; temp.push({ ...defaultBoxShadow, id: new Date().getTime(), horizontalOffset: 0, verticalOffset: 3, blur: 8, spread: 0, color: "#00000024", }); setBoxShadow([...temp]); }; const findAndUpdateValue = (key, data) => { let target = boxShadow.map((el) => { if (el.id === data.id) { el[key] = data.updatedValue; } return el; }); setBoxShadow(target); }; const copyToClipboard = (text) => { var textArea = document.createElement("textarea"); textArea.value = text; // Avoid scrolling to bottom textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.position = "fixed"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand("copy"); var msg = successful ? "successful" : "unsuccessful"; } catch (err) { console.error("Fallback: Oops, unable to copy", err); } document.body.removeChild(textArea); notify("Copied Successfully!"); }; const copyVanillaCSS = () => { let generatedShadow = `box-shadow: ${generateShadow()}`; copyToClipboard(generatedShadow); }; const generateTailwindCSSJIT = () => { let probableOutput = `box-shadow: ${generateShadow()}`; if (probableOutput.includes("box-shadow:")) { probableOutput = probableOutput.split("box-shadow:")[1]; } if (probableOutput.includes(";")) { probableOutput = probableOutput.split(";")[0]; } let finalOutput = probableOutput.trim().split(" ").join("_"); finalOutput = `shadow-[${finalOutput}]`; copyToClipboard(finalOutput); }; const handleReset = () => { setBoxShadow([defaultBoxShadow]); }; const notify = (message) => { toast(message || "Copied successfully!", { duration: 4000, position: "top-center", // Styling style: {}, className: "", // Custom Icon icon: "๐Ÿ‘", // Change colors of success/error/loading icon iconTheme: { primary: "#000", secondary: "#fff", }, // Aria ariaProps: { role: "status", "aria-live": "polite", }, }); }; const handleRandomize = () => { let temp = [...boxShadow]; temp.forEach((el) => { el.horizontalOffset = Math.floor(Math.random() * 41) - 20; el.verticalOffset = Math.floor(Math.random() * 41) - 20; el.blur = Math.floor(Math.random() * 50); el.spread = Math.floor(Math.random() * 50); el.color = randomColor(); }); setBoxShadow(temp); }; const randomColor = () => { let color = "#"; let letters = "0123456789ABCDEF"; for (let i = 0; i < 8; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }; return ( <div ref={ref} className="bg-gray-50 w-full px-4 lg:px-20 min-h-screen relative mb-20" > <Toaster /> {modal && ( <PaletteModal onChangeHandler={onChangeHandler} palette={palette} ref={boxRef} /> )} <div className="pt-10 pb-20"> <h2 className="font-bold text-xl md:text-3xl tracking-normal mb-4 text-black dark:text-black mx-auto mt-4 text-center "> Box Shadow Generator for{" "} <span className="bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500"> TailwindCSS </span> </h2> <h4 className="prose text-gray-700 font-light dark:text-gray-400 text-center mx-auto"> A free tool that helps you generate box shadows for TailwindCSS (JIT) and Vanilla CSS with ease. </h4> </div> <div className="w-fullitems-center flex flex-col lg:flex-row"> <div className="w-full lg:w-[60%]"> <div class="relative flex flex-col justify-center py-6 sm:py-12"> <div class="absolute inset-0 bg-center [mask-image:linear-gradient(180deg,white,rgba(255,255,255,0))]"></div> <div style={{ boxShadow: generateShadow(), }} class="relative bg-white px-6 pt-10 pb-8 ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10" > <div class="mx-auto max-w-md"> <img src="/avatar-new.png" alt="Manu Arora" className="h-8 rounded-full" /> <div class="divide-y divide-gray-300/50"> <div class="space-y-6 py-8 text-base leading-7 text-gray-600"> <p> Add shadow to this box with the controls on the side panel. This box mimics a card box that you might have on your website. </p> <p> Add shadow layers, change colors and play with the controls. </p> </div> <div class="pt-8 text-base font-semibold leading-7"> <p class="text-gray-900">Want beautiful shadows already?</p> <p> <button onClick={() => window && window.scrollTo(0, 0)} href="https://tailwindcss.com/docs" class="text-sky-500 hover:text-sky-600" > Explore the presets </button> </p> </div> </div> </div> </div> </div> </div> <div className="h-full w-full lg:w-[40%] flex flex-col"> <div className="flex flex-row justify-between flex-wrap mb-2 text-xs space-x-2 pb-4 px-2"> <button onClick={addShadowLayer} className="text-white flex flex-row space-x-1 items-center font-light bg-zinc-500 px-2 py-1 rounded-md hover:bg-zinc-600" > <IoMdAdd className="stroke-[10px]" /> Add Shadow Layer </button> <div className="flex flex-row space-x-2"> <button onClick={handleRandomize} className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200" > <FaRandom className="stroke-[1px] mr-2" /> Randomize </button> <button onClick={handleReset} className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200" > <GrPowerReset className="stroke-[10px] mr-2" /> Reset </button> <button onClick={copyVanillaCSS} className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200" > <AiOutlineCopy className="stroke-[10px] mr-2" /> Vanilla CSS </button> <button onClick={generateTailwindCSSJIT} className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200" > <AiOutlineCopy className="stroke-[10px] mr-2" /> Tailwind JIT </button> </div> </div> <div className="text-black palette rounded-md px-2 h-[30rem] overflow-y-auto space-y-4"> {boxShadow.map((el, idx) => ( <FormElement shadowElement={el} onChangeHandler={onChangeHandler} key={el.id} /> ))} </div> </div> </div> </div> ); }); const FormElement = ({ onChangeHandler, shadowElement }) => { return ( <div className="relative bg-white rounded-lg shadow-lg shadow-black/10 py-4 px-6"> <button className="absolute right-2 top-2" onClick={() => onChangeHandler("delete", shadowElement)} > <MdOutlineCancel className="text-slate-500 hover:text-red-500" /> </button> <div className="flex flex-row space-x-2 mb-2"> <label className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white" htmlFor={`horizontalOffset-${shadowElement.id}`} > X </label> <input value={shadowElement.horizontalOffset} className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700" id={`horizontalOffset-${shadowElement.id}`} type="number" onChange={(e) => onChangeHandler("horizontalOffset", { updatedValue: e.target.value, ...shadowElement, }) } /> <p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white"> {shadowElement.horizontalOffset}px Horizontal Offset </p> </div> <div className="flex flex-row space-x-2 mb-2"> <label className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white" htmlFor={`verticalOffset-${shadowElement.id}`} > Y </label> <input value={shadowElement.verticalOffset} className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700" id={`verticalOffset-${shadowElement.id}`} type="number" onChange={(e) => onChangeHandler("verticalOffset", { updatedValue: e.target.value, ...shadowElement, }) } /> <p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white"> {shadowElement.verticalOffset}px Vertical Offset </p> </div> <div className="flex flex-row space-x-2 mb-2"> <label className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white" htmlFor={`blur-${shadowElement.id}`} > B </label> <input min="0" value={shadowElement.blur} className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700" id={`blur-${shadowElement.id}`} type="number" onChange={(e) => onChangeHandler("blur", { updatedValue: e.target.value, ...shadowElement, }) } /> <p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white"> {shadowElement.blur}px blur </p> </div> <div className="flex flex-row space-x-2 mb-2"> <label className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white" htmlFor={`spread-${shadowElement.id}`} > S </label> <input min="0" value={shadowElement.spread} className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700" id={`spread-${shadowElement.id}`} type="number" onChange={(e) => onChangeHandler("spread", { updatedValue: e.target.value, ...shadowElement, }) } /> <p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white"> {shadowElement.spread}px spread </p> </div> <div className="flex flex-row space-x-2 mb-2"> <label className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white" htmlFor={`color-${shadowElement.id}`} > C </label> <input value={shadowElement.color} className="inline-block w-28 shadow rounded-md px-2 uppercase text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700" id={`color-${shadowElement.id}`} type="text" onChange={(e) => onChangeHandler("color", { updatedValue: e.target.value, ...shadowElement, }) } /> <button onClick={() => onChangeHandler("color-button", shadowElement)} className="p-3 w-10 rounded-md" style={{ backgroundColor: shadowElement.color }} ></button> </div> <div className="flex flex-row space-x-2 mb-2"> <div class={styles["checkbox-wrapper-1"]}> <input id={`inset-${shadowElement.id}`} class={styles.substituted} type="checkbox" aria-hidden="true" onChange={(e) => onChangeHandler("inset", { updatedValue: e.target.checked, ...shadowElement, }) } /> <label className="text-base" htmlFor={`inset-${shadowElement.id}`}> Inset </label> </div> {/* <input min="0" value={shadowElement.inset} className="accent-sky-500 px-4 py-4 inline-block" id={`inset-${shadowElement.id}`} type="checkbox" onChange={(e) => onChangeHandler("inset", { updatedValue: e.target.checked, ...shadowElement, }) } /> */} </div> </div> ); }; const PaletteModal = React.forwardRef((props, ref) => { const { onChangeHandler, palette } = props; return ( <div className="h-full w-full absolute z-20 inset-0 flex items-center justify-center bg-black/10"> <div ref={ref} className="h-3/4 w-2/4 rounded-md bg-white overflow-y-auto p-4 shadow" > <h1 className="font-bold text-base text-center text-zinc-700 mb-4"> Tailwind CSS Color Palette </h1> {palette.map((pal, idx) => ( <div className=" mb-2" key={pal.paletteName}> <h4 className="font-bold text-zinc-700 mx-4">{pal.paletteName}</h4> <div className="flex flex-row flex-wrap"> {pal.swatches.map((sw, idx) => ( <div> <button onClick={() => onChangeHandler("color-select", sw.color)} className="h-10 w-20 rounded-md mx-2 my-1" style={{ backgroundColor: sw.color }} ></button> <p className="text-zinc-400 text-[0.60rem] mx-2 font-light"> <span className="font-normal text-zinc-600">{sw.name}</span>{" "} - {sw.color} </p> </div> ))} </div> </div> ))} </div> </div> ); });
3 # The Location Class class Location: # Constructor def __init__(self, name): self.name = name self.power = 0 self.units = [] # ACTIONS : Sometimes even our territory values must be changed when Actions occur, we do this in these functions # ----------------------------------------------------------------------- # For when a unit is bought and placed here def purchaseUnit(self, un): self.power += un.getPower() self.units.append(un) self.owner = un.getOwner() def move_from(self, un): self.power -= un.getPower() self.units.remove(un) if len(self.units) == 0: self.owner = None return True return False def move_to(self, un): self.power += un.getPower() self.units.append(un) un.move(self) if len(self.units) == 1: self.owner = un.getOwner() return True return False # Function to defend from player pl's attacking unit un def defend(self, att_pow): # So long as the attacking power is not brought to 0, then the defenders will keep fighting while att_pow > 0 and self.power > 0: # Trade the first unit defender = self.units[0] def_pow = defender.getPower() # If the defender is stronger, then it just takes the damage if def_pow > att_pow: defender.takeDamage(att_pow) # If not then it will die else: self.owner.loseUnit(self, defender) att_pow -= def_pow def loseUnit(self, un): self.power -= un.getPower() self.units.remove(un) if len(self.units) == 0: self.owner = None return True return False class Coast(Location): def __init__(self, name, data, ter): super().__init__(name, data["sea_neighbors"], data["sea_button"]) self.territory = ter def getTerritory(self): return self.territory def navPower(self): return sum([un.getPower() for un in self.units]) class Territory(Location): def __init__(self, name, data): super().__init__(name, data["neighbors"], data["button"].center) self.coast = Coast(name, data, self) self.button = data["button"] self.border = data["border"] self.resources = data["resources"] self.turn_claimed = None def getCoast(self): return self.coast def getButton(self): return self.button def getBorder(self): return self.border def getResources(self): return self.resources def isClaimed(self, turn): if self.turn_claimed is not None: return self.turn_claimed == 0 or self.turn_claimed <= turn - 3 return False def attPower(self): return sum([un.getPower() for un in self.units if not un.isDefensive() and not un.isArial()]) def defPower(self): return sum([un.getPower() for un in self.units if un.isDefensive()]) def ariPower(self): return sum([un.getPower() for un in self.units if un.isArial()]) # ACTIONS : Sometimes even our territory values must be changed when Actions occur, we do this in these functions # ----------------------------------------------------------------------- # Function to begin the game calle by this territories new owner def startGame(self, owner, un): self.owner = owner self.turn_claimed = 0 self.power += un.getPower() self.units.append(un) def move_from(self, un): if super(Territory, self).move_from(un): self.turn_claimed = None return True return False def loseUnit(self, un): if super(Territory, self).loseUnit(un): self.turn_claimed = None return True return False # Turn a integer into a Roman Numeral def roman(number): ret_val = "" num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] sym = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] i = 12 while number: div = number // num[i] number %= num[i] while div: ret_val += sym[i] div -= 1 i -= 1 return ret_val
var CG = (function(CG) { let g_width, g_x, g_y, g_z, g_x0, g_y0; class Tetraedro{ /** * @param {WebGLRenderingContext} gl * @param {Number[]} color * @param {Number} width * @param {Matrix4} initial_transform * Constructor de tetraedro */ constructor(gl, color, width, initial_transform) { g_width = (width || 1); let anguloT = 2 * Math.PI/3; g_x = width*2*Math.sqrt(2)/3; g_y = 0; g_z = -width/3; g_x0 = g_x * Math.cos(anguloT) + g_y * Math.sin(anguloT); g_y0 = -g_x * Math.sin(anguloT) + g_y * Math.cos(anguloT); this.initial_transform = initial_transform || new CG.Matrix4(); this.positionbuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionbuffer); let vertices = this.getVertices(); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); this.color = color; // buffer de normales this.normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer); let normals = this.getNormals(vertices); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW); this.num_elements = vertices.length/3; } /** * @param {WebGLRenderingContext} gl * @param {GLint} positionAttributeLocation * @param {WebGLUniformLocation} colorUniformLocation * @param {WebGLUniformLocation} PVM_matrixLocation * @param {Matrix4} projectionViewMatrix * Funciรณn que dibuja el objeto geomรฉtrico usando el color asignado */ draw(gl, positionAttributeLocation, normalAttributeLocation, colorUniformLocation, PVM_matrixLocation, VM_matrixLocation, projectionMatrix, viewMatrix) { // buffer de posiciones gl.enableVertexAttribArray(positionAttributeLocation); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionbuffer); gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0); // Buffer de normales gl.enableVertexAttribArray(normalAttributeLocation); gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer); gl.vertexAttribPointer(normalAttributeLocation, 3, gl.FLOAT, false, 0, 0); // Color de la figura gl.uniform4fv(colorUniformLocation, this.color); // VM_MatrixLocation let viewModelMatrix = CG.Matrix4.multiply(viewMatrix, this.initial_transform); gl.uniformMatrix4fv(VM_matrixLocation, false, viewModelMatrix.toArray()); // PVM let projectionViewModelMatrix = CG.Matrix4.multiply(projectionMatrix, viewModelMatrix); gl.uniformMatrix4fv(PVM_matrixLocation, false, projectionViewModelMatrix.toArray()); // Dibujado gl.drawArrays(gl.TRIANGLES, 0, this.num_elements); } /** * @param {WebGLRenderingContext} gl * @param {GLint} positionAttributeLocation * @param {WebGLUniformLocation} colorUniformLocation * @param {WebGLUniformLocation} PVM_matrixLocation * @param {Matrix4} projectionViewMatrix * Funciรณn que dibuja el objeto geomรฉtrico en modo wireframe */ drawWireframe(gl, positionAttributeLocation, colorUniformLocation, PVM_matrixLocation, projectionViewMatrix) { let positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); let vertices = this.getVerticesW(); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); let indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); let faces = this.getFaces(); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(faces), gl.STATIC_DRAW); let num_elementsL = faces.length; gl.enableVertexAttribArray(positionAttributeLocation); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0); gl.uniform4fv(colorUniformLocation, [0,0,0,1]); let projectionViewModelMatrix = CG.Matrix4.multiply(projectionViewMatrix, this.initial_transform); gl.uniformMatrix4fv(PVM_matrixLocation, false, projectionViewModelMatrix.toArray()); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.drawElements(gl.LINE_STRIP, num_elementsL, gl.UNSIGNED_SHORT, 0); } /** * Funciรณn que devuelve un arreglo con los vรฉrtices del tetraedro. */ getVerticesW() { return [ 0, 0, g_width, /*0*/ g_x0, g_y0, g_z, /*1*/ g_x0, -g_y0, g_z, /*2*/ g_x, g_y, g_z /*3*/ ]; } /** * Funciรณn que devuelve el arreglo de vรฉrtices para ser usado por drawArrays */ getVertices() { return [ 0, 0, g_width, /*0*/ g_x0, g_y0, g_z, /*1*/ g_x, g_y, g_z /*3*/, 0, 0, g_width, /*0*/ g_x0, -g_y0, g_z, /*2*/ g_x0, g_y0, g_z, /*1*/ 0, 0, g_width, /*0*/ g_x, g_y, g_z, /*3*/ g_x0, -g_y0, g_z, /*2*/ g_x0, g_y0, g_z, /*1*/ g_x0, -g_y0, g_z, /*2*/ g_x, g_y, g_z /*3*/ ]; } /** * Funciรณn que devuelve las normales para el tetraedro */ getNormals(vertices) { let normals = []; let v1 = new CG.Vector3(); let v2 = new CG.Vector3(); let v3 = new CG.Vector3(); let n; //Reconstrucciรณn de vรฉrtices for (let i = 0; i < vertices.length; i+=9) { v1.set(vertices[i ], vertices[i+1], vertices[i+2]); v2.set(vertices[i+3], vertices[i+4], vertices[i+5]); v3.set(vertices[i+6], vertices[i+7], vertices[i+8]); // Cรกlculo de la normal n = CG.Vector3.cross(CG.Vector3.substract(v1, v2), CG.Vector3.substract(v2, v3)).normalize(); normals.push( n.x, n.y, n.z, n.x, n.y, n.z, n.x, n.y, n.z ); } return normals; } /** * Funciรณn que devuelve las caras de la figura */ getFaces() { return [ 3, 1, 0, 0, 1, 2, 2, 0, 3, 3, 2, 1 ]; } } CG.Tetraedro = Tetraedro; return CG; })(CG || {});
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { HttpResponse } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { FormBuilder } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of, Subject, from } from 'rxjs'; import { IVol } from 'app/entities/vol/vol.model'; import { VolService } from 'app/entities/vol/service/vol.service'; import { IHotel } from 'app/entities/hotel/hotel.model'; import { HotelService } from 'app/entities/hotel/service/hotel.service'; import { IActivite } from 'app/entities/activite/activite.model'; import { ActiviteService } from 'app/entities/activite/service/activite.service'; import { IVoyageur } from 'app/entities/voyageur/voyageur.model'; import { VoyageurService } from 'app/entities/voyageur/service/voyageur.service'; import { IReservation } from '../reservation.model'; import { ReservationService } from '../service/reservation.service'; import { ReservationFormService } from './reservation-form.service'; import { ReservationUpdateComponent } from './reservation-update.component'; describe('Reservation Management Update Component', () => { let comp: ReservationUpdateComponent; let fixture: ComponentFixture<ReservationUpdateComponent>; let activatedRoute: ActivatedRoute; let reservationFormService: ReservationFormService; let reservationService: ReservationService; let volService: VolService; let hotelService: HotelService; let activiteService: ActiviteService; let voyageurService: VoyageurService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([]), ReservationUpdateComponent], providers: [ FormBuilder, { provide: ActivatedRoute, useValue: { params: from([{}]), }, }, ], }) .overrideTemplate(ReservationUpdateComponent, '') .compileComponents(); fixture = TestBed.createComponent(ReservationUpdateComponent); activatedRoute = TestBed.inject(ActivatedRoute); reservationFormService = TestBed.inject(ReservationFormService); reservationService = TestBed.inject(ReservationService); volService = TestBed.inject(VolService); hotelService = TestBed.inject(HotelService); activiteService = TestBed.inject(ActiviteService); voyageurService = TestBed.inject(VoyageurService); comp = fixture.componentInstance; }); describe('ngOnInit', () => { it('Should call Vol query and add missing value', () => { const reservation: IReservation = { id: 456 }; const vols: IVol[] = [{ id: 22849 }]; reservation.vols = vols; const volCollection: IVol[] = [{ id: 17106 }]; jest.spyOn(volService, 'query').mockReturnValue(of(new HttpResponse({ body: volCollection }))); const additionalVols = [...vols]; const expectedCollection: IVol[] = [...additionalVols, ...volCollection]; jest.spyOn(volService, 'addVolToCollectionIfMissing').mockReturnValue(expectedCollection); activatedRoute.data = of({ reservation }); comp.ngOnInit(); expect(volService.query).toHaveBeenCalled(); expect(volService.addVolToCollectionIfMissing).toHaveBeenCalledWith(volCollection, ...additionalVols.map(expect.objectContaining)); expect(comp.volsSharedCollection).toEqual(expectedCollection); }); it('Should call Hotel query and add missing value', () => { const reservation: IReservation = { id: 456 }; const hotels: IHotel[] = [{ id: 4692 }]; reservation.hotels = hotels; const hotelCollection: IHotel[] = [{ id: 17597 }]; jest.spyOn(hotelService, 'query').mockReturnValue(of(new HttpResponse({ body: hotelCollection }))); const additionalHotels = [...hotels]; const expectedCollection: IHotel[] = [...additionalHotels, ...hotelCollection]; jest.spyOn(hotelService, 'addHotelToCollectionIfMissing').mockReturnValue(expectedCollection); activatedRoute.data = of({ reservation }); comp.ngOnInit(); expect(hotelService.query).toHaveBeenCalled(); expect(hotelService.addHotelToCollectionIfMissing).toHaveBeenCalledWith( hotelCollection, ...additionalHotels.map(expect.objectContaining), ); expect(comp.hotelsSharedCollection).toEqual(expectedCollection); }); it('Should call Activite query and add missing value', () => { const reservation: IReservation = { id: 456 }; const activites: IActivite[] = [{ id: 18204 }]; reservation.activites = activites; const activiteCollection: IActivite[] = [{ id: 3143 }]; jest.spyOn(activiteService, 'query').mockReturnValue(of(new HttpResponse({ body: activiteCollection }))); const additionalActivites = [...activites]; const expectedCollection: IActivite[] = [...additionalActivites, ...activiteCollection]; jest.spyOn(activiteService, 'addActiviteToCollectionIfMissing').mockReturnValue(expectedCollection); activatedRoute.data = of({ reservation }); comp.ngOnInit(); expect(activiteService.query).toHaveBeenCalled(); expect(activiteService.addActiviteToCollectionIfMissing).toHaveBeenCalledWith( activiteCollection, ...additionalActivites.map(expect.objectContaining), ); expect(comp.activitesSharedCollection).toEqual(expectedCollection); }); it('Should call Voyageur query and add missing value', () => { const reservation: IReservation = { id: 456 }; const voyageur: IVoyageur = { id: 25612 }; reservation.voyageur = voyageur; const voyageurCollection: IVoyageur[] = [{ id: 4244 }]; jest.spyOn(voyageurService, 'query').mockReturnValue(of(new HttpResponse({ body: voyageurCollection }))); const additionalVoyageurs = [voyageur]; const expectedCollection: IVoyageur[] = [...additionalVoyageurs, ...voyageurCollection]; jest.spyOn(voyageurService, 'addVoyageurToCollectionIfMissing').mockReturnValue(expectedCollection); activatedRoute.data = of({ reservation }); comp.ngOnInit(); expect(voyageurService.query).toHaveBeenCalled(); expect(voyageurService.addVoyageurToCollectionIfMissing).toHaveBeenCalledWith( voyageurCollection, ...additionalVoyageurs.map(expect.objectContaining), ); expect(comp.voyageursSharedCollection).toEqual(expectedCollection); }); it('Should update editForm', () => { const reservation: IReservation = { id: 456 }; const vols: IVol = { id: 10947 }; reservation.vols = [vols]; const hotels: IHotel = { id: 5679 }; reservation.hotels = [hotels]; const activites: IActivite = { id: 13150 }; reservation.activites = [activites]; const voyageur: IVoyageur = { id: 9098 }; reservation.voyageur = voyageur; activatedRoute.data = of({ reservation }); comp.ngOnInit(); expect(comp.volsSharedCollection).toContain(vols); expect(comp.hotelsSharedCollection).toContain(hotels); expect(comp.activitesSharedCollection).toContain(activites); expect(comp.voyageursSharedCollection).toContain(voyageur); expect(comp.reservation).toEqual(reservation); }); }); describe('save', () => { it('Should call update service on save for existing entity', () => { // GIVEN const saveSubject = new Subject<HttpResponse<IReservation>>(); const reservation = { id: 123 }; jest.spyOn(reservationFormService, 'getReservation').mockReturnValue(reservation); jest.spyOn(reservationService, 'update').mockReturnValue(saveSubject); jest.spyOn(comp, 'previousState'); activatedRoute.data = of({ reservation }); comp.ngOnInit(); // WHEN comp.save(); expect(comp.isSaving).toEqual(true); saveSubject.next(new HttpResponse({ body: reservation })); saveSubject.complete(); // THEN expect(reservationFormService.getReservation).toHaveBeenCalled(); expect(comp.previousState).toHaveBeenCalled(); expect(reservationService.update).toHaveBeenCalledWith(expect.objectContaining(reservation)); expect(comp.isSaving).toEqual(false); }); it('Should call create service on save for new entity', () => { // GIVEN const saveSubject = new Subject<HttpResponse<IReservation>>(); const reservation = { id: 123 }; jest.spyOn(reservationFormService, 'getReservation').mockReturnValue({ id: null }); jest.spyOn(reservationService, 'create').mockReturnValue(saveSubject); jest.spyOn(comp, 'previousState'); activatedRoute.data = of({ reservation: null }); comp.ngOnInit(); // WHEN comp.save(); expect(comp.isSaving).toEqual(true); saveSubject.next(new HttpResponse({ body: reservation })); saveSubject.complete(); // THEN expect(reservationFormService.getReservation).toHaveBeenCalled(); expect(reservationService.create).toHaveBeenCalled(); expect(comp.isSaving).toEqual(false); expect(comp.previousState).toHaveBeenCalled(); }); it('Should set isSaving to false on error', () => { // GIVEN const saveSubject = new Subject<HttpResponse<IReservation>>(); const reservation = { id: 123 }; jest.spyOn(reservationService, 'update').mockReturnValue(saveSubject); jest.spyOn(comp, 'previousState'); activatedRoute.data = of({ reservation }); comp.ngOnInit(); // WHEN comp.save(); expect(comp.isSaving).toEqual(true); saveSubject.error('This is an error!'); // THEN expect(reservationService.update).toHaveBeenCalled(); expect(comp.isSaving).toEqual(false); expect(comp.previousState).not.toHaveBeenCalled(); }); }); describe('Compare relationships', () => { describe('compareVol', () => { it('Should forward to volService', () => { const entity = { id: 123 }; const entity2 = { id: 456 }; jest.spyOn(volService, 'compareVol'); comp.compareVol(entity, entity2); expect(volService.compareVol).toHaveBeenCalledWith(entity, entity2); }); }); describe('compareHotel', () => { it('Should forward to hotelService', () => { const entity = { id: 123 }; const entity2 = { id: 456 }; jest.spyOn(hotelService, 'compareHotel'); comp.compareHotel(entity, entity2); expect(hotelService.compareHotel).toHaveBeenCalledWith(entity, entity2); }); }); describe('compareActivite', () => { it('Should forward to activiteService', () => { const entity = { id: 123 }; const entity2 = { id: 456 }; jest.spyOn(activiteService, 'compareActivite'); comp.compareActivite(entity, entity2); expect(activiteService.compareActivite).toHaveBeenCalledWith(entity, entity2); }); }); describe('compareVoyageur', () => { it('Should forward to voyageurService', () => { const entity = { id: 123 }; const entity2 = { id: 456 }; jest.spyOn(voyageurService, 'compareVoyageur'); comp.compareVoyageur(entity, entity2); expect(voyageurService.compareVoyageur).toHaveBeenCalledWith(entity, entity2); }); }); }); });
<!DOCTYPE html> <html> <head> <title>PSY9219M - Research Methods and Skills</title> <meta charset="utf-8"> <meta name="author" content="Dr Matt Craddock" /> <link href="libs/remark-css/default.css" rel="stylesheet" /> <link href="libs/remark-css/default-fonts.css" rel="stylesheet" /> <link rel="stylesheet" href="css\my-theme.css" type="text/css" /> </head> <body> <textarea id="source"> class: center, middle, inverse, title-slide # PSY9219M - Research Methods and Skills ### Dr Matt Craddock ### 25/09/2018 --- # Who am I? .pull-left[ ![](../images/01/itme.jpg) ] .pull-right[ ### Dr Matt Craddock - Research background in cognitive neuroscience - EEG, fMRI, non-invasive brain stimulation - Programming in R, Matlab, Python - Past experience with SPSS, SigmaPlot, Excel |Sarah Swift Building Room 2226| |------------------------------| |mcraddock@lincoln.ac.uk | ] --- # PSY9219M - Research Methods and Skills -- .pull-left[ ![](../images/01/catistics-small.jpg) ] -- .pull-right[ ![](../images/01/dog-gramming.jpg) ] --- # Course outline .pull-left[ ### Weeks 1-5 - Introduction to R - Basic R programming - Plotting with ggplot2 - Data import, selection and manipulation - Describing and summarising your data ] .pull-right[ ### Weeks 5-6, 8-10 - Hypothesis testing and estimation - *t*-tests and comparing two groups - Correlation and linear regression - One-way ANOVA - Factorial ANOVA ] ### Weeks 11-13 - Qualitative methods --- # Course outline .pull-left[ ### Weeks 1-5 ![](../images/01/dog-gramming.jpg) ] .pull-right[ ### Weeks 5-6, 8-10 ![](../images/01/catistics-small.jpg) ] --- # Course outline .pull-left[ ### Weeks 1-5 ![:scale 45%](../images/01/R4DS.png) ] .pull-right[ ### Weeks 5-10 ![Discovering Statistics Using R](../images/01/DiscoverR.jpg) ] --- class: inverse, center, middle # Introduction to R and RStudio --- background-image: url(https://www.r-project.org/Rlogo.png) background-position: 80% 10% # What is R? .large[ R is a statistical, mathematical programming language * Created in 1993 * Designed from the ground up to support many statistical tasks * Covers all aspects of data analysis from import through to production of reports * Free, open source * Can be downloaded from the [R-project](https://r-project.org) website * Continually evolving * R has over 12,000 *packages* that add additional functions ] --- class: inverse, center, middle # But WHY? --- # What can you do? .pull-left[ ![:scale 100%](images/01/whatyoucando_collage.png) ] .pull-right[ ] --- background-image: url(../images/01/Rcompanies.png) background-size: contain --- background-image: url(../images/01/spss_usage.png) #Still not convinced? --- # Scenario A .large[ You've just started work in a psychology lab. You're asked to help analyse some old data. There is reaction time data from 50 participants. Each participant's data is stored in a separate text file. - How do you combine the data from each participant together to be able to analyse the data? - It turns out some of the participants only completed part of the experiment - which ones, and what should you do with their data? - What steps should you take to select and perform appropriate statistical analysis? ] --- # Scenario B .large[ You've been asked to design, implement, and evaluate a new treatment regime across several psychiatric institutes. Several colleagues are skeptical that it can deliver the kind of improvements in outcomes indicated in a publication describing the method. - How do you interpret the strength of the previously published evidence? - How do you design a rigorous test of the treatment efficacy? - How do you evaluate and report on the outcomes of your trial? ] --- class: inverse, center, middle # Getting started --- background-image: url(../images/01/RStudio-logo.png) background-size: 30% background-position: 80% 5% # What is RStudio? .large[ - An **Integrated Development Environment (IDE)** - An interface for R that makes your life much, much easier - Makes many things explicit that you would otherwise have to guess ] ![:scale 50%](../images/01/rstudio-basic.png) --- background-image: url(../images/01/rstudiocloud_page.png) background-size: 60% background-position: 50% 90% # Getting started .large[ 1. Open up a web browser 2. Go to https://rstudio.cloud 3. Sign up! Use your REAL NAME, and your University of Lincoln email address. ] --- background-image: url(../images/01/RStudioCloud.png) background-size: contain class: inverse --- background-image: url(../images/01/RStudioCloud_proj_circ.png) background-size: contain class: inverse --- background-image: url(../images/01/default_project.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud-tools.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud-appear.png) background-size: contain class: inverse --- class: inverse, center, middle # How it works! --- background-image: url(../images/01/proj_console.png) background-size: contain class: inverse --- background-image: url(../images/01/proj_console_repl.png) background-size: contain class: inverse --- # How to use R * The R Console * REPL: Read/Evaluate/Print/Loop * Type stuff in, it tries to do it When you see the **&gt;** symbol - ```r *&gt; ``` ... R is waiting for your input. ```r &gt; 5 [1] 5 ``` --- # Warming up Try using R like a calculator! ### Basic arithmetic operators |Symbol |Operation | |:------|:--------------| |+ |addition | |- |subtraction | |* |multiplication | |/ |division | |^ |exponentiation | |%% |modulo | --- # Warming up You can break up long maths expressions over multiple lines: ```r 2 + 4 + 5 + 5 + 6 + 7 + 8 + 10 ``` ``` ## [1] 47 ``` Note that when you do that, the "&gt;" symbol changes to a "+" ```r &gt; 5 + *+ 5 [1] 10 ``` --- # Remember! .large[**&gt;** means R is waiting for input.] ```r &gt; ``` .large[**+** means R is waiting for you to finish your command.] ```r + ``` Either finish your command, or press the **Esc** key to cancel it. --- # Text input R can also accept text strings as input. ```r "hello world!" [1] "hello world!" ``` You need to use quotation marks ("") to tell R that this is text: ```r hello world! ``` ``` ## Error: &lt;text&gt;:1:7: unexpected symbol ## 1: hello world ## ^ ``` Otherwise, you'll receive an error like the one above. --- # Why is there an error? In R, you can assign values to an **object** for subsequent use. **Objects** have names that are written as text. The assignment operator is the two-character symbol: ```r *&lt;- ``` You assign values to objects by putting the **&lt;-** sign between the name of the object and the value you want to give it: ```r example &lt;- 5 example ``` ``` ## [1] 5 ``` Note that R does not immediately provide output when you assign the output to an object. --- # The assignment operator .large[Think of **&lt;-** as meaning "is now". i.e. ```r example &lt;- 5 ``` can be read as ```r The object "example" is now 5 ``` ] --- # Working with objects Once an object is assigned, the name that you gave it *stands in* for the *value* that you assigned to it, and can be used as if it were that value: ```r example ``` ``` ## [1] 5 ``` ```r example + 10 ``` ``` ## [1] 15 ``` ```r example + 13 - 1 * 2 %% 4 ``` ``` ## [1] 16 ``` --- background-image: url(../images/01/cloud_environ.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud_environ2.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud-history.png) background-size: contain class: inverse --- class: inverse, center, middle # Try it out! --- # Try a few things out! 1. Assign some values to objects using the assignment operator (**&lt;-**) 2. Try using arithmetic operations (e.g. *, /, %%) on those objects 3. Try using arithmetic operations to combine multiple numerical objects 4. Try using arithmetic operations on text --- # Combining multiple things Sometimes you want to allocate more than one value to an object. You can use the **c()** function to do this. ```r c(8, 5, 10) ``` ``` ## [1] 8 5 10 ``` ```r example &lt;- c(8, 5, 10) example ``` ``` ## [1] 8 5 10 ``` ```r c("hello", "how", "are", "you") ``` ``` ## [1] "hello" "how" "are" "you" ``` ## IMPORTANT: BRACKETS () AFTER A WORD MEAN THAT THIS IS A **FUNCTION** --- # Vectors The function **c()** is creating **vectors**. Vectors are simply a one-dimensional collection of things that all have the same *type* (we will cover data types next week!). Note that mixing, for example, text and numbers, will yield a *character* vector. ```r c(5, "five", 2) ``` ``` ## [1] "5" "five" "2" ``` --- # Functions Functions are commands that operate on **objects**. For example, to calculate the *mean* of several numbers, you can use the function **mean()**. The output of functions can also be assigned to **objects** using **&lt;-**. ```r mean(c(8, 5, 10)) ``` ``` ## [1] 7.666667 ``` ```r example &lt;- c(8, 5, 10) mean(example) ``` ``` ## [1] 7.666667 ``` ```r example_mean &lt;- mean(example) example_mean ``` ``` ## [1] 7.666667 ``` --- # Try it out! 1. Use **c()** to create a vector of numbers. 2. Use **c()** to create a vector of strings. 3. Calculate the **mean()** of a vector of numbers. 4. Try guessing some other simple statistics (e.g. other types of *average*) that you can use. --- background-image: url(../images/01/cloud-help.png) background-size: 40% background-position: 50% 75% # Getting help If you don't know how to use a function, R has built-in help! There are several ways you can access it: ```r help("mean") ?mean ??mean ``` --- # Packages Packages are the key to R's versatility. Over 12000 are currently available from the **Comprehensive R Archive Network** - [CRAN](https::https://cran.r-project.org/). The **install.packages()** function can be used to install packages. Let's install the "cowsay" package. **cowsay** is an extraordinarily useful package, as you'll see. One way to install the package is using the console: ```r install.packages("cowsay") ``` Once it's installed, use the **library()** function to load the package! ```r library(cowsay) ``` But **another** way to install is using the GUI! --- background-image: url(../images/01/cloud-packages.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud-cowsay.png) background-size: contain class: inverse --- background-image: url(../images/01/cloud-help.png) background-position: 90% 85% background-size: 40% # Try out the **cowsay** package **cowsay** adds a function called **say()**. Load the function in as follows, and look at the help for **say()**. ```r library(cowsay) ?say() ``` .left-pull[ Remember that help appears in the bottom right window! Look at **Usage** and **Arguments** **Usage** is how to use the function. **Arguments** are what the functions expect and understand. ] --- ```r say(what = "Feed me, human.", by = "cat") ``` ``` ## Colors cannot be applied in this environment :( Try using a terminal or RStudio. ``` ``` ## ## -------------- ## Feed me, human. ## -------------- ## \ ## \ ## \ ## |\___/| ## ==) ^Y^ (== ## \ ^ / ## )=*=( ## / \ ## | | ## /| | | |\ ## \| | |_|/\ ## jgs //_// ___/ ## \_) ## ``` --- # Try out the say() function 1. Try a few different animals by changing the **by** argument 2. Change what the animals say by changing the **what** argument. 3. Assign the output to an object using the **&lt;-** operator. 4. Print out the value that you assigned to the object. --- # Additional resources .pull-left[ ![:scale 45%](../images/01/R4DS.png) ] .pull-right[ ![Discovering Statistics Using R](../images/01/DiscoverR.jpg) ] There are copies of both these books in the library. R for Data Science is available freely online at http://r4ds.had.co.nz/ --- background-image: url(../images/01/Datacamp_.png) background-size: contain class: inverse --- # DataCamp DataCamp provides a huge number of practical exercises across many different languages, not least of which is R. # Get signed up for DataCamp! .large[ # [https://tinyurl.com/DatacampSignup](https://tinyurl.com/DatacampSignup) ] --- # Homework! 1. If you didn't get properly signed up with RStudio.cloud today, do it! 2. Get signed up with DataCamp using the link provided 3. Read through Chapter 1 of R for Data Science 4. Try out some of the introductory exercises --- class: title-slide-final, middle, inverse background-image: url('images/University of Lincoln_logo_General White Landscape.png') background-size: 500px background-position: 50% 10% --- # Scenario C .large[ You've collected data from 100 participants using an online questionnaire with 20 questions. Some responses are free text (i.e. they can write whatever they like). Some responses use a Likert scale. For those responses, you also have a set of standard values that represent population averages. - What kind of statistical analyses are appropriate for these data? - How do you get the data into a format you can analyse it? - How do you combine it with and compare it against the data from the broader population? ] </textarea> <style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style> <script src="https://remarkjs.com/downloads/remark-latest.min.js"></script> <script src="js/macros.js"></script> <script>var slideshow = remark.create({ "highlightStyle": "github", "highlightLines": true, "countIncrementalSlides": false, "ratio": "16:9" }); if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) { window.dispatchEvent(new Event('resize')); }); (function(d) { var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler"); if (!r) return; s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }"; d.head.appendChild(s); })(document); (function(d) { var el = d.getElementsByClassName("remark-slides-area"); if (!el) return; var slide, slides = slideshow.getSlides(), els = el[0].children; for (var i = 1; i < slides.length; i++) { slide = slides[i]; if (slide.properties.continued === "true" || slide.properties.count === "false") { els[i - 1].className += ' has-continuation'; } } var s = d.createElement("style"); s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }"; d.head.appendChild(s); })(document); // delete the temporary CSS (for displaying all slides initially) when the user // starts to view slides (function() { var deleted = false; slideshow.on('beforeShowSlide', function(slide) { if (deleted) return; var sheets = document.styleSheets, node; for (var i = 0; i < sheets.length; i++) { node = sheets[i].ownerNode; if (node.dataset["target"] !== "print-only") continue; node.parentNode.removeChild(node); } deleted = true; }); })();</script> <script> (function() { var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) { links[i].target = '_blank'; } } })(); </script> <script> slideshow._releaseMath = function(el) { var i, text, code, codes = el.getElementsByTagName('code'); for (i = 0; i < codes.length;) { code = codes[i]; if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) { text = code.textContent; if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) || /^\$\$(.|\s)+\$\$$/.test(text) || /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) { code.outerHTML = code.innerHTML; // remove <code></code> continue; } } i++; } }; slideshow._releaseMath(document); </script> <!-- dynamically load mathjax for compatibility with self-contained --> <script> (function () { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML'; if (location.protocol !== 'file:' && /^https?:/.test(script.src)) script.src = script.src.replace(/^https?:/, ''); document.getElementsByTagName('head')[0].appendChild(script); })(); </script> </body> </html>
<script setup> import { ref, onMounted } from 'vue' const DataValue = ref([]); const isLoad = ref(true); const LoadImg = (imgUrl) => { const imgArr = [...imgUrl]; let i = 0; imgArr.forEach(src => { const img = new Image(); img.src = src; img.onload = () => { i += 1; if (i === imgArr.length) { isLoad.value = false; } } }) } onMounted(() => { fetch('https://610cd85966dd8f0017b76eb5.mockapi.io/api/card') .then(res => res.json()).then(res => { DataValue.value = res; const imgArr = res.map(item => [item.avatar, item.content]); LoadImg([].concat(...imgArr)); }); }) </script> <template> <div :class="['card', {load: isLoad}]" v-for="item in DataValue" :key="item.id"> <header> <div class="photo"> <img :src="item.avatar"> </div> <p>{{ isLoad ? "" : item.username }}</p> </header> <p>{{ isLoad ? "" : item.text }}</p> <main> <img :src="item.content"> </main> </div> </template> <style lang="scss" scoped> * { padding: 0; margin: 0; box-sizing: border-box; } img { display: block; } html, body { width: 100%; height: 100%; background-color: #e1e1e1; display: flex; justify-content: center; align-items: center; } #app { width: 100%; height: 100%; display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; padding: 35px; } .card { width: 300px; height: auto; border-radius: 10px; overflow: hidden; background-color: #fff; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2); margin-bottom: 50px; >p { font-size: 14px; padding: 0 10px; margin-bottom: 10px; } header { width: 100%; display: flex; justify-content: flex-start; align-items: center; padding: 10px; >div { margin-right: 10px; >img { border-radius: 50%; } } >p { font-size: 13px; } } img { opacity: 1; transition: opacity .3s; } } .load { width: 300px; height: 380px; border-radius: 10px; overflow: hidden; background-color: #fff; >header { width: 100%; display: flex; justify-content: flex-start; align-items: center; padding: 10px; >div { width: 30px; height: 30px; border-radius: 50px; margin-right: 10px; background-color: #ededed; >img { border-radius: 50%; } } >p { font-size: 13px; display: block; width: 40%; height: 18px; background-color: #ededed; } } >p { font-size: 14px; margin: 0 10px 10px 10px; display: block; width: 70%; height: 18px; background-color: #ededed; } >main { width: 100%; height: 300px; background-color: #ededed; } img { opacity: 0; } } @keyframes loading { to { background-position-x: -20%; } } .load { .photo, p, main { background: linear-gradient(100deg, rgba(256, 256, 256, 0) 30%, rgba(256, 256, 256, 0.5) 50%, rgba(256, 256, 256, 0) 30%) #ededed; background-size: 200% 100%; background-position-x: 180%; animation: 2s loading ease-in-out infinite; } } </style>
<?php /** * Copyright ยฉ Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\SharedCatalog\Test\Unit\Model; use Magento\CatalogPermissions\App\ConfigInterface; use Magento\Framework\App\Config\ScopeConfigInterface; /** * Unit test for Magento\SharedCatalog\Model\CategoryPermissions class. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CategoryPermissionsTest extends \PHPUnit\Framework\TestCase { /** * @var \Magento\CatalogPermissions\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ private $configResource; /** * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ private $storeManager; /** * @var \Magento\SharedCatalog\Model\CategoryPermissions */ private $model; /** * @var \Magento\SharedCatalog\Model\CategoryPermissionsInvalidator|\PHPUnit_Framework_MockObject_MockObject */ private $invalidatorMock; /** * @inheritdoc */ protected function setUp() { $this->configResource = $this->getMockBuilder( \Magento\Framework\App\Config\ConfigResource\ConfigInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->invalidatorMock = $this->createMock( \Magento\SharedCatalog\Model\CategoryPermissionsInvalidator::class ); $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->model = $objectManager->getObject( \Magento\SharedCatalog\Model\CategoryPermissions::class, [ 'configResource' => $this->configResource, 'storeManager' => $this->storeManager, 'invalidator' => $this->invalidatorMock ] ); } /** * Test enable method. * * @return void */ public function testEnable() { $this->configResource->expects($this->exactly(4)) ->method('saveConfig') ->withConsecutive( [ ConfigInterface::XML_PATH_ENABLED, 1, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0 ], [ ConfigInterface::XML_PATH_GRANT_CATALOG_CATEGORY_VIEW, ConfigInterface::GRANT_ALL, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0 ], [ ConfigInterface::XML_PATH_GRANT_CATALOG_PRODUCT_PRICE, ConfigInterface::GRANT_ALL, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0 ], [ ConfigInterface::XML_PATH_GRANT_CHECKOUT_ITEMS, ConfigInterface::GRANT_ALL, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0 ] ) ->willReturnSelf(); $website = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $website->expects($this->atLeastOnce()) ->method('getId') ->willReturn(1); $this->storeManager->expects($this->atLeastOnce()) ->method('getWebsites') ->willReturn([$website]); $this->invalidatorMock->expects($this->once())->method('invalidate'); $this->model->enable(); } }
#include <iostream> using namespace std; class Base { protected: int baseData; public: Base(int baseData) : baseData(baseData) { } Base& operator= (const Base& rhs) { cout << "Base& operator= ()" << endl; baseData = rhs.baseData; return *this; } void Show() { cout << "Base: " << baseData << endl; } }; class Derived : public Base { protected: int derivedData; public: Derived(int baseData, int derivedData) : Base(baseData), derivedData(derivedData) { } // ์ž์‹์—์„œ ๋Œ€์ž… ์—ฐ์‚ฐ์ž๋ฅผ ์ •์˜ํ•˜๋ฉด, // ๊ธฐ๋ณธ ๋Œ€์ž… ์—ฐ์‚ฐ์ž์™€ ๋‹ฌ๋ฆฌ // // ๋ถ€๋ชจ์˜ ๋Œ€์ž… ์—ฐ์‚ฐ์ž๋ฅผ ์ž๋™์œผ๋กœ ํ˜ธ์ถœํ•˜์ง€ ์•Š๋Š”๋‹ค. Derived& operator= (const Derived& rhs) { cout << "Derived& operator= ()" << endl; derivedData = rhs.derivedData; return *this; } void Show() { cout << "Base: " << baseData << ", Derived: " << derivedData << endl; } }; int main(int argc, char* argv[]) { Derived dest(0, 0), src(1, 2); dest = src; dest.Show(); return 0; }
use crate::cartridge; use crate::cartridge::mbc1::MBC1; use crate::cartridge::Interface; #[test] fn new() { struct TestCase { init_fn: fn() -> Vec<u8>, } let test_cases: Vec<TestCase> = vec![ TestCase { init_fn: || -> Vec<u8> { let mut cart_data: Vec<u8> = vec![0x00; 0x8000]; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1; return cart_data; }, }, TestCase { init_fn: || -> Vec<u8> { let mut cart_data: Vec<u8> = vec![0x00; 0x8000]; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; return cart_data; }, }, TestCase { init_fn: || -> Vec<u8> { let mut cart_data: Vec<u8> = vec![0x00; 0x8000]; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM_BATTERY; return cart_data; }, }, ]; for tc in test_cases { let mbc1 = MBC1::new(vec![]); let implementation = cartridge::new((tc.init_fn)()); match implementation.as_any().downcast_ref::<MBC1>() { Some(mbc1) => {} None => panic!("returned cartridge implementation was not a MBC1!"), }; } } #[test] fn read() { struct TestCase { description: String, run_fn: fn(), } let test_cases: Vec<TestCase> = vec![ TestCase { description: String::from("read from bank 0 w/ no bank switching"), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x4000]; cart_data[0x0] = 0x7F; let mbc1 = MBC1::new(cart_data); let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from bank 0 w/ bank switching but ram bank register is 0", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x4000]; cart_data[0x0] = 0x7F; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from bank 0x20 w/ bank switching when ram bank register is 1", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x21 * 0x4000]; cart_data[0x20 * 0x4000] = 0x7F; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; mbc1.ram_bank_select_register = 0x1; let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from bank 0x40 w/ bank switching when ram bank register is 2", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x41 * 0x4000]; cart_data[0x40 * 0x4000] = 0x7F; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; mbc1.ram_bank_select_register = 0x2; let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from bank 0x60 w/ bank switching when ram bank register is 3", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x61 * 0x4000]; cart_data[0x60 * 0x4000] = 0x7F; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; mbc1.ram_bank_select_register = 0x3; let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from bank 0x00 w/ bank switching when ram bank register is greater than 4 (bit masking)", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[0x0000] = 0x7F; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; mbc1.ram_bank_select_register = 0x4; let read_result = mbc1.read(0x0); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 0 -> should still access bank 1, not bank 0", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x2 * 0x4000]; cart_data[0x4000] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x0; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 1 -> should select data in bank 1", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x2 * 0x4000]; cart_data[0x4000] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x1; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 3 -> should select data in bank 3", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x4 * 0x4000]; cart_data[0x4000 * 0x3] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x3; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 3 + ram banking mode -> should still only select bank 3", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x4 * 0x4000]; cart_data[0x4000 * 0x3] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x3; mbc1.ram_bank_select_register = 0x1; mbc1.banking_mode = MBC1::RAM_BANKING_MODE; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 3 + ram banking mode + 1MB cart -> should select bank 0x23", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x24 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; cart_data[0x4000 * 0x23] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x3; mbc1.ram_bank_select_register = 0x1; mbc1.banking_mode = MBC1::RAM_BANKING_MODE; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read rom region 0x4000 - 0x8000 w/ rom select register 0 + ram banking mode + ram select register 3 + 1MB cart -> should select bank 0x61", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x62 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = cartridge::rom_size_id::ONE_MEGABYTE; cart_data[0x4000 * 0x61] = 0x7F; let mut mbc1 = MBC1::new(cart_data); mbc1.rom_bank_select_register = 0x0; mbc1.ram_bank_select_register = 0x3; mbc1.banking_mode = MBC1::RAM_BANKING_MODE; let read_result = mbc1.read(0x4000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF -> cart has no ram -> should return 0xFF", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::NO_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x0; mbc1.ram_banks[0][0] = 0x7F; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0xFF, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF + cart type has ram + but type is not MBC1 w/ RAM -> should return 0xFF", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::ONE_BANK; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x0; mbc1.ram_banks[0][0] = 0x7F; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0xFF, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF + ram select register is 0 + cart type has ram + cart is MBC1_RAM + ram is disabled -> should return 0xFF", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::ONE_BANK; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x0; mbc1.ram_banks[0][0] = 0x7F; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0xFF, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF + ram select register is 0 + cart type has ram + cart is MBC1_RAM + ram is enabled -> should return value in ram bank 0", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::ONE_BANK; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x0; mbc1.ram_banks[0][0] = 0x7F; mbc1.ram_enabled = true; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF + ram select register is 1 + cart type has ram + cart is MBC1_RAM + ram is enabled + cart has more than 4 banks -> should return value in ram bank 1", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x1; mbc1.ram_banks[1][0] = 0x7F; mbc1.ram_enabled = true; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read ram region 0xA000-0xBFFF + ram select register is 4 + cart type has ram + cart is MBC1_RAM + ram is enabled + cart has more than 4 banks -> should return value in ram bank 0 (because of mask)", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_bank_select_register = 0x4; mbc1.ram_banks[0][0] = 0x7F; mbc1.ram_enabled = true; let read_result = mbc1.read(0xA000); assert_eq!( read_result.unwrap(), 0x7F, ) }, }, TestCase { description: String::from( "read from undefined region", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mbc1 = MBC1::new(cart_data); let read_result = mbc1.read(0x8000); assert!(read_result.is_none()) }, }, ]; for tc in test_cases { println!("{}", tc.description); (tc.run_fn)(); } } #[test] fn write() { struct TestCase { description: String, run_fn: fn(), } let test_cases: Vec<TestCase> = vec![ TestCase { description: String::from( "writing to 0x0000 - 0x2000 -> non 0x-A value in the lower nibble -> disables ram", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.write(0x0000, 0x13); assert!(!mbc1.ram_enabled); }, }, TestCase { description: String::from( "writing to 0x0000 - 0x2000 -> 0x5A value (lower nibble == 0xA) -> enables ram", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x0000, 0x5A); assert!(mbc1.ram_enabled); }, }, TestCase { description: String::from( "writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 1 bank -> should set register to 1", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x00; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x2000, 0xFF); assert_eq!(mbc1.rom_bank_select_register, 0x01); }, }, TestCase { description: String::from( "writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 4 banks -> should set register to 3", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x01; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x2000, 0xFF); assert_eq!(mbc1.rom_bank_select_register, 0x03); }, }, TestCase { description: String::from( "writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 8 banks -> should set register to 7", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x02; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x2000, 0xFF); assert_eq!(mbc1.rom_bank_select_register, 0x07); }, }, TestCase { description: String::from( "writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 16 banks -> should set register to 15", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x03; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x2000, 0xFF); assert_eq!(mbc1.rom_bank_select_register, 0x0F); }, }, TestCase { description: String::from( "writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 32 banks -> should set register to 31", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x04; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x2000, 0xFF); assert_eq!(mbc1.rom_bank_select_register, 0x1F); }, }, TestCase { description: String::from( "writing to 0x4000 - 0x6000 -> value is 0x1 -> should set ram select register to 1", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x4000, 0x1); assert_eq!(mbc1.ram_bank_select_register, 0x1); }, }, TestCase { description: String::from( "writing to 0x4000 - 0x6000 -> value is 0xFF -> should set ram select register to 3", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x4000, 0xFF); assert_eq!(mbc1.ram_bank_select_register, 0x3); }, }, TestCase { description: String::from( "writing to 0x6000 - 0x8000 -> value is 0x1 -> should set banking mode to ram banking mode", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0x6000, 0x1); assert_eq!(mbc1.banking_mode, MBC1::RAM_BANKING_MODE); }, }, TestCase { description: String::from( "writing to 0x6000 - 0x8000 -> value is 0x10 -> should set banking mode to simple banking mode", ), run_fn: || { let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000]; let mut mbc1 = MBC1::new(cart_data); mbc1.banking_mode = MBC1::RAM_BANKING_MODE; mbc1.write(0x6000, 0x10); assert_eq!(mbc1.banking_mode, MBC1::SIMPLE_BANKING_MODE); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart does not support ram -> should do nothing", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[0][0x1000], 0x00); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram disabled + cart has ram -> should do nothing", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[0][0x1000], 0x00); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 0", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::ONE_BANK; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[0][0x1000], 0x10); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 1", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.ram_bank_select_register = 0x01; mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[1][0x1000], 0x10); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 2", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.ram_bank_select_register = 0x02; mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[2][0x1000], 0x10); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 3", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.ram_bank_select_register = 0x03; mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[3][0x1000], 0x10); }, }, TestCase { description: String::from( "writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 0", ), run_fn: || { let mut cart_data: Vec<u8> = vec![0x00; 0x4000]; cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS; cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM; let mut mbc1 = MBC1::new(cart_data); mbc1.ram_enabled = true; mbc1.ram_bank_select_register = 0x04; mbc1.write(0xB000, 0x10); assert_eq!(mbc1.ram_banks[0][0x1000], 0x10); }, }, ]; for tc in test_cases { println!("{}", tc.description); (tc.run_fn)(); } }
/* # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Installation : # # NodeMCU ESP8266/ESP12E RFID MFRC522 / RC522 # # D2 <----------> SDA/SS # # D5 <----------> SCK # # D7 <----------> MOSI # # D6 <----------> MISO # # GND <----------> GND # # D1 <----------> RST # # 3V/3V3 <----------> 3.3V # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # */ #include <SPI.h> #include <MFRC522.h> #define SS_PIN 4 //--> SDA / SS is connected to pinout D2 #define RST_PIN 5 //--> RST is connected to pinout D1 #define ON_Board_LED 2 //--> Defining an On Board LED, used for indicators when the process of connecting to a wifi router #define Buzzer 16 // D0 pin for the buzzer MFRC522 mfrc522(SS_PIN, RST_PIN); //--> Create MFRC522 instance. int readsuccess; byte readcard[4]; char str[32] = ""; String StrUID; void setup() { Serial.begin(115200); //--> Initialize serial communications with the PC SPI.begin(); //--> Init SPI bus mfrc522.PCD_Init(); //--> Init MFRC522 card delay(500); pinMode(ON_Board_LED, OUTPUT); pinMode(Buzzer, OUTPUT); digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board digitalWrite(Buzzer, LOW); Serial.println(""); Serial.println("Please tag a card or keychain to see the UID !"); Serial.println(""); } void loop() { readsuccess = getid(); if (readsuccess) { digitalWrite(ON_Board_LED, LOW); digitalWrite(Buzzer, HIGH); String UIDresultSend = StrUID; Serial.println(UIDresultSend); delay(1000); digitalWrite(ON_Board_LED, HIGH); digitalWrite(Buzzer, LOW); } } //----------------Procedure for reading and obtaining a UID from a card or keychain--------------// int getid() { if (!mfrc522.PICC_IsNewCardPresent()) { return 0; } if (!mfrc522.PICC_ReadCardSerial()) { return 0; } Serial.print("THE UID OF THE SCANNED CARD IS : "); for (int i = 0; i < 4; i++) { readcard[i] = mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard array_to_string(readcard, 4, str); StrUID = str; } mfrc522.PICC_HaltA(); return 1; } //----------------------------Procedure to change the result of reading an array UID into a string-----------------------------// void array_to_string(byte array[], unsigned int len, char buffer[]) { for (unsigned int i = 0; i < len; i++) { byte nib1 = (array[i] >> 4) & 0x0F; byte nib2 = (array[i] >> 0) & 0x0F; buffer[i * 2 + 0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA; buffer[i * 2 + 1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA; } buffer[len * 2] = '\0'; }
import {Action} from '@ngrx/store'; import {Visitor} from '../models/visitor.model'; import {VisitorForm} from '../models/visitor-form.model'; export const FETCH_VISITORS_SUCCESS = '[Visitor] Fetch Visitors Success'; export const FETCH_VISITORS_START = '[Visitor] Fetch Visitors Start'; export const FETCH_VISITOR_START = '[Visitor] Fetch Visitor Start'; export const CLEAR_SELECTED_VISITOR = '[Visitor] Clear Selected Visitor'; export const FETCH_VISITOR_SUCCESS = '[Visitor] Fetch Visitor Success'; export const UPDATE_VISITOR_START = '[Visitor] Update Visitor Start'; export const UPDATE_VISITOR_SUCCESS = '[Visitor] Update Visitor Success'; export const DELETE_VISITOR_SUCCESS = '[Visitor] Delete Visitor Success'; export const DELETE_VISITOR_START = '[Visitor] Delete Visitor Start'; export const CREATE_VISITOR_SUCCESS = '[Visitor] Create Visitor Success'; export const CREATE_VISITOR_START = '[Visitor] Create Visitor Start'; export class FetchVisitorsSuccess implements Action { readonly type = FETCH_VISITORS_SUCCESS; constructor(public payload: Visitor[]) {} } export class FetchVisitorsStart implements Action { readonly type = FETCH_VISITORS_START; } export class ClearSelectedVisitor implements Action { readonly type = CLEAR_SELECTED_VISITOR; } export class DeleteVisitorSuccess implements Action { readonly type = DELETE_VISITOR_SUCCESS; constructor(public payload: Visitor['visitorId']) {} } export class DeleteVisitorStart implements Action { readonly type = DELETE_VISITOR_START; constructor(public payload: Visitor) {} } export class CreateVisitorSuccess implements Action { readonly type = CREATE_VISITOR_SUCCESS; constructor(public payload: Visitor) {} } export class CreateVisitorStart implements Action { readonly type = CREATE_VISITOR_START; constructor(public payload: VisitorForm) {} } export class FetchVisitorSuccess implements Action { readonly type = FETCH_VISITOR_SUCCESS; constructor(public payload: Visitor) {} } export class FetchVisitorStart implements Action { readonly type = FETCH_VISITOR_START; constructor(public payload: Visitor['visitorId']) {} } export class UpdateVisitorStart implements Action { readonly type = UPDATE_VISITOR_START; constructor(public payload: VisitorForm) {} } export class UpdateVisitorSuccess implements Action { readonly type = UPDATE_VISITOR_SUCCESS; constructor(public payload: Visitor) {} } export type VisitorActions = | ClearSelectedVisitor | CreateVisitorSuccess | DeleteVisitorSuccess | FetchVisitorsSuccess | FetchVisitorSuccess | UpdateVisitorSuccess;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('group_user', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('group_id'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); $table->unique(['user_id', 'group_id']); // Ensures a user cannot join the same group multiple times }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('group_user'); } };