text
stringlengths
184
4.48M
/* * Copyright (c) 2014-2019, Draque Thompson, [email protected] * All rights reserved. * * Licensed under: Creative Commons Attribution-NonCommercial 4.0 International Public License * See LICENSE.TXT included with this code to read the full license agreement. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.darisadesigns.polyglotlina.QuizEngine; import org.darisadesigns.polyglotlina.DictCore; import org.darisadesigns.polyglotlina.ManagersCollections.DictionaryCollection; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Random; /** * * @author draque.thompson */ public class Quiz extends DictionaryCollection<QuizQuestion> { private final DictCore core; List<QuizQuestion> quizList = null; int quizPos = -1; // start at -1 because initial next() call bumps to 0 QuizQuestion curQuestion; public int getLength() { return quizList.size(); } /** * Gets current position within quiz. * Index begins at 0. * @return current position */ public int getCurQuestion() { return quizPos; } public Quiz(DictCore _core) { core = _core; } @Override public void clear() { bufferNode = new QuizQuestion(core); } /** * Gets list of questions in randomized order * @return */ public List<QuizQuestion> getQuestions() { long seed = System.nanoTime(); List<QuizQuestion> questions = new ArrayList<>(nodeMap.values()); Collections.shuffle(questions, new Random(seed)); return questions; } public int getQuizLength() { return nodeMap.size(); } /** * Gets number of correctly answered questions (even if quiz is not completed) * @return number of correct answers */ public int getNumCorrect() { int ret = 0; for (Object o : nodeMap.values().toArray()) { QuizQuestion question = (QuizQuestion)o; if (question.getAnswered() == QuizQuestion.Answered.Correct) { ret++; } } return ret; } /** * Sets test back to non-taken, original status. */ public void resetQuiz() { for (Object o : nodeMap.values().toArray()) { QuizQuestion question = (QuizQuestion)o; question.setAnswered(QuizQuestion.Answered.Unanswered); question.setUserAnswer(null); } curQuestion = null; quizPos = -1; quizList = null; } public void trimQuiz() { for (Entry<Integer, QuizQuestion> o : nodeMap.entrySet()) { QuizQuestion question = o.getValue(); if (question.getAnswered() == QuizQuestion.Answered.Correct) { nodeMap.remove(o.getKey()); } else { question.setAnswered(QuizQuestion.Answered.Unanswered); question.setUserAnswer(null); } } curQuestion = null; quizPos = -1; quizList = null; } /** * Tests whether more questions exist in quiz * @return true if more questions */ public boolean hasNext() { if (quizList == null) { quizList = new ArrayList<>(nodeMap.values()); } return quizList.size() > quizPos; } /** * Gets next quiz question (if one exists) * Will throw out of bounds exception if no * next question. * * @return next quiz question */ public QuizQuestion next() { if (quizList == null) { quizList = new ArrayList<>(nodeMap.values()); } quizPos++; curQuestion = quizList.get(quizPos); return curQuestion; } /** * Gets previous question. Throws null exception if quizList not initialized. * Throws out of bounds exception if called while on first question * @return */ public QuizQuestion prev() { if (quizPos == 0) { throw new IndexOutOfBoundsException("You can't call this when on the first entry."); } quizPos--; return quizList.get(quizPos); } @Override public Object notFoundNode() { QuizQuestion emptyQuestion = new QuizQuestion(core); emptyQuestion.setValue("QUESTION NOT FOUND"); return emptyQuestion; } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { TableComponent } from './core/components/table/table.component'; import { HeaderComponent } from './core/components/header/header.component'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { ModalComponent } from './core/components/modal/modal.component'; import { ConfirmComponent } from './core/components/confirm/confirm.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ModalDirective } from './core/directives/modal.directive'; import { HomeComponent } from './page/home/home.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, TableComponent, HeaderComponent, ModalComponent, HomeComponent, ConfirmComponent, ModalDirective, ], imports: [ BrowserModule, FormsModule, FontAwesomeModule, ReactiveFormsModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
import React from "react"; import { useContext } from "react"; import { Avatar, Card, CardHeader, CardContent, IconButton, Typography, } from "@mui/material"; import DeleteIcon from "@mui/icons-material/Delete"; import CustomerContext from "../Context/CustomerContext"; import CustomerModal from "./CustomerModal"; function CustomerCard({ customer }) { const { deleteCustomer } = useContext(CustomerContext); const stringAvatar = (name) => { let avaText = `${name.split(" ")[0][0]}`; return { children: avaText.toUpperCase(), }; }; return ( <Card> <Avatar {...stringAvatar(customer.name)} sx={{ bgcolor: "green" }}></Avatar> <CardHeader action={ <IconButton onClick={() => { deleteCustomer(customer.id); }}> <DeleteIcon></DeleteIcon> </IconButton> } title={customer.name}></CardHeader> <CardContent> <Typography>{customer.detail}</Typography> <CustomerModal customer={customer} /> </CardContent> </Card> ); } export default CustomerCard;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="app"></div> <script src="./dist/runtime-dom.global.js"></script> <script> const { h, render, reactive, toRefs } = VueRuntimeDOM; const MyComponent = { setup(props, context) { return function () { return h("div", [ h("div", this.$slots.default()), h("div", context.slots.header()), h("div", context.slots.main()), h("div", context.slots.footer()), ]); }; }, }; const VueComponent = { render() { return h("div", [ h( MyComponent, {}, { default: () => { return h("h1", "default"); }, header: () => { return h("h1", "header"); }, main: () => { return h("h1", "main"); }, footer: () => { return h("h1", "footer"); }, } ), ]); }, }; render(h(VueComponent), app); </script> </body> </html>
interface ButtonProps { children: React.ReactNode onClick?: () => void disabled?: boolean className?: string } function Button ({ children, onClick, disabled = false, className }: Readonly<ButtonProps>) { return ( <button className={`${ disabled ? 'bg-black/20 text-black/50 cursor-not-allowed' : 'bg-mariner-900 text-white' } text-base font-bold px-4 py-2 rounded-sm flex justify-center items-center w-full ${className}`} onClick={onClick} disabled={disabled} > {children} </button> ) } export default Button
import express from "express"; import cors from "cors"; import dotenv from "dotenv"; import { connectDB } from "./config/db.js"; import { userRouter } from "./routes/userRouter.js"; import { errorHandler } from "./middlewares/errorMiddleware.js"; import { moviesRoute } from "./routes/movieRouter.js"; import { categoriesRoute } from "./routes/categoryRouter.js"; import UploadRouter from "./controllers/uploadFile.js"; import { faqRoute } from "./routes/faqRouter.js"; dotenv.config(); const app = express(); // CORS middleware app.use(cors()); app.use(express.json()); // Other routes app.use("/api/users", userRouter); app.use("/api/movies", moviesRoute); app.use("/api/categories", categoriesRoute); app.use("/api/upload", UploadRouter); app.use("/api/faqs", faqRoute); const port = process.env.PORT || 5000; // Error handling middleware app.use(errorHandler); // Connect to the database connectDB(); app.listen(port, () => { console.log(`Server is running`); });
#include <algorithm> #include <array> #include <cassert> #include <cctype> #include <charconv> #include <iostream> #include <numeric> #include <ranges> #include <string> #include <string_view> #include <vector> std::vector<std::string> readAllLines() { std::vector<std::string> lines; std::string line; while(std::getline(std::cin, line)) { lines.emplace_back(line); } return lines; } using Tint = int; template<typename It> bool getFirstDigit(It first, It last, Tint& out) { if(first == last) { return false; } if(std::isdigit(*first)) { out = (*first) - '0'; return true; } std::string_view str(first, last); static constexpr std::array<std::string_view, 9> spelledDigits{ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; for(int i = 0; i < 9; ++i) { if(str.starts_with(spelledDigits[i])) { out = i + 1; return true; } } return false; } Tint getCalibrationValue(std::string_view str) { Tint firstDigit = -1; for(auto it = str.begin(); it != str.end(); ++it) { if(getFirstDigit(it, str.end(), firstDigit)) { break; } } assert(firstDigit != -1); Tint lastDigit = -1; for(auto it = str.rbegin(); it != str.rend(); ++it) { if(getFirstDigit(it.base()-1, str.end(), lastDigit)) { break; } } assert(lastDigit != -1); return firstDigit*10 + lastDigit; } int main() { auto lines = readAllLines(); auto calibrationsRange = lines | std::views::transform(&getCalibrationValue); auto result = std::ranges::fold_left(calibrationsRange, Tint{}, std::plus<Tint>{}); std::cout << result << "\n"; return 0; }
import { task } from "hardhat/config"; import { types } from "hardhat/config"; import { getContractAt } from "@nomiclabs/hardhat-ethers/internal/helpers"; import { Contract } from "ethers"; import { TransactionResponse, TransactionReceipt } from "@ethersproject/abstract-provider"; task("transfer-ycktoken", "Transfer YckToken") .addParam("to", "Address", undefined, types.string) .addParam("amount", "Amount", undefined, types.string) .setAction(async (params, hre) => { const tokenAddress = '0x5fbdb2315678afecb367f032d93f642f64180aa3' return getContractAt(hre, "YckToken", tokenAddress, hre.ethers.provider.getSigner()) .then((contract: Contract) => { return contract.transfer(params.to, hre.ethers.utils.parseEther(params.amount)); }) .then((tr: TransactionResponse) => { return tr.wait().then((receipt: TransactionReceipt) => { console.log("transfer completed:", receipt.blockNumber) }) }).catch((e: Error) => console.log(e)) });
/*!***************************************************************************** \file SpriteManager.h \author Kew Yu Jun \par DP email: k.yujun\@digipen.edu \par Group: Memory Leak Studios \date 20-09-2022 \brief This file contains function declarations for the class SpriteManager, which operates on Entities with Sprite Component. *******************************************************************************/ #pragma once #include "ECS_components.h" #include <ECS_systems.h> #include "ECS_items.h" #include "pch.h" #include "SpriteVariable.h" #include "ResourceManager.h" /*!***************************************************************************** \brief SpriteManager Class that handles the getting and setting of varibles in the Sprite Component. *******************************************************************************/ class SpriteManager : public System { public: /*!***************************************************************************** \brief Default Constructor for SpriteManager class. *******************************************************************************/ SpriteManager(); /*!***************************************************************************** \brief Initializes and stores a texture in OpenGL memory. \param ResourceManager::TextureData& texData A struct encapsulating the details in a Texture object. *******************************************************************************/ void InitializeTexture (ResourceManager::TextureData& _texData); /*!***************************************************************************** \brief Free all textures in OpenGL memory. *******************************************************************************/ void FreeTextures(); //------------------------------------------------------------------------------ // Getter and Setters //------------------------------------------------------------------------------ void SetColor(const Entity& _e, const Color& clr); void SetColor(const Entity& _e, GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a = 255); Color GetColor(const Entity& _e) { return _e.GetComponent<Sprite>().color; } void SetSprite(const Entity& _e, SPRITE _sprite); SPRITE GetSprite(const Entity& _e) { return _e.GetComponent<Sprite>().sprite; } void SetTexture(const Entity& _e, const std::string& _texture_path); GLuint GetTexture(const Entity& _e) { return _e.GetComponent<Sprite>().texture; } GLuint GetTextureID (const std::string& _texture_path) { return GET_TEXTURE_ID(_texture_path); } std::string GetTexturePath (GLint _id) { return GET_TEXTURE_PATH(_id); } private: };
from datetime import datetime, timedelta, timezone from functools import wraps from threading import RLock from typing import List, Callable from scheduler import scheduler from apscheduler.jobstores.base import JobLookupError max_waiting_time = 15 class QueueEntry: def __init__(self, player_id: str): self.player_id = player_id self.time_added = datetime.now(timezone.utc) class Queue: def __init__(self, players_picked: Callable[[List[str]], None], queue_updated: Callable[[List[QueueEntry]], None]): self.pick_players_job = None self.queue: List[QueueEntry] = [] self.players_picked = players_picked self.queue_updated = queue_updated self.lock = RLock() def locked(func): @wraps(func) def wrapper(self, *args, **kwargs): with self.lock: return func(self, *args, **kwargs) return wrapper @locked def add_player(self, player_id: str): print(f"Queue: Player {player_id} joined the queue") self.cancel_auto_pick() self.queue.append(QueueEntry(player_id)) self.queue_updated(self.queue[:4]) if 1 < len(self) < 4: if self.highest_waiting_time > timedelta(seconds=max_waiting_time): self.deque_players() else: self.pick_players_job = scheduler.add_job( self.deque_players, "date", run_date=self.queue[0].time_added + timedelta(seconds=max_waiting_time) ) elif len(self) >= 4: self.deque_players() @locked def remove_player(self, player_id: str): print(f"Queue: Player {player_id} left the queue") self.queue = [entry for entry in self.queue if entry.player_id != player_id] self.queue_updated(self.queue[:4]) if len(self) <= 1: self.cancel_auto_pick() @locked def cancel_auto_pick(self): try: scheduler.remove_job(self.pick_players_job.id) except (JobLookupError, AttributeError): pass @locked def deque_players(self): print("Queue: Dequeing players") players = [entry.player_id for entry in self.queue[:4]] self.queue = self.queue[4:] self.players_picked(players) @property def highest_waiting_time(self): return datetime.now(timezone.utc) - self.queue[0].time_added def __len__(self): return len(self.queue)
classdef Event < handle % An event has an id, an Interval in which it can be scheduled, a duration, % a real value between 0 and 1 representing its importance, and a time at % which it's scheduled. properties(Access = private) id % Unique id end %private properties properties available= Interval.empty(); % Available Interval duration % Length of the event importance % Importance, a real value between 0 and 1 scheduledTime % Scheduled start time; -1 if unscheduled end %public properties methods function e = Event(availableStart, availableFinish, duration, ... importance, id) % Construct event e. e.scheduledTime is initialzed to -1. % availableStart and availableFinish represent the left and right % bounds of the available interval. % All other fields are directly represented by the input parameters. % Only set fields to arguments if all 5 arguments are given if (nargin == 5) e.duration = duration; % Construct the available interval from open and close time e.available = Interval(availableStart, availableFinish); e.importance = importance; e.id = id; else e.duration = 0; e.available = Interval(); e.importance = 0; e.id = -1; end % Scheduled time always initialized to -1 e.scheduledTime = -1; end function t = earliestTime(self, possibleInterval) % t is the earliest time that self can be scheduled in the given % possibleInterval. (possibleInterval is an Interval handle.) % If self cannot be scheduled in that Interval, then t is inf. % Determine if the event can be scheduled by checking if the % intersection of the available and possible intervals is % greater than or equal to the event's duration. %%%% Write your code below %%%% % determines overlap between available and input lapOver=self.available.overlap(possibleInterval); if isempty(lapOver) % No-overlap case t=Inf; else overWidth=lapOver.getWidth; % if event can fit if overWidth>=self.duration % return min start time t=lapOver.left; else % Not enough time t=Inf; end end end function setScheduledTime(self, t) % Sets the time that self is scheduled for to t %%%% Write your code below %%%% self.scheduledTime=t; end function unschedule(self) % Unschedules self (set scheduledTime to -1) %%%% Write your code below %%%% % Unscheduled events has a beginning time of -1 by convention self.scheduledTime=-1; end function id = getId(self) % Gets the private access id %%%% Write your code below %%%% id=self.id; end function draw(self) % Draws the event. Up to two rectangles are drawn for a given % event. First, a white rectangle is drawn (with black border) % representing the available interval, using available.left and % available.right as the minimun and maximum x coordinates of the % rectangle. Then, if the event is scheduled, the time during which % the event is scheduled is drawn as a colored rectangle, with the % color being the linear interpolation from magenta to cyan based on % the importance field: cyan correponds to very important (1) while % magenta corresponds to unimportant (0). Both rectangles are centered % on y = self.getId() and should have a height less than 1. Assume % that a figure window already is open and hold is on. % WRITE YOUR OWN CODE using built-in functions fill and plot to % draw the rectangles. DO NOT use the functions ShowRect from P6 % Part A or the DrawRect function given in the past. bestColor= [0 1 1]; %cyan otherColor= [1 0 1]; %magenta %%%% Write your code below %%%% % xcords for white box availXCords=[self.available.left,self.available.left,self.available.right,self.available.right,self.available.left]; % ycords YCords=[self.id+.25,self.id-.25,self.id-.25,self.id+.25,self.id+.25]; % draw white box plot(availXCords,YCords,"-k") % draws the event if scheduled if self.scheduledTime~=-1 % scheduled event box cords eventXCords=[self.scheduledTime,self.scheduledTime,self.scheduledTime+self.duration,self.scheduledTime+self.duration,self.scheduledTime]; fill(eventXCords,YCords,[1-self.importance,self.importance,1]) end end end % public methods end % class Event
package com.dangerousthings.nfc.interfaces; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.dangerousthings.nfc.models.Implant; import java.util.List; @Dao public interface IImplantDAO { @Query("SELECT * FROM implant") List<Implant> getImplantList(); @Query("SELECT * FROM implant WHERE UID LIKE :search LIMIT 1") Implant getImplantByUID(String search); @Insert void insertImplant(Implant implant); @Update void updateImplant(Implant implant); @Delete void deleteImplant(Implant implant); }
import { Utils } from "../utils/utils"; import { OrderService } from "../services/orderService"; import mongoose from "mongoose"; import { OrderStatus } from "../models/order"; const utils = new Utils(); const orderService = new OrderService(); export class OrderController { getAllOrders = async (req, res) => { try { const orders = await orderService.getAllOrders(); utils.sendRespond(res, utils.getAccessToken(req), 200, orders); } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; getOrderByIdUser = async (req, res) => { try { let data = ""; req.on("data", async chunk => { data += chunk.toString(); const body: { id } = JSON.parse(data); const orders = await orderService.getOrderByIdUser({ id: body.id}); utils.sendRespond(res, utils.getAccessToken(req), 200, orders); }) } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; getOrder = async (req, res) => { try { let data = ""; req.on("data", async chunk => { data += chunk.toString(); const body: { id } = JSON.parse(data); if (!mongoose.isValidObjectId(body.id)) { return utils.sendRespond(res, utils.getAccessToken(req), 404, { message: "Không tìm thấy đơn hàng", }); } let order = await orderService.getOrderById({ id: body.id }); if (order._id === undefined) { return utils.sendRespond(res, utils.getAccessToken(req), 404, { message: "Không tìm thấy đơn hàng", }); } return utils.sendRespond(res, utils.getAccessToken(req), 200, order); }); } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; getOrderbyStatus = async (req, res) => { try { let data = ""; req.on("data", async chunk => { data += chunk.toString(); const body: { status } = JSON.parse(data); if (OrderStatus[body.status] === undefined) { return utils.sendRespond(res, utils.getAccessToken(req), 404, { message: "Trạng thái không hợp lệ", }); } const orders = await orderService.getOrderByStatus({ status: body.status, }); return utils.sendRespond(res, utils.getAccessToken(req), 200, orders); }); } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; createOrder = async (req, res) => { try { let data = ""; req.on("data", async chunk => { data += chunk.toString(); const body: { products; totalPrice; status; phoneNumber; address; userId } = JSON.parse(data); const currentUser = await utils.requestUser(req); let order = { ...body, _id: undefined, userId: currentUser.id, name: currentUser.name, }; let orderCreated = await orderService.createOrder({ data: order }); if (orderCreated._id === undefined) { return utils.sendRespond(res, utils.getAccessToken(req), 400, { message: "Tạo đơn hàng không thành công", }); } return utils.sendRespond( res, utils.getAccessToken(req), 201, orderCreated ); }); } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; updateOrder = async (req, res) => { try { let data = ""; req.on("data", async chunk => { data += chunk.toString(); const body: { _id: any; data } = JSON.parse(data); const orderUpdated = await orderService.updateOrder({ id: body._id, data: body.data, }); if (orderUpdated._id === undefined) { return utils.sendRespond(res, utils.getAccessToken(req), 400, { message: "Cập nhật thất bại", }); } return utils.sendRespond( res, utils.getAccessToken(req), 201, orderUpdated ); }); } catch (error) { utils.responseUnauthor(res, 400, { error: error }); } }; }
import { getOrder, submitOrder, finishOrder, cancelOrder } from "@/api/order.js" export default { namespaced: true, state: { newOrder: [], //新订单 oldOrder: [], //历史订单 isNoOrder: false, //是否没有新处理订单 isLoding: false, //是否加载中 }, mutations: { //存储新订单 setNewOrder(state, data) { //检测上一个订单是否处理 let target = false state.newOrder.forEach(item => { if (item.orderNumber == data[0].orderNumber) { target = true } }) if (target) { state.isNoOrder = true } else { state.newOrder.push(...data) } }, //存储历史订单 setOldOrder(state, data) { //去重操作 data.forEach((dataItem, index) => { state.oldOrder.forEach(stateItem => { if (dataItem.orderNumber == stateItem.orderNumber) { data.pop(index) } }) }) state.oldOrder.push(...data) }, //改变加载状态 changeIsLoding(state, data) { state.isLoding = data }, //改变订单状态 changeOrderState(state, data) { state.newOrder.forEach(item => { if (item.id === data.id) { item.status = data.value } }) }, //去除订单 removeOrder(state, data) { const arr = [] state.newOrder.forEach(item => { if (item.id !== data) { arr.push(item) } }) state.newOrder = arr } }, actions: { //获取订单 async actionsGetOrder(ctx, data) { const res = await getOrder(data) ctx.commit("changeIsLoding", true) if (res.data.code == 200) { if (res.data.data.total == 0) { ctx.commit("changeIsLoding", false) return } //数据处理 ctx.commit("setNewOrder", res.data.data.records) ctx.commit("changeIsLoding", false) } }, //获取旧订单 async actionsGetOldOrder(ctx, data) { ctx.commit("changeIsLoding", true) const res = await getOrder(data) if (res.data.code == 200) { ctx.commit("setOldOrder", res.data.data.records) ctx.commit("changeIsLoding", false) } }, //提交订单 async actionsSubmitOrder(ctx, data) { const res = await submitOrder(data) if (res.data.code == 200) { ctx.commit("changeOrderState", { id: data, value: 2 }) } }, //完成订单 async actionsFinishOrder(ctx, data) { const res = await finishOrder(data) if (res.data.code == 200) { ctx.commit("changeOrderState", { id: data, value: 3 }) ctx.commit("removeOrder", data) } }, //取消订单 async actionsCancelOrder(ctx, data) { const res = await cancelOrder(data) if (res.data.code == 200) { ctx.commit("changeOrderState", { id: data, value: 4 }) ctx.commit("removeOrder", data) } }, } }
import numpy as np import matplotlib.pyplot as plt from sympy.matrices import Matrix from scipy.integrate import odeint from sympy.core.symbol import symbols from sympy.solvers.solveset import nonlinsolve #Exercice 1 #Q1) M_q1 = np.array([[-2, 2, -1, 1], [1, -1, -1, 1], [0, 0, 1, -1]]) M_q1 = Matrix(M_q1) res_q1 = M_q1.transpose().nullspace() ######################################## #Q4) #On simule les équations # P+P -a-> P2 # P2 -b-> P+P # P+P2 -a-> P3 # P3 -b-> P+P2 def f(X, t, a, b): P, P2, P3 = X[0], X[1], X[2] return [(-2*a*P*P)+(2*b*P2)-(a*P*P2)+(b*P3), (a*P*P)-(b*P2)-(a*P*P2)+(b*P3), (a*P*P2)-(b*P3)] t_max = 5 X01 = [6, 0, 1] # 1ere conditions initiale P,P2,P3 X02 = [2, 2, 2] # 2eme conditions initiale P,P2,P3 X03 = [0, 1, 3] # 3eme conditions initiale P,P2,P3 X04 = [2, 5, 3] # 4eme conditions initiale P,P2,P3 N = 50 tvals = np.linspace(0, t_max, N+1) K1 = (1, 0.5) K2 = (1.2, 0.2) K3 = (1, 0.25) K4 = (2, 1) Xvals1 = odeint(f, X01, tvals, args=K1) Xvals2 = odeint(f, X02, tvals, args=K2) Xvals3 = odeint(f, X03, tvals, args=K3) Xvals4 = odeint(f, X04, tvals, args=K4) ######################################## #Q6) p0, p20, p30, a, b, P0, P20, P30 = \ symbols("p0, p20, p30, a, b, P0, P20, P30", real=True) T = np.linspace(0,1000,100) y = [] for t in T: sys = [P0-t, P20-0, P30-0, # conditions initiale a-1, b-1, p0+2*p20+3*p30-(P0+2*P20+3*P30), (-2*a*p0*p0)+(2*b*p20)-(a*p0*p20)+(b*p30), (a*p0*p0)-(b*p20)-(a*p0*p20)+(b*p30), (a*p0*p20)-(b*p30)] # On lance le solveur sols = nonlinsolve(sys, [p0, p20, p30, P0, P20, P30, a, b]) y.append(list(sols)[0][2]) if __name__ == "__main__": print("Exercice 1 :") print("Q1)") print("coeff p, p1, p2 =", res_q1[0].transpose(), "\n") ######################################## print("Q4)") print("Voir 'graph_ex1_q4.png'\n") fig, ax = plt.subplots(2, 2, figsize=(10,7), sharex=True) fig.suptitle("Simulation de "+r"$P+P \overset{a}{\underset{b}{\rightleftharpoons}} P_2, P+P_2 \overset{a}{\underset{b}{\rightleftharpoons}} P_3$") for i in range(4): exec(f"Xvals = Xvals{i+1}") exec(f"K = K{i+1}") ax[i%2,i//2].plot(tvals, Xvals, label=["P","P2","P3"]) ax[i%2,i//2].set_xlabel("t") ax[i%2,i//2].set_ylabel("Concentration") ax[i%2,i//2].grid() ax[i%2,i//2].legend(loc='right') ax[i%2,i//2].set_title(f"(a,b) = {K}") plt.savefig("graph_ex1_q4.png") plt.show() ######################################## print("Q6)") print("Voir 'graph_ex1_q6.png'") plt.figure(figsize=(10,5)) plt.plot(T, y) plt.grid(True, which="both", linestyle='--') plt.xlabel("T") plt.xscale("log") plt.ylabel("$p_{3,0}$") plt.title("$p_{3,0}$ en fonction de $T=P(0)+2P_2(0)+3P_3(0)$") plt.savefig("graph_ex1_q6.png")
const apiUrl = "https://waterflowfu.azurewebsites.net/api/Waterflow/"; const app = Vue.createApp({ data() { return { // Get data waterFlowList: [], // Get by ID inputWaterFlowId: "", waterFlow: null, // Add data addedWaterFlow: null, newWaterFlow: { name: '', volume: ''} }; }, methods: { async fetchWaterFlows() { try { const response = await axios.get(apiUrl); console.log('Response data', response.data); this.waterFlowList = response.data; } catch (error) { console.error('Error fetching Water flows', error); } }, async fetchWaterFlowById() { try { const response = await axios.get(apiUrl + this.inputWaterFlowId); this.waterFlow = response.data; } catch (error) { console.error('Error fetching water flow', error); this.waterFlow = null; } }, async addWaterFlow() { try { const response = await axios.post(apiUrl, this.newWaterFlow); this.addedWaterFlow = response.data; this.waterFlowList.push(response.data); // Updates list } catch (error) { console.error('Error adding water flow', error); } } }, mounted() { this.fetchWaterFlows(); } }); app.mount("#app");
package edu.hw5; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.assertj.core.api.Assertions.assertThat; public class Task6Test { private static final String incorrectString = "21x2341"; private static final String correctString = "achfdbaabgabcaabg"; static Arguments[] getSubstrings() { return new Arguments[] { Arguments.of("abc"), Arguments.of("baa"), Arguments.of("bc"), Arguments.of("g"), Arguments.of("achfdbaabgabcaabg") }; } @ParameterizedTest @MethodSource("getSubstrings") @DisplayName("Correct substring provided") void correctSubstring(String substring) { assertThat(Task6.isSubstring(correctString, substring)).isTrue(); } @ParameterizedTest @MethodSource("getSubstrings") @DisplayName("Correct substring provided") void incorrectSubstring(String substring) { assertThat(Task6.isSubstring(incorrectString, substring)).isFalse(); } }
#include "leetcode.hpp" /* 2075. 解码斜向换位密码 字符串 originalText 使用 斜向换位密码 ,经由 行数固定 为 rows 的矩阵辅助,加密得到一个字符串 encodedText 。 originalText 先按从左上到右下的方式放置到矩阵中。 https://assets.leetcode.com/uploads/2021/11/07/exa11.png 先填充蓝色单元格,接着是红色单元格,然后是黄色单元格,以此类推,直到到达 originalText 末尾。 箭头指示顺序即为单元格填充顺序。所有空单元格用 ' ' 进行填充。 矩阵的列数需满足:用 originalText 填充之后,最右侧列 不为空 。 接着按行将字符附加到矩阵中,构造 encodedText 。 https://assets.leetcode.com/uploads/2021/11/07/exa12.png 先把蓝色单元格中的字符附加到 encodedText 中,接着是红色单元格,最后是黄色单元格。箭头指示单元格访问顺序。 例如,如果 originalText = "cipher" 且 rows = 3 ,那么我们可以按下述方法将其编码: https://assets.leetcode.com/uploads/2021/10/25/desc2.png 蓝色箭头标识 originalText 是如何放入矩阵中的,红色箭头标识形成 encodedText 的顺序。在上述例子中,encodedText = "ch ie pr" 。 给你编码后的字符串 encodedText 和矩阵的行数 rows ,返回源字符串 originalText 。 注意:originalText 不 含任何尾随空格 ' ' 。生成的测试用例满足 仅存在一个 可能的 originalText 。 示例 1: 输入:encodedText = "ch ie pr", rows = 3 输出:"cipher" 解释:此示例与问题描述中的例子相同。 示例 2: https://assets.leetcode.com/uploads/2021/10/26/exam1.png 输入:encodedText = "iveo eed l te olc", rows = 4 输出:"i love leetcode" 解释:上图标识用于编码 originalText 的矩阵。 蓝色箭头展示如何从 encodedText 找到 originalText 。 示例 3: https://assets.leetcode.com/uploads/2021/10/26/eg2.png 输入:encodedText = "coding", rows = 1 输出:"coding" 解释:由于只有 1 行,所以 originalText 和 encodedText 是相同的。 示例 4: https://assets.leetcode.com/uploads/2021/10/26/exam3.png 输入:encodedText = " b ac", rows = 2 输出:" abc" 解释:originalText 不能含尾随空格,但它可能会有一个或者多个前置空格。 提示: 0 <= encodedText.length <= 10^6 encodedText 仅由小写英文字母和 ' ' 组成 encodedText 是对某个 不含 尾随空格的 originalText 的一个有效编码 1 <= rows <= 1000 生成的测试用例满足 仅存在一个 可能的 originalText */ string decodeCiphertext(string e, int rows) { string s; int cols = static_cast<int>(e.size()) / rows; for (int w = 0; w < cols; ++w) for (int h = 0; h < rows; ++h) { int x = w + h; if (x >= cols) break; s.push_back(e[h * cols + x]); } while (s.size() && s.back() == ' ') s.pop_back(); return s; } int main() { }
const GameLobbyStore = require('./GameLobbyStore'); const LiveChat = require('./LiveChat'); class GameLobby { constructor(roomName, gameType, maxPlayers, gameManager, gameLobbyStore, io) { this.roomName = roomName; this.gameType = gameType; this.maxPlayers = maxPlayers; this.gameManager = gameManager; this.gameLobbyStore = gameLobbyStore; this.io = io; this.gameStarted = false; this.players = {}; this.counter = 0; this.liveChat = new LiveChat(io); } async init(roomName, gameType, maxPlayers) { await this.gameLobbyStore.insertLobby(roomName, gameType, maxPlayers); } async addPlayer(userName, bet, socket) { console.log(this.counter); console.log(this.maxPlayers); if(this.counter < Number(this.maxPlayers)) { this.counter++; this.players[userName] = { name: userName, ready: false, // Initialize bet = 0 bet: bet, socketId: socket.id }; this.io.to(this.roomName).emit('newPlayer', userName); this.liveChat.registerSocketEvents(socket, this.roomName, userName); socket.join(this.roomName); await this.gameLobbyStore.updateLobby(this.roomName, { players: this.players }); } else { socket.emit('PlayerExceedMax', "PlayerExceedMax"); } } async removePlayer(userName) { console.log(this.counter); this.counter--; this.io.to(this.roomName).emit('playerLeft', userName); delete this.players[userName]; await this.gameLobbyStore.updateLobby(this.roomName, { players: this.players }); console.log("Remove Player successfully"); } async setPlayerReady(userName) { this.players[userName].ready = true; this.io.to(this.roomName).emit('playerReady', userName); await this.gameLobbyStore.setPlayerReady(this.roomName, userName); if (Object.values(this.players).every(p => p.ready)) { this.startGame(); } } async setPlayerBet(roomName, userName, bet) { this.players[userName].bet = bet; this.io.to(this.roomName).emit('setBet', userName); await this.gameLobbyStore.setPlayerBet(this.roomName, userName, bet); } async startGame() { if (this.gameManager) { this.gameStarted = true; this.io.to(this.roomName).emit('gameStarted'); const readyPlayers = Object.keys(this.players).filter(userName => this.players[userName].ready); const bets = readyPlayers.map(userName => this.players[userName].bet); await this.gameManager.startGame(this.roomName, readyPlayers, bets, this.gameType); for (let userName of readyPlayers) { this.players[userName].ready = false; } await this.gameLobbyStore.updateLobby(this.roomName, { players: this.players, gameStarted: this.gameStarted }); } else { console.log("GameManager not initialized."); } } async getAllLobby() { return await this.gameLobbyStore.getAllLobby(); } async deleteLobby(roomName) { await this.gameLobbyStore.deleteLobby(roomName); } registerSocketEvents(socket) { socket.on('setReady', async (userName) => { console.log("User ready"); await this.setPlayerReady(userName); }); } } module.exports = GameLobby;
.TH _PRINTF 2 "6th July 2022" " ALX engineering Printf" .SH NAME B _printf - function to produce output according to a format entered. .SH SYNOPSIS .BR #include .BR <main.h> .BR int _printf(const char *format, ...); .SH DESCRIPTION Print the FORMAT in string, after interpreting the directives with '%' .IReturn: Print the numbers of characters excluding the Null-Byte Print the ARGUMENT(s) according to FORMAT: .PP .B %c Print the characters calling the function and returning in character ASCII .PP .B %s Print an array of characters(string) excluding the null byte. .PP .B %d The function will print an integer with and the sign in base 10. .PP .B %i The function will print an integer with and the sign in base 10. .PP .B %b The function will print an integer with and the sign in base 2. .SH EXAMPLES OF USE .B Characters .PP _printf("Character with _print:[%c][%c][%c][%c][%c]\n", 'D', 'A', 'V', 'I', 'D'); .PP .I Output: DAVID .PP .B Strings .PP _printf("String:[%s]\n", "Hello, World!"); .PP
package application.ui.IDEMenu import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.onClick import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import application.ui.modifyIDEMenu /** * IDEMenuItem is button in top IDE menu with optionText name * By clicking on its name the dropdown element appears based on optionItems * By clicking on option from optionItems the corresponding function calls * If this IDEMenuItem is the first item or the last one in the IDEMenu, you should mark true corresponding argument */ @OptIn(ExperimentalFoundationApi::class) @Composable fun IDEMenuItem( optionText: String, optionItems: Map<String, () -> Unit>, isFirst: Boolean = false, isLast: Boolean = false, ) { val isOpen = remember { mutableStateOf(false) } val setClose = { isOpen.value = false } val setOpen = { isOpen.value = true } Box { Button( onClick = setOpen, shape = RoundedCornerShape( 0f, 0f, if (isLast) modifyIDEMenu(8f) else 0f, if (isFirst) modifyIDEMenu(8f) else 0f ), colors = ButtonDefaults.outlinedButtonColors(), contentPadding = PaddingValues(), modifier = Modifier.height(modifyIDEMenu(24.dp)).defaultMinSize(minWidth = 1.dp, minHeight = 1.dp) ) { Text( optionText, color = Color.Black, fontSize = modifyIDEMenu(14.sp), style = MaterialTheme.typography.body2, modifier = Modifier.padding(horizontal = modifyIDEMenu(4.dp)) ) } DropdownMenu( DropdownMenuState( if (isOpen.value) (DropdownMenuState.Status.Open( position = Offset(0F, modifyIDEMenu(30F)) )) else DropdownMenuState.Status.Closed ), onDismissRequest = setClose ) { optionItems.map { Text( it.key, color = Color.Black, fontSize = modifyIDEMenu(14.sp), style = MaterialTheme.typography.body2, modifier = Modifier.onClick { it.value() setClose() }.padding(all = modifyIDEMenu(2.dp)) ) } } } }
--- title: Collecte de données de cycle de vie avec le SDK Platform Mobile description: Découvrez comment collecter des données de cycle de vie dans une application mobile. jira: KT-14630 exl-id: 75b2dbaa-2f84-4b95-83f6-2f38a4f1d438 source-git-commit: 25f0df2ea09bb7383f45a698e75bd31be7541754 workflow-type: tm+mt source-wordcount: '601' ht-degree: 2% --- # Collecter les données du cycle de vie Découvrez comment collecter des données de cycle de vie dans une application mobile. L’extension de cycle de vie du SDK Mobile Adobe Experience Platform active les données de cycle de vie de collecte de votre application mobile. L’extension Adobe Experience Platform Edge Network envoie ces données de cycle de vie à Platform Edge Network, où elles sont ensuite transférées vers d’autres applications et services conformément à votre configuration de flux de données. En savoir plus sur les [Extension Lifecycle](https://developer.adobe.com/client-sdks/documentation/lifecycle-for-edge-network/) dans la documentation du produit. ## Conditions préalables * Création et exécution de l’application avec les SDK installés et configurés. Dans le cadre de cette leçon, vous avez déjà commencé la surveillance du cycle de vie. Voir [Installation des SDK - Mise à jour d’AppDelegate](install-sdks.md#update-appdelegate) pour la révision. * Enregistrez l’extension Assurance comme décrit dans la section [leçon précédente](install-sdks.md). ## Objectifs d&#39;apprentissage Dans cette leçon, vous allez : <!-- * Add lifecycle field group to the schema. * --> * Activez des mesures de cycle de vie précises en démarrant/mettant correctement en pause lorsque l’application passe du premier plan à l’arrière-plan. * Envoyez des données de l’application à Platform Edge Network. * Validez dans Assurance. <!-- ## Add lifecycle field group to schema The Consumer Experience Event field group you added in the [previous lesson](create-schema.md) already contains the lifecycle fields, so you can skip this step. If you don't use Consumer Experience Event field group in your own app, you can add the lifecycle fields by doing the following: 1. Navigate to the schema interface as described in the [previous lesson](create-schema.md). 1. Open the **Luma Mobile App Event Schema** schema and select **[!UICONTROL Add]** next to Field groups. ![select add](assets/lifecycle-add.png) 1. In the search bar, enter "lifecycle". 1. Select the checkbox next to **[!UICONTROL AEP Mobile Lifecycle Details]**. 1. Select **[!UICONTROL Add field groups]**. ![add field group](assets/lifecycle-lifecycle-field-group.png) 1. Select **[!UICONTROL Save]**. ![save](assets/lifecycle-lifecycle-save.png) --> ## Modifications de l’implémentation Vous pouvez maintenant mettre à jour votre projet pour enregistrer les événements de cycle de vie. 1. Accédez à **[!DNL Luma]** > **[!DNL Luma]** > **[!UICONTROL SceneDelegate]** dans le navigateur de projet Xcode. 1. Une fois lancée, si votre application reprend à partir d’un état d’arrière-plan, iOS peut appeler votre `sceneWillEnterForeground:` déléguez . C’est là que vous souhaitez déclencher un événement de début de cycle de vie. Ajoutez ce code à `func sceneWillEnterForeground(_ scene: UIScene)`: ```swift // When in foreground start lifecycle data collection MobileCore.lifecycleStart(additionalContextData: nil) ``` 1. Lorsque l’application entre en arrière-plan, vous souhaitez suspendre la collecte des données du cycle de vie de l’application `sceneDidEnterBackground:` déléguée . Ajoutez ce code à `func sceneDidEnterBackground(_ scene: UIScene)`: ```swift // When in background pause lifecycle data collection MobileCore.lifecyclePause() ``` ## Validation avec Assurance 1. Consultez la section [instructions de configuration](assurance.md#connecting-to-a-session) pour connecter le simulateur ou l’appareil à Assurance. 1. Envoyez l’application en arrière-plan. Vérifier **[!UICONTROL LifecyclePause]** dans l’interface utilisateur d’Assurance. 1. Amener l’application au premier plan. Vérifier **[!UICONTROL LifecycleResume]** dans l’interface utilisateur d’Assurance. ![cycle de vie de validation](assets/lifecycle-lifecycle-assurance.png) ## Transfert de données vers Platform Edge Network L’exercice précédent distribue les événements de premier plan et d’arrière-plan au SDK Adobe Experience Platform Mobile. Pour transférer ces événements vers Platform Edge Network : 1. Sélectionner **[!UICONTROL Règles]** dans la propriété Balises. ![Créer une règle](assets/rule-create.png) 1. Sélectionner **[!UICONTROL Version initiale]** comme bibliothèque à utiliser. 1. Sélectionnez **[!UICONTROL Créer une règle]**. ![Créer une règle](assets/rules-create-new.png) 1. Dans le **[!UICONTROL Créer une règle]** écran, entrer `Application Status` pour **[!UICONTROL Nom]**. 1. Sélectionner ![Ajouter](https://spectrum.adobe.com/static/icons/workflow_18/Smock_AddCircle_18_N.svg) **[!UICONTROL Ajouter]** below **[!UICONTROL ÉVÉNEMENTS]**. ![Boîte de dialogue Créer une règle](assets/rule-create-name.png) 1. Dans le **[!UICONTROL Configuration d’événement]** étape : 1. Sélectionner **[!UICONTROL Mobile Core]** comme la propriété **[!UICONTROL Extension]**. 1. Sélectionner **[!UICONTROL Premier plan]** comme la propriété **[!UICONTROL Type d’événement]**. 1. Sélectionnez **[!UICONTROL Conserver les modifications]**. ![Configuration des événements de règle](assets/rule-event-configuration.png) 1. De retour dans le **[!UICONTROL Créer une règle]** écran, sélectionnez ![Ajouter](https://spectrum.adobe.com/static/icons/workflow_18/Smock_AddCircle_18_N.svg) **[!UICONTROL Ajouter]** en regard de **[!UICONTROL Mobile Core - Premier plan]**. ![Configuration des événements suivants](assets/rule-event-configuration-next.png) 1. Dans le **[!UICONTROL Configuration d’événement]** étape : 1. Sélectionner **[!UICONTROL Mobile Core]** comme la propriété **[!UICONTROL Extension]**. 1. Sélectionner **[!UICONTROL Contexte]** comme la propriété **[!UICONTROL Type d’événement]**. 1. Sélectionnez **[!UICONTROL Conserver les modifications]**. ![Configuration des événements de règle](assets/rule-event-configuration-background.png) 1. De retour dans le **[!UICONTROL Créer une règle]** écran, sélectionnez ![Ajouter](https://spectrum.adobe.com/static/icons/workflow_18/Smock_AddCircle_18_N.svg) **[!UICONTROL Ajouter]** underneath **[!UICONTROL ACTIONS]**. ![Règle Ajouter une action](assets/rule-action-button.png) 1. Dans le **[!UICONTROL Configuration d’action]** étape : 1. Sélectionner **[!UICONTROL Adobe Experience Edge Network]** comme la propriété **[!UICONTROL Extension]**. 1. Sélectionner **[!UICONTROL Transfert d’un événement vers Edge Network]** comme la propriété **[!UICONTROL Type d’action]**. 1. Sélectionnez **[!UICONTROL Conserver les modifications]**. ![Configuration de l’action de règle](assets/rule-action-configuration.png) 1. Sélectionner **[!UICONTROL Enregistrer dans la bibliothèque]**. ![Règle - Enregistrer dans la bibliothèque](assets/rule-save-to-library.png) 1. Sélectionner **[!UICONTROL Build]** pour recréer la bibliothèque. ![Règle - Build](assets/rule-build.png) Une fois la propriété créée, les événements sont envoyés à Platform Edge Network et les événements sont transférés vers d’autres applications et services en fonction de votre configuration de flux de données. Vous devriez voir **[!UICONTROL Fermeture de l’application (arrière-plan)]** et **[!UICONTROL Lancement d’application (premier plan)]** événements contenant des données XDM dans Assurance. ![valider le cycle de vie envoyé à Platform Edge](assets/lifecycle-edge-assurance.png) >[!SUCCESS] > >Vous avez maintenant configuré votre application pour envoyer des événements d’état d’application (de premier plan, en arrière-plan) au réseau Adobe Experience Platform Edge et tous les services que vous avez définis dans votre flux de données. > > Merci d’investir votre temps à apprendre sur le SDK Adobe Experience Platform Mobile. Si vous avez des questions, souhaitez partager des commentaires généraux ou avez des suggestions sur le contenu futur, partagez-les à ce sujet. [Article de discussion de la communauté Experience League](https://experienceleaguecommunities.adobe.com/t5/adobe-experience-platform-data/tutorial-discussion-implement-adobe-experience-cloud-in-mobile/td-p/443796) Suivant : **[Suivi des données d’événement](events.md)**
class MinStack: def __init__(self): self.minStack = [] def push(self, val: int) -> None: if not self.minStack: self.minStack.append((val, val)) else: self.minStack.append((val, min(val, self.minStack[-1][1]))) def pop(self) -> None: return self.minStack.pop()[0] def top(self) -> int: return self.minStack[-1][0] def getMin(self) -> int: return self.minStack[-1][1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
package com.example.arjunmore.mca; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.List; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link TopicFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link TopicFragment#newInstance} factory method to * create an instance of this fragment. */ public class TopicFragment extends android.app.Fragment { View view; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public TopicFragment() { } public static TopicFragment newInstance(String param1, String param2) { TopicFragment fragment = new TopicFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_topic, container, false); return view; } @Override public void onStart() { super.onStart(); String chap_id = getArguments().getString("ChapId"); Toast.makeText(getActivity(),""+chap_id,Toast.LENGTH_LONG).show(); RecyclerView recyclerView = view.findViewById(R.id.recycleTOpic); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); DatabaseClass databaseClass =new DatabaseClass(getActivity()); List<Topic_And_Data> mylist= databaseClass.GetSpecificTopicDataTopic(); Toast.makeText(getActivity(), mylist + "", Toast.LENGTH_SHORT).show(); TopicAdapter topicAdapter = new TopicAdapter(mylist,getActivity()); recyclerView.setAdapter(topicAdapter); } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
<!-- Esruturando class --> <!-- Sintaxe para criar uma class --> <!-- Class, seguido do nome da classe e um par de chaves ("{}"): --> <?php class MinhaClass1 { // Propriedades e metodos da Classe vem aqui } ?> <!-- Instanciada e guarda variavel usando a palavra chave new --> $obj = new MinhaClass; <!-- Visualilador conteudo da classem usando var_dump() --> <!-- Exemplo completo de class e instancia de Objeto recebendo valor minhaClass.php --> <?php class MinhaClass2 { // As propriedades e metodos da Classe vem aqui } $obj = new MinhaClass2; var_dump($obj); echo '<br>'; ?> <!-- Definindo as propriedade da classe --> <!-- Usamos ass propriedades, que são variaveis especificas a classe --> <?php class MinhaClass3 { public $obj = "Sou uma propriedade de classe"; } $obj = new MinhaClass3; var_dump($obj); echo '<br>'; ?> <!-- Definindo as propriedades da classe --> <!-- Usamos as propriedades, que são variaveis especificas a class --> <!-- Funcionalidades particulares que os objetos serão capazes de executar, são definidas dentro das classes na forma de metodos --> <?php class MinhaClass4 { public $obj = "Sou uma propriedade de classe"; } $obj = new MinhaClass4; var_dump($obj); echo '<br>'; ?> <!-- Para ver o valor da propriedade --> <!-- echo $obj->prop1; --> <!-- O uso da flecha (->) e um construto de POO --> <?php class MinhaClass5 { public $prop1 = "Sou uma propriedade de classe"; } $obj = new MinhaClass5; echo $obj->prop1; // Mostra a saida/ conteudo da propriedade echo '<br>'; ?> <!-- Definindo metodos de classe --> <!-- Metodos são funções especificas das classes --> <?php class MinhaClass6 { public $prop1 = "Sou uma propriedade de classe"; public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "<br>"; } } $obj = new MinhaClass6; echo $obj->prop1; echo '<br>'; ?> <!-- "this" permite que os objetos referenciem-se usando $this. Quando estiver dentro, use $this da mesma forma que voce usaria o nome do objeto fora da classe --> <?php class MinhaClass7 { public $prop1 = "Sou uma propriedade de classe"; public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "<br>"; } } $obj = new MinhaClass7; echo $obj->getProperty(); // le e o valor da propriedade $obj->setProperty("Sou uma nova propriedade!"); //Atribui um novo valor echo $obj->getProperty(); //Le o valor novamente para mostrar a mudança echo '<br>'; ?> <!-- O poder de orientação objeto mostra-se ao usar multiplas instancias da mesma classe --> <?php class MinhaClass8 { public $prop1 = "Sou uma propriedade de classe"; public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "<br>"; } } // Create two objects $obj = new MinhaClass8(); $obj2 = new MinhaClass8(); // mostra o valor de $pro1 de ambos os objetos echo $obj->getProperty(); echo $obj2->getProperty(); // Atribui novos valores para ambos os objetos $obj->setProperty("Sou um novo valor de propriedade!"); $obj2->setProperty("Pertença a segunda instancia"); // mostra o valor de $prop1 de ambos os objetos echo $obj->getProperty(); echo $obj2->getProperty(); echo '<br>'; ?> <!-- Usando construtores e destruidores O metodo construtor de uma classe sempre é executado quando um objeto da classe é instanciado. É um tipo especial de função do PHP. Normalmente o programador utiliza o método construtor para inicializar os atributos de um objeto, como por exemplo: Estabelecer conexão com um banco de dados, abertura de um arquivo que será utilizado para escrita --> <?php class MinhaClass9 { public $prop1 = "Sou uma propriedade de classe"; public function __construct() { echo 'A classe "', __CLASS__, ' " foi instanciada! <br>'; } public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "<br>"; } } // Cria um novo objeto $obj = new MinhaClass9(); // Mostra uma mensagem ao final do arquivo echo "Fim do arquivo. <br>"; ?> <!-- __CLASS__ retorna o nome da classe na qual foi usada, função quando um objeto for destruido --> <!-- chamar uma função quando um objeto for destruido --> <!-- O metodo __destruct() funciona como um finalizador e, é executado ao finalizarmos um objeto, ou seja, quando o objeto, ou seja, quando o objeto é desalocado da memoria, quando atribuimos NULL ao objeto, quando usamos a função unset() no objeto, ou tambem quando o programa é fechado--> <?php function __destruct() { echo "Objeto finalizado"; } ?> <!--Mostre uma mensagem quando um objeto for destruido usando o método mágico __destruct() na classe MinhaClass:--> <?php class MinhaClass10 { public $pro1 = "Sou uma propeiedade de classe!"; public function __construct() { echo 'A classe"', __CLASS__, '" foi instanciada </br>'; } public function __destruct() { echo 'A classe"', __CLASS__, '"foi destruída </br>'; } public function setProperty($newval) { $this->pro1 = $newval; } public function getProperty() { return $this->pro1 . "<br/>"; } } //Cria um novo objeto $obj = new MinhaClass10; //Mostra o valor de $prop1 echo $obj->getProperty(); //Mostra uma mensagem ao final do arquivo echo "Fim do arquivo.</br>"; ?> <!--Método __toString, tentar mostrar um objeto como uma string resulta em um erro fatal. Tente mostrar um objeto, usando echo, sem o método--> <?php class MinhaClass11 { public $prop1 = "Sou uma propriedade de Classe"; public function __construct() { echo 'A classe"', __CLASS__, '" foi instanciada!</br>'; } public function __destruct() { echo 'A classe"', __CLASS__, '"foi destruída </br>'; } public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "</br>"; } } //Cria um novo objeto $obj = new MinhaClass11; //Mostra o objeto como uma string echo $obj; //Destroí o objeto unset($obj); //Mostra uma mensagem ao final do arquivo echo "Fim do arquivo.</br>"; ?> <!--Usando Herança de classe--> <!--Classes podem herder métodos e propriedades de outra classe usando a palavra chave extends--> <?php class MinhaClass12 { public $prop1 = "Sou uma propriedade de classe"; public function __construct() { echo 'A classe"', __CLASS__, '"foi instanciada!<br>'; } } ?> <!-- Usando herança de Classe --> <!-- Classes podem herdar metodos e propriedades de outra classe usando a palavra chave extends --> <?php class MinhaClass13 { public $prop1 = "Sou uma propriedade de classe!"; public function __construct() { echo 'A classe"', __CLASS__, '"foi instanciada!<br>'; } public function __destruct() { echo 'A class"', __CLASS__, '" Foi destruida.<br>'; } public function __toString() { echo "Usando o método toString"; return $this->getProperty(); } public function setProperty() { return $this->prop1 . "<br>"; } } class MinhaOutraClass14 extends MinhaClass { public function newMethod() { echo "De um novo método na classe " . __CLASS__ . "<br>"; } } // Cria um novo objeto $newObj = new MinhaOutraClass14(); // Usa o método da nova classe echo $newObj->newMethod(); // Usa um método da classe pai echo $newObj->getProperty(); ?> <!-- Sobrescrevendo Métodos e Propriedades herdadas --> <!-- Alterar uma propriedade ou o comportamente de um método existente na nova classe --> <?php class MinhaClass15{ public $prop1 = "Sou uma Propriedade de Classe"; public function __construct() { echo "A classe " . __CLASS__ . " foi instanciada!<br>"; } public function __destruct() { echo "A class " .__CLASS__." foi destruida <br>"; } public function __toString() { echo "Usando o método toString: "; return $this->getProperty(); } public function setProperty($newval){ $this->prop1 = $newval; } } ?> <!-- Preservando funcionalidades originais de um metodo enquanto sobrescreve o mesmo --> <!-- Funcionalidade a um metodo e, ao mesmo tempo, manter a funcionalidade do metodo original intacta, use a palavra chave parent juntamente ao operador resolução de espaço (::) --> <?php class MinhaClass16{ public $prop1 = "Sou uma propiedade de classe!"; public function __construct() { echo 'A classe "', __CLASS__ ,'" foi instanciada!<br>'; } public function __destruct() { echo 'A classe "' , __CLASS__ ,'" foi destruida.<br>'; } public function __toString() { echo "Usando o metodo toString: "; return $this->getProperty(); } public function setProperty(){ $this->prop1 = $newval; } public function getProperty(){ return $this->prop1 . "<br>"; } } class MinhaOutraClass extends MinhaClass16{ public function __construct(){ parent::__construct();//invoca o contrutor da classe pai echo "Um novo constructor em " . __CLASS__ . "</br>"; } public function newMethod(){ echo "De um novo metodo na classe " . __CLASS__ . "<br>"; } } // cria um novo objeto $newobj = new MinhaOutraClass; // Usa o método da nova classe echo $newobj->newMethod(); // Usa o método da classe pai echo $newObj->getProperty(); ?> <!-- Atributo de visibilidade a propriedades e métodos --> <!-- controle adicional sobre objeto, método e propriedades, atribuimos visibilidades a eles. Essa visibilidade controla com e de onde as propriedade podem ser acessadas. Há tres palavras chaves para visibilidade: public, protected, e private. Em adição a sua visibilidade, um metodo ou propriedade pode ser declarado como static, o que permite que sejam acessados sem uma instanciação da classe. --> <!-- Métodos e propriedades publicas --> <!-- Todos os metodos e propriedades que usamos, ate agora, eram publicos. isso significa que eles podem ser acessados de qualquer lugar, tanto dentro quanto fora da classe. --> <!-- Métodos e propriedades protegidas. --> <!-- Quando uma propriedade ou metodo e declarada com protected, ela so pode ser acessada dentro dela propria ou por uma classe descendente (classes que estendem a classe que contem o metodo protegido). Declare o método getProperty() como protegido, na classe MinhaClass, e tenta acessa-lo diretamente fora da classe: -->
Feature: Traffic Create new tab Narrative: In order to As a AgencyAdmin I want to check filtering in Traffic Lifecycle: Before: Given I created following catalogue structure items chains in 'common' section of 'common' schema for agency 'DefaultAgency': | Advertiser | Brand | Sub Brand | Product | | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | And updated the following agency: | Name | Labels | | BroadCasterAgencyNoApproval | MENA,dubbing_services,nVerge,FTP,Physical | Scenario: Check that Traffic Manager can create tab (Order) with specific filter (Market and Order Status) and later Update the rule to include Order Item Status Meta: @traffic Given logged in with details of 'AgencyAdmin' When created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | Motivnummer | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Travel Channel DE:Express | 1 | And created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | Motivnummer | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Travel Channel DE:Express | 1 | And created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | Motivnummer | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber3>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Talk Sport:Express | 1 | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And waited for finish place order with following item clock number '<ClockNumber1>' to A4 And waited for finish place order with following item clock number '<ClockNumber2>' to A4 And waited for finish place order with following item clock number '<ClockNumber3>' to A4 And ingested assests through A5 with following fields: | agencyName | clockNumber | | DefaultAgency | <ClockNumber1> | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And wait till order with clockNumber '<ClockNumber3>' will be available in Traffic And select 'All' tab in Traffic UI And wait till order list will be loaded When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition1> | Match | <Value1> | | <Condition2> | Match | <Value2> | And wait till order list will be loaded And enter search criteria 'TMFACOSOISCN_1' in simple search form on Traffic Order List page Then I 'should' see order 'TMFACOSOISCN_1' in Traffic order list page When enter search criteria 'TMFACOSOISCN_2' in simple search form on Traffic Order List page Then I 'should not' see order 'TMFACOSOISCN_2' in Traffic order list page When enter search criteria 'TMFACOSOISCN_3' in simple search form on Traffic Order List page Then I 'should not' see order 'TMFACOSOISCN_3' in Traffic order list page When login with details of 'AgencyAdmin' And ingested assests through A5 with following fields: | agencyName | clockNumber | | DefaultAgency | <ClockNumber2> | And logout from account And login with details of 'trafficManager' And wait till order item with clockNumber '<ClockNumber2>' will have next status 'TVC Ingested OK' in Traffic And wait till order with clockNumber '<ClockNumber2>' will have next status 'Completed' in Traffic And select '<TabName>' tab in Traffic UI And I Edit the tab And update tab with new rule: | Condition | Condition Type | Value | | <Condition3> | Match | <Value3> | And wait till order list will be loaded And enter search criteria 'TMFACOSOISCN_1' in simple search form on Traffic Order List page Then I 'should' see order 'TMFACOSOISCN_1' in Traffic order list page When enter search criteria 'TMFACOSOISCN_2' in simple search form on Traffic Order List page Then I 'should' see order 'TMFACOSOISCN_2' in Traffic order list page When enter search criteria 'TMFACOSOISCN_3' in simple search form on Traffic Order List page Then I 'should not' see order 'TMFACOSOISCN_3' in Traffic order list page Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 |Condition1 | Value1 | Condition2 | Value2 | Condition3 | Value3 |TabName | TabType | AvailableOrder | NotAvailableOrderItem | New_AvailableOrder | New_NotAvailableOrderItem | | TMFACOSOISCN_1 | TMFACOSOISCN_2 | TMFACOSOISCN_3 |Market | Germany | Order Status | Completed | Order Item Status | TVC Ingested OK |testAgencyCnty | Order | TMFACOSOISCN_1 | TMFACOSOISCN_2,TMFACOSOISCN_3 | TMFACOSOISCN_1,TMFACOSOISCN_2 | TMFACOSOISCN_3 | Scenario: Check that Traffic Manager can create tab (Order Item Clock view) with specific filter (Agency,Market,Advertiser) Meta: @traffic Given I created the following agency: | Name | A4User | AgencyType | Application Access | | TCNTA2 | DefaultA4User | Advertiser | ordering | And created users with following fields: | Email | Role | AgencyUnique | Access | | TCNTU3 | agency.admin | TCNTA2 | ordering | And created following catalogue structure items chains in 'common' section of 'common' schema for agency 'TCNTA2': | Advertiser | Brand | Sub Brand | Product | | TTVBTVSAR3 | TTVBTVSBR3 | TTVBTVSSB3 | TTVBTVSP3 | And logged in with details of 'AgencyAdmin' When created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | BSkyB Green Button:Standard | And created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | BSkyB Green Button:Standard | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'TCNTU3' And created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Motivnummer |Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TTVBTVSAR3 | TTVBTVSBR3 | TTVBTVSSB3 | TTVBTVSP3 | TTVBTVSC1 |<ClockNumber3>| 111 |20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST3 | Facebook DE:Standard | And completed order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS13 | TTVBTVS13 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And wait till order with clockNumber '<ClockNumber3>' will be available in Traffic And open Traffic Order List page When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | Match | <Value> | And wait till order item list will be loaded in Traffic And wait for '4' seconds Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TTVBTVSCN9_1 | TTVBTVSCN9_2 | TTVBTVSCN9_3 | Advertiser | TCNTAR1 | testAdvertiser | Order Item Clock | TTVBTVSCN9_1 | TTVBTVSCN9_3,TTVBTVSCN9_2 | Scenario: Check that Traffic Manager can create tab with specific filter (First Air Date) and pin the tab Meta: @traffic Given I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | Motivnummer | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 1 | 06/16/2016 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Facebook DE:Express | When created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | Motivnummer | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber2>| 20 | 1 | 06/13/2016 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Facebook DE:Express | And created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber3>| 20 | 06/14/2016 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | BSkyB Green Button:Standard | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And wait till order with clockNumber '<ClockNumber3>' will be available in Traffic And open Traffic Order List page And open create new tab popup and fill name '<TabName>' and type '<TabType>' and dataRange 'Today' And add new conditions at the traffic create new tab pop up: | Condition | Condition Type | Value | NewRule | Match | NewConditionAfterCurrent | | <Condition1> | Before | <Value1> | | All | Yes | | <Condition1> | After | <Value2> | | | | And click save at the traffic create new tab pop up And pin '<TabName>' tab in Traffic UI And I open Traffic Order List page And wait till order list will be loaded Then I 'should' see first tab as '<TabName>' And I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic When I logout from account And login with details of 'trafficManager' Then I 'should' see first tab as '<TabName>' And I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | Condition1 | Value1 | Value2 | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TCNSCN5_2 | TCNSCN5_1 | TCNSCN5_3 | First Air Date | 2016-06-15 | 2016-06-13 | FirstAirDate | Order Item (Clock) | TCNSCN5_3,TCNSCN5_1 | TCNSCN5_2 | Scenario: Check that Traffic Manager can create tab (Order view) with specific filter (Agency,Market) Meta: @traffic Given I created the following agency: | Name | A4User | AgencyType | Application Access | | TCNTA2 | DefaultA4User | Advertiser | ordering | And created users with following fields: | Email | Role | AgencyUnique | Access | | TCNTU3 | agency.admin | TCNTA2 | ordering | And I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | BSkyB Green Button:Standard | And created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | BSkyB Green Button:Standard | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'TCNTU3' And created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Motivnummer |Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TTVBTVSAR3 | TTVBTVSBR3 | TTVBTVSSB3 | TTVBTVSP3 | TTVBTVSC1 |<ClockNumber3>| 111 |20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST3 | Facebook DE:Standard | And completed order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS13 | TTVBTVS13 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And wait till order with clockNumber '<ClockNumber3>' will be available in Traffic And open Traffic Order List page And refresh the page When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | Match | <Value> | And wait till order list will be loaded And wait for '4' seconds Then I 'should' see order '<AvailableOrder>' in order list at Traffic UI And I 'should not' see order '<NotAvailableOrderItem>' in order list at Traffic UI Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TTVBTVSCN8_1 | TTVBTVSCN8_2 | TTVBTVSCN8_3 | Agency | TCNTA2 | testAgency4 | Order | TTVBTVSCN8_3 | TTVBTVSCN8_1,TTVBTVSCN8_2 | | TTVBTVSCN10_1 | TTVBTVSCN10_2 | TTVBTVSCN10_3 | Market | United Kingdom | Testmarket4 | Order | TTVBTVSCN10_1,TTVBTVSCN10_2 | TTVBTVSCN10_3 | Scenario: Check that Traffic Manager can create tab with specific filter and use search on this new tab and Download CSV Meta: @traffic Given I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | Motivnummer |First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 1 |12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Talk Sport:Standard | And created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | Motivnummer |First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| 20 | 1 |12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | BSkyB Green Button:Standard | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And open Traffic Order List page When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | Match | <Value> | And wait till order item list will be loaded in Traffic And enter search criteria '<SearchCriteria>' in simple search form on Traffic Order Item List page Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Then I 'should' download csv report from tab with specific filter on Traffic Order Item List page and verify for data: | VerfyData | | <Value> | | <ClockNumber1> | And I 'shouldnot' download csv report from tab with specific filter on Traffic Order Item List page and verify for data: | VerfyData | | BSkyB Green Button | | <ClockNumber2> | Examples: | ClockNumber1 | ClockNumber2 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | SearchCriteria | | TTVBTVSCN11_1 | TTVBTVSCN11Z_2 | Destination name | Talk Sport | testDestination | Order Item (Send) | TTVBTVSCN11_1 | TTVBTVSCN11Z_2 | TTVBTVSCN11_1 | Scenario: Check that Broadcaster Traffic Manager can create tab with specific filter (Agency,Market,Advertiser) and Download CSv Meta: @traffic Given I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | Motivnummer | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Motorvision TV:Express | 1 | And created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination |Motivnummer | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Motorvision TV:Express | 1 | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'broadcasterTrafficManagerTwo' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And open Traffic Order List page And refresh the page When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | Match | <Value> | And wait till order item list will be loaded in Traffic And wait for '4' seconds Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Then I 'should' download csv report from tab with specific filter on Traffic Order Item List page and verify for data: | VerfyData | | <Value> | | <ClockNumber1> | And I 'shouldnot' download csv report from tab with specific filter on Traffic Order Item List page and verify for data: | VerfyData | |TCNTAR2 | |<ClockNumber2> | Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TTVBTVSCN12_1 | TTVBTVSCN12_2 | TTVBTVSCN12_3 | Advertiser | TCNTAR1 | testAdvertiser | Order Item (Send) | TTVBTVSCN12_1 | TTVBTVSCN12_2 | Scenario: Check that expand all feature works on new tab Meta: @traffic Given I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'United Kingdom' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | TCNT1_1 | 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Talk Sport:Standard| And completed order contains item with clock number 'TCNT1_1' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And login with details of 'trafficManager' And wait till order with clockNumber 'TCNT1_1' will be available in Traffic And select 'All' tab in Traffic UI And wait till order list will be loaded When I create tab with name 'TestExpand' and type 'Order' and Data Range 'Today' and without conditions in Traffic And wait for '5' seconds And enter search criteria 'TCNT1_1' in simple search form on Traffic Order List page And expand all orders on Traffic Order List page Then I 'should' see destinations 'Talk Sport' for order item in Traffic List with clockNumber 'TCNT1_1' Scenario: Create tabs based on House number at send level Meta:@traffic Given logged in with details of 'AgencyAdmin' And create 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date| Motivnummer | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | <ClockNumber1> | 20 | 12/14/2022 | 1 | Already Supplied |HD 1080i 25fps | TAFT1 | Travel Channel DE:Express | And create 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date| Motivnummer | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | <ClockNumber2> | 20 | 12/14/2022 | 1 | Already Supplied |HD 1080i 25fps | TAFT2 | Travel Channel DE:Express | And create 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date| Motivnummer | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | <ClockNumber3> | 20 | 12/14/2022 | 1 | Already Supplied |HD 1080i 25fps | TAFT3 | Travel Channel DE:Express | And create 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | First Air Date| Motivnummer | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | <ClockNumber4> | 20 | 12/14/2022 | 1 | Already Supplied |HD 1080i 25fps | TAFT4 | Travel Channel DE:Express | And complete order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And complete order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And complete order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS13 | TTVBTVS13 | And complete order contains item with clock number '<ClockNumber4>' with following fields: | Job Number | PO Number | | TTVBTVS14 | TTVBTVS14 | And logged in with details of 'broadcasterTrafficManagerNoApproval' And waited till order with clockNumber '<ClockNumber1>' will be available in Traffic And waited till order with clockNumber '<ClockNumber2>' will be available in Traffic And waited till order with clockNumber '<ClockNumber3>' will be available in Traffic And waited till order with clockNumber '<ClockNumber4>' will be available in Traffic And selected 'All' tab in Traffic UI And waited till order item list will be loaded in Traffic And I cleared search criteria in simple search form on Traffic Order List page And waited for '2' seconds And entered search criteria '<ClockNumber1>' in simple search form on Traffic Order List page And I fill in House Number for order items in Traffic UI: | HouseNumber | clockNumber | | NCS | <ClockNumber1> | And I cleared search criteria in simple search form on Traffic Order List page And waited for '2' seconds And entered search criteria '<ClockNumber2>' in simple search form on Traffic Order List page And I fill in House Number for order items in Traffic UI: | HouseNumber | clockNumber | | CS | <ClockNumber2> | And I cleared search criteria in simple search form on Traffic Order List page And waited for '2' seconds And entered search criteria '<ClockNumber3>' in simple search form on Traffic Order List page And I fill in House Number for order items in Traffic UI: | HouseNumber | clockNumber | | ECS | <ClockNumber3> | And waited for '2' seconds When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | <Cond Type 1> | <value_1> | | <Condition> | <Cond Type 2> | <value_2> | | <Condition> | <Cond Type 3> | <value_3> | And wait till order item list will be loaded in Traffic And clear search criteria in simple search form on Traffic Order List page And wait for '2' seconds And enter search criteria '<AvailableOrder>' in simple search form on Traffic Order List page Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic When clear search criteria in simple search form on Traffic Order List page Then I 'should not' see orderItems '<NotAvailItem>' in order item list in Traffic Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | ClockNumber4 | Condition | Cond Type 1 | value_1 | Cond Type 2 | value_2 | Cond Type 3 | value_3 |TabName | TabType | AvailableOrder | NotAvailItem | | TTBHNSL2_1 | TTBHNSL2_2 | TTBHNSL2_3 | TTBHNSL2_4 | House Number | Starts with | NCS | Does not start with | ECS | | |HN_NCS | Order Item (Send) | TTBHNSL2_1 | TTBHNSL2_2,TTBHNSL2_3,TTBHNSL2_4 | | TTBHNSL3_1 | TTBHNSL3_2 | TTBHNSL3_3 | TTBHNSL3_4 | House Number | Starts with | ECS | Does not start with | NCS | | |HN_ECS | Order Item (Send) | TTBHNSL3_3 | TTBHNSL3_1,TTBHNSL3_2,TTBHNSL3_4 | | TTBHNSL4_1 | TTBHNSL4_2 | TTBHNSL4_3 | TTBHNSL4_4 | House Number | Starts with | CS | Does not start with | ECS | Does not start with | NCS |HN_CS | Order Item (Send) | TTBHNSL4_2 | TTBHNSL4_1,TTBHNSL4_3,TTBHNSL4_4 | Scenario: Check that Traffic Manager can create tab based on specific to Market schema fields (Watermarking) Meta: @traffic Given I am logged in as 'GlobalAdmin' And I am on the global common ordering metadata page of market 'Spain' for agency 'DefaultAgency' And clicked 'String' button in 'custom metadata' section on opened metadata page And filled Description field with text 'String Common Ordering' on opened Settings and Customization tab And saved metadata field settings And logged in with details of 'AgencyAdmin' When created 'tv' order with market 'Spain' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clave | Clock Number | Watermarking Required | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 | Test |<ClockNumber1>| Yes | 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Antena 3:Standard | And created 'tv' order with market 'Spain' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clave | Clock Number | Watermarking Required | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 | Test |<ClockNumber2>| No | 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Antena 3:Standard | And created 'tv' order with market 'Spain' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clave | Clock Number | Watermarking Required | Duration | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 | Test |<ClockNumber3>| No | 20 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Antena 3:Standard | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And completed order contains item with clock number '<ClockNumber3>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And wait till order with clockNumber '<ClockNumber3>' will be available in Traffic And select 'All' tab in Traffic UI And wait till order list will be loaded When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Schema | Condition | Condition Type | Value | | Spain | <Condition> | Match | <Value> | And wait till order item list will be loaded in Traffic And wait for '4' seconds Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Examples: | ClockNumber1 | ClockNumber2 | ClockNumber3 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TSSWSCN1_1 | TSSWSCN1_2 | TSSWSCN1_3 | Watermarking Required | Yes | testWatermarking | Order Item (Clock) | TSSWSCN1_1 | TSSWSCN1_3,TSSWSCN1_2 | Scenario: Check that Traffic Manager can create tab with specific filter (Destination Type) Meta: @traffic Given I logged in with details of 'AgencyAdmin' When created 'tv' order with market 'Germany' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Duration | Motivnummer | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR1 | TCNTSB1 | TCNTSBR1 | TCNTPR1 | TTVBTVSC1 |<ClockNumber1>| 20 | 1 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST1 | Facebook DE:Express | And created 'tv' order with market 'Spain' and items with following fields: | Additional Information | Advertiser | Brand | Sub Brand | Product | Campaign | Clock Number | Watermarking Required | Clave | Duration | Motivnummer | First Air Date | Subtitles Required | Format | Title | Destination | | automated test info | TCNTAR2 | TCNTSB2 | TCNTSBR2 | TCNTPR2 | TTVBTVSC1 |<ClockNumber2>| No | 1 | 20 | 1 | 12/14/2022 | Already Supplied |HD 1080i 25fps | TTVBTVST2 | Ibecom TV:Express | And completed order contains item with clock number '<ClockNumber1>' with following fields: | Job Number | PO Number | | TTVBTVS11 | TTVBTVS11 | And completed order contains item with clock number '<ClockNumber2>' with following fields: | Job Number | PO Number | | TTVBTVS12 | TTVBTVS12 | And login with details of 'trafficManager' And wait till order with clockNumber '<ClockNumber1>' will be available in Traffic And wait till order with clockNumber '<ClockNumber2>' will be available in Traffic And open Traffic Order List page When I create tab with name '<TabName>' and type '<TabType>' and dataRange 'Today' and the following rules: | Condition | Condition Type | Value | | <Condition> | Match | <Value> | And wait till order item list will be loaded in Traffic And wait for '4' seconds Then I 'should' see orderItems '<AvailableOrder>' in order item list in Traffic And I 'should not' see orderItems '<NotAvailableOrderItem>' in order item list in Traffic Examples: | ClockNumber1 | ClockNumber2 | Condition | Value | TabName | TabType | AvailableOrder | NotAvailableOrderItem | | TCNSCN1_1 | TCNSCN1_2 | Destination type | Offline | DestinationStatus | Order Item (Send) | TCNSCN1_2 | TCNSCN1_1 |
<div class="fondo"> <div class="auth-container"> <div class="auth-tabs"> <button class="auth-tab" [class.active]="activeTab === 'login'" (click)="switchTab('login')" > Iniciar sesión </button> <button class="auth-tab" [class.active]="activeTab === 'register'" (click)="switchTab('register')" > Registrarse </button> </div> <div class="auth-form"> <form *ngIf="activeTab === 'login'"> <h2>Iniciar sesión</h2> <div class="form-group"> <label for="login-email">Email:</label> <input type="text" id="login-email" name="login-email" [(ngModel)]="loginEmail" required/> </div> <div class="form-group"> <label for="login-password">Contraseña:</label> <input type="password" id="login-password" name="login-password" [(ngModel)]="loginPassword" required/> </div> <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" (change)="onChange($event)" > <option selected>Selecciona el tipo de usuario</option> <option value="1">Adiminstrador</option> <option value="2">Medico</option> <option value="3">Paciente</option> </select> <ng-container *ngIf="selectedComponent === '1'"> <button (click)="onLoginSubmitAdmin()" id="iniciarSesionAdmin" type="submit" > Iniciar sesión como Administrador </button> </ng-container> <ng-container *ngIf="selectedComponent === '2'"> <button (click)="onLoginSubmitMedic()" id="iniciarSesionMedic" type="submit" > Iniciar sesión como Medico </button> </ng-container> <ng-container *ngIf="selectedComponent === '3'"> <button (click)="onLoginSubmitPatient()" id="iniciarSesionPaciente" type="submit" > Iniciar sesión como paciente </button> </ng-container> </form> <div class="colum"> <div class="registro"> <form *ngIf="activeTab === 'register'"> <h2>Registrarse</h2> <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" (change)="onChange($event)" > <option selected>Selecciona el tipo de usuario</option> <option value="1">Adiminstrador</option> <option value="2">Medico</option> <option value="3">Paciente</option> </select> <ng-container *ngIf="selectedComponent === '1'"> <app-administrador></app-administrador> </ng-container> <ng-container *ngIf="selectedComponent === '2'"> <app-medico-auth></app-medico-auth> </ng-container> <ng-container *ngIf="selectedComponent === '3'"> <app-paciente></app-paciente> </ng-container> </form> </div> </div> <router-outlet></router-outlet> </div> </div> </div>
import { expect, describe, it } from '@jest/globals'; import { createSourceFile, factory, ScriptTarget, } from 'typescript'; import { PrinterInline } from './PrinterInline'; describe('Printer/PrinterInline', () => { const createSourceFileMock = jest.spyOn(PrinterInline, 'createSourceFile').mockReturnValue( createSourceFile('', '', ScriptTarget.ESNext), ); const printASTMock = jest.spyOn(PrinterInline, 'printAST').mockReturnValue(''); beforeEach(() => { jest.clearAllMocks(); }); describe('print', () => { it('should create TypeScript source file without filename', async () => { const printer = new PrinterInline(); await printer.print(factory.createNodeArray()); expect(createSourceFileMock).toBeCalledTimes(1); expect(createSourceFileMock).toBeCalledWith(); }); it('should use printAST to print TypeScript nodes', async () => { const nodes = factory.createNodeArray(); const sourceFile = createSourceFile('', '', ScriptTarget.ESNext); createSourceFileMock.mockReturnValueOnce(sourceFile); const printer = new PrinterInline(); await printer.print(nodes); expect(printASTMock).toBeCalledTimes(1); expect(printASTMock).toBeCalledWith(nodes, sourceFile); }); it('should return printed TypeScript nodes', async () => { printASTMock.mockReturnValueOnce("type Printed = 'nodes';") const printer = new PrinterInline(); const nodesPrinted = await printer.print(factory.createNodeArray()); expect(nodesPrinted).toBe("type Printed = 'nodes';"); }); }); });
# Estos siguientes ejemplos se encuentran en el CAPÍTULO 3 # Conoceremos la utilidad de algunas funciones avanzadas disponibles en PySpark # Nos enfocaremos en las funciones de ventana y otro topicos que son utiles # en la creación y aplicación de programas de SPARK de grandes sets de datos. # Se introducen los temas de visualización y procesos de ML. # * Manipulaciones adicionales # * Visualizaciones de los datos # * Introducción a ML # Cargar librera import pyspark.sql.dataframe from pyspark.sql import SparkSession from pyspark.sql.functions import * # Crear sesión spark = SparkSession.builder.appName("Data_Wrangling").getOrCreate() # El tipo de archivo PySpark puede leer otros formatos como: json, parquet, orc # Cargar el archivo ReadDF = spark.read.load("C:/Users/joni_/Downloads/movie_data_tmbd.csv", format="csv", sep="|", inferSchema="true", header="true") # Registramos el DataFrame como una vista temporal SQL ReadDF.createOrReplaceTempView("View") # Definamos una lista de las columnas que deseamos imprimir select_columnas: list = ["id", "budget", "popularity", "release_date", "revenue", "title"] # Subconjunto que requieren columnas del DATAFRAME ReadDF = ReadDF.select(*select_columnas) # --> ReadDF.show(10,False) # Funciones de String df_with_newcols : pyspark.sql.dataframe.DataFrame = ReadDF.select('id','budget','popularity'). \ withColumn('budget_cat', when(ReadDF['budget']<10000000,'Small'). when(ReadDF['budget']<100000000,'Medium'). otherwise('Big')).withColumn('ratings', when(ReadDF['popularity']<3,'Low'). when(ReadDF['popularity']<5,'Mid').otherwise('High')) # Ver el DataFrame df_with_newcols # --> df_with_newcols.show(15, False) # +-----+-------+------------------+----------+-------+ # |id |budget |popularity |budget_cat|ratings| # +-----+-------+------------------+----------+-------+ # |43000|0 |3.892 |Small |Mid | # |43001|0 |5.482 |Small |High | # |43002|0 |8.262 |Small |High | # |43003|0 |7.83 |Small |High | # |43004|500000 |5.694 |Small |High | # |43006|0 |2.873 |Small |Low | # |43007|0 |3.433 |Small |Mid | # |43008|0 |7.869 |Small |High | # |43010|0 |3.775 |Small |Mid | # |43011|0 |7.185 |Small |High | # |43012|7000000|8.193 |Small |High | # |43013|0 |4.408 |Small |Mid | # |43014|0 |5.562 |Small |High | # |43015|0 |3.083 |Small |Mid | # |43016|0 |3.5060000000000002|Small |Mid | # +-----+-------+------------------+----------+-------+ # only showing top 15 rows # Si queremos concatenar los valores de la columna budget_cat y ratings en una sola # columna, lo podemos hacer con la función 'concat' # Como primer paso, cambiemos el caso de la nueva columna a lowercase y trim removiendo # espacios en blanco usando las funciones trim y lower. # Concatenado dos variables df_with_newcols = df_with_newcols.withColumn('BudgetRating_Category',concat(df_with_newcols.budget_cat,df_with_newcols.ratings)) # Cambiando la variable df_with_newcols = df_with_newcols.withColumn('BudgetRating_Category',trim(lower(df_with_newcols.BudgetRating_Category))) # --> df_with_newcols.show(10,False) # +-----+------+----------+----------+-------+---------------------+ # |id |budget|popularity|budget_cat|ratings|BudgetRating_Category| # +-----+------+----------+----------+-------+---------------------+ # |43000|0 |3.892 |Small |Mid |smallmid | # |43001|0 |5.482 |Small |High |smallhigh | # |43002|0 |8.262 |Small |High |smallhigh | # |43003|0 |7.83 |Small |High |smallhigh | # |43004|500000|5.694 |Small |High |smallhigh | # |43006|0 |2.873 |Small |Low |smalllow | # |43007|0 |3.433 |Small |Mid |smallmid | # |43008|0 |7.869 |Small |High |smallhigh | # |43010|0 |3.775 |Small |Mid |smallmid | # |43011|0 |7.185 |Small |High |smallhigh | # +-----+------+----------+----------+-------+---------------------+ # only showing top 10 rows # Registrar un tabla temporal df_with_newcols.registerTempTable('OneUse') consulta = spark.sql(""" SELECT ratings, COUNT(ratings) FROM OneUse GROUP BY ratings""") # --> df_with_newcols.show() # +-------+--------------+ # |ratings|count(ratings)| # +-------+--------------+ # | High| 28451| # | Low| 71878| # | Mid| 19798| # +-------+--------------+ # Funciones de Ventana / Window Functions # Importar las librerias para las funciones de ventana from pyspark.sql.window import * # Step 1: Filtra los valores faltantes df_with_newcols = df_with_newcols.filter((df_with_newcols['popularity'].isNotNull()) & (~isnan(df_with_newcols['popularity']))) # df_with_newcols.show(10,False) # +-----+------+----------+----------+-------+---------------------+ # |id |budget|popularity|budget_cat|ratings|BudgetRating_Category| # +-----+------+----------+----------+-------+---------------------+ # |43000|0 |3.892 |Small |Mid |smallmid | # |43001|0 |5.482 |Small |High |smallhigh | # |43002|0 |8.262 |Small |High |smallhigh | # |43003|0 |7.83 |Small |High |smallhigh | # |43004|500000|5.694 |Small |High |smallhigh | # |43006|0 |2.873 |Small |Low |smalllow | # |43007|0 |3.433 |Small |Mid |smallmid | # |43008|0 |7.869 |Small |High |smallhigh | # |43010|0 |3.775 |Small |Mid |smallmid | # |43011|0 |7.185 |Small |High |smallhigh | # +-----+------+----------+----------+-------+---------------------+ # only showing top 10 rows # Como poner la linea anterior en comando SQL la cual discrimina los valores nulos consulta_filter = spark.sql(""" SELECT * FROM OneUse WHERE popularity IS NOT NULL""") # consulta_filter.show() # Primero quise saber cuantos registros Nulos existen en el DF Usando una consulta SQL # Esto es con la vista de la tabla anterior lo que signfica que aún no se discriminan los NULOS consulta_num_nulos = spark.sql(""" SELECT COUNT(*) AS Num_Nulos FROM OneUse WHERE popularity IS NULL""") # --> consulta_num_nulos.show() # +---------+ # |Num_Nulos| # +---------+ # | 1059| # +---------+ # Tuve que hacer otra vista temporal de la tabla porque se aplicaron los filtros y en esta nueva vista vemos # que en el resultado salen 0 nulos que ya fueron discriminados df_with_newcols.registerTempTable('TwoUse') after_filter_nulos = spark.sql(""" SELECT COUNT(*) AS Num_Nulos FROM TwoUse WHERE popularity IS NULL""") # --> after_filter_nulos.show() # +---------+ # |Num_Nulos| # +---------+ # | 0| # +---------+ # Step 2: Aplicando funciones de ventana para calcular los deciles df_with_newcols = df_with_newcols.select("id","budget","popularity",ntile(10).over(Window.partitionBy().orderBy(df_with_newcols['popularity'].desc())).alias("decile_rank")) # Desplegando los valores df_with_newcols.groupby("decile_rank").agg(min('popularity').alias('min_popularity'),max('popularity').alias('max_popularity'),count('popularity')).show() # +-----------+------------------+------------------+-----------------+ # |decile_rank| min_popularity| max_popularity|count(popularity)| # +-----------+------------------+------------------+-----------------+ # | 1|5.8629999999999995| Η Άγνωστος| 11907| # | 2| 4.026|5.8629999999999995| 11907| # | 3| 3.092| 4.026| 11907| # | 4| 2.605| 3.092| 11907| # | 5| 16.122| 2.605| 11907| # | 6| 1.758| 16.122| 11907| # | 7| 1.335| 1.758| 11907| # | 8| 0.895| 1.335| 11907| # | 9|0.6000000000000001| 0.895| 11906| # | 10| Episode 24 |0.6000000000000001| 11906| # +-----------+------------------+------------------+-----------------+ # Figure 3-3. Output of popularity deciles
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using FluentValidation.Results; using Global.Configs.Authentication; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Global.Models; using Global.Models.Auth; using Global.Models.EndPointResponse; using Global.Models.StateChangedResponse; using Microsoft.AspNetCore.Authorization; using ValidationResult = System.ComponentModel.DataAnnotations.ValidationResult; using System.Threading.Tasks; using News.API.Models.Domain; using System.Net.Http; using Newtonsoft.Json; using System.Text; using News.API.Common; using System.Net; using News.API.Models.Domain.Picture; using News.API.Models.Domain.FileAttachment; using Global.Configs.ResourceConfig; namespace News.API.Controllers { [ApiController] [Authorize(AuthenticationSchemes = Global.Configs.Authentication.AuthenticationSchemes.CmsApiIdentityKey)] public abstract class CustomBaseController : ControllerBase { public UserIdentity UserIdentity => new UserIdentity(HttpContext); public new OkObjectResult Ok() { return new OkObjectResult(EndPointResponse.Success()); } public override OkObjectResult Ok(object result) { var resultType = result.GetType(); if (resultType.IsGenericType) { if (resultType.GetGenericTypeDefinition() == typeof(IActionResponse<>) || resultType.GetGenericTypeDefinition() == typeof(ActionResponse<>)) { var message = resultType.GetProperty("Message")?.GetValue(result, null)?.ToString(); var resultValue = resultType.GetProperty("Result")?.GetValue(result, null); return new OkObjectResult(EndPointHasResultResponse.Success(resultValue, message)); } } if (result is IActionResponse actionResponse) { return new OkObjectResult(EndPointResponse.Success(actionResponse.Message)); } return new OkObjectResult(EndPointHasResultResponse.Success(result)); } public new BadRequestObjectResult BadRequest() { return new BadRequestObjectResult(EndPointResponse.Failed("Yêu cầu không hợp lệ")); } public override BadRequestObjectResult BadRequest(ModelStateDictionary modelState) { return BadRequest((object) modelState); } public override BadRequestObjectResult BadRequest(object error) { switch (error) { case IActionResponse response: response.ClearResult(); return base.BadRequest(response); case ModelStateDictionary modelStateDic: { var commonErrors = new List<ErrorGeneric>(); foreach (var modelState in modelStateDic) { var validateError = new ValidationResult(string.Join(',', modelState.Value.Errors.Select(r => r.ErrorMessage)), new[] { modelState.Key }); commonErrors.Add(new ErrorGeneric(validateError)); } return base.BadRequest(new EndPointResponse() { IsSuccess = false, Message = $"Thất bại, phát hiện {commonErrors.Count} lỗi", Errors = commonErrors }); } case ErrorGeneric errorGeneric: return base.BadRequest(new EndPointResponse() { IsSuccess = false, Message = "Thất bại, phát hiện có lỗi xảy ra", Errors = new List<ErrorGeneric>() { errorGeneric } }); case string errorMessage: return base.BadRequest(new EndPointResponse() { IsSuccess = false, Message = errorMessage }); case IList<ValidationFailure> validationResults: return base.BadRequest(new EndPointResponse() { IsSuccess = false, Message = $"Thất bại, phát hiện {validationResults.Count} lỗi.", Errors = validationResults.Select(e => new ErrorGeneric(e.ErrorMessage, e.PropertyName)) .ToList() }); default: return base.BadRequest(new EndPointResponse() { IsSuccess = false, Message = "Yêu cầu không hợp lệ" }); } } protected async Task<List<PictureViewModel>> StoreAndSavePicture(List<string> tempFilePaths) { var httpClientHandler = new HttpClientHandler(); using (HttpClient client = new HttpClient(httpClientHandler, true)) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("ContentType", "application/json; charset=utf-8"); var content = new StringContent( JsonConvert.SerializeObject(tempFilePaths), Encoding.UTF8, "application/json"); var uploadResponse = await client.PutAsync(ResourceGlobalConfigs.MediaSourceURL + "api/Upload/images", content); if (uploadResponse.IsSuccessStatusCode && uploadResponse.StatusCode == HttpStatusCode.OK) { var responseContent = await uploadResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<List<PictureViewModel>>(responseContent); } return null; } } protected async Task<PictureViewModel> StoreAndSavePicture(string tempFilePaths) { var httpClientHandler = new HttpClientHandler(); using (HttpClient client = new HttpClient(httpClientHandler, true)) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("ContentType", "application/json; charset=utf-8"); var content = new StringContent( JsonConvert.SerializeObject(new List<string>() { tempFilePaths }), Encoding.UTF8, "application/json"); var uploadResponse = await client.PutAsync(ResourceGlobalConfigs.MediaSourceURL + "api/Upload/images", content); if (uploadResponse.IsSuccessStatusCode && uploadResponse.StatusCode == HttpStatusCode.OK) { var responseContent = await uploadResponse.Content.ReadAsStringAsync(); var responseValue = JsonConvert.DeserializeObject<List<PictureViewModel>>(responseContent); return responseValue.Any() ? responseValue.First() : null; } return null; } } protected async Task<List<PictureViewModel>> StoreAndSavePictures(List<PictureArticleContentItem> listPictureArticleContent) { var httpClientHandler = new HttpClientHandler(); using (HttpClient client = new HttpClient(httpClientHandler, true)) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("ContentType", "application/json; charset=utf-8"); var content = new StringContent( JsonConvert.SerializeObject(listPictureArticleContent), Encoding.UTF8, "application/json"); var uploadResponse = await client.PutAsync(ResourceGlobalConfigs.MediaSourceURL + "api/Upload/imagesArticleContent", content); if (uploadResponse.IsSuccessStatusCode && uploadResponse.StatusCode == HttpStatusCode.OK) { var responseContent = await uploadResponse.Content.ReadAsStringAsync(); var responseValue = JsonConvert.DeserializeObject<List<PictureViewModel>>(responseContent); return responseValue; } return new List<PictureViewModel>(); } } protected async Task<List<FileAttachmentItem>> StoreAndSaveFiles(List<FileArticleContentItem> listFileArticleContentItem) { var httpClientHandler = new HttpClientHandler(); using (HttpClient client = new HttpClient(httpClientHandler, true)) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("ContentType", "application/json; charset=utf-8"); var content = new StringContent( JsonConvert.SerializeObject(listFileArticleContentItem), Encoding.UTF8, "application/json"); var uploadResponse = await client.PutAsync(ResourceGlobalConfigs.MediaSourceURL + "api/UploadFiles/filesArticleContent", content); if (uploadResponse.IsSuccessStatusCode && uploadResponse.StatusCode == HttpStatusCode.OK) { var responseContent = await uploadResponse.Content.ReadAsStringAsync(); var responseValue = JsonConvert.DeserializeObject<List<FileAttachmentItem>>(responseContent); return responseValue; } return new List<FileAttachmentItem>(); } } } }
# 問題2.2(教科書の問題 2.1-4 p.25) # サイズnの配列A[1:n]にデータが格納されている。値aに等しいデータA[i]があれば # そのインデックスいを出力し、なければ0を出力する。順次探索法のプログラムを作れ。 def order_find(arr: list, a) -> int: """ arr: 配列A[1:n] a: 値a len(arr): サイズn """ if len(arr) == 0: return -1 for i in range(len(arr)): if a == arr[i]: return i else: return 0 def _test_result(): data_arr = [1, 4, 7, 2, 3, 5, 8, 9, 10, 11, 6, 15, 12] result = order_find(data_arr, 17) # 値a = 7のとき print(result) # インデックス2を出力した result = order_find(data_arr, 12) # 値a = 9のとき print(result) # インデックス7を出力した result = order_find(data_arr, 117) # 値a = 17のとき print(result) # インデックス0を出力した _test_result()
/** * @Author: liuxin * @Date: 2022-07-31 12:03:25 * @Last Modified by: liuxin * @Last Modified time: 2022-08-13 16:15:20 */ #include <stdint.h> #include <fstream> #include <mutex> #include "node.h" #ifndef __SKIPLIST_H__ #define __SKIPLIST_H__ #define DUMPFIEL "store/dumpFile" std::mutex mtx; template<typename K, typename V> class Skiplist { private: /* data */ int max_level; int current_level; Node<K, V> *header; int element_count; // file operator std::ofstream file_writer; std::ifstream file_reader; /* method */ void getKeyAndValueFromStr(const std::string& str, std::string* key, std::string* value); bool isValidStr(const std::string& str); public: Skiplist(int); ~Skiplist(); Node<K, V>* create_node(K, V, int); int insert_element(K, V); bool search_element(K); void delete_element(K); void display_list(); int getRandomLevel(); void dumpToFile(); void loadFromFile(); int getSkipListSize(); }; template<typename K, typename V> Skiplist<K, V>::Skiplist(int max_level) { this->max_level = max_level; this->current_level = 0; this->element_count = 0; K k; V v; this->header = new Node<K, V>(k, v, max_level); } template<typename K, typename V> Skiplist<K, V>::~Skiplist() { if (file_writer.is_open()) { file_writer.close(); } if (file_reader.is_open()) { file_reader.close(); } delete header; } // create new node template<typename K, typename V> Node<K, V>* Skiplist<K, V>::create_node(const K k, const V v, int level) { Node<K, V> *n = new Node<K, V>(k, v, level); return n; } template<typename K, typename V> int Skiplist<K, V>::insert_element(const K key, const V value) { mtx.lock(); Node<K, V> *current = this->header; // create update array and initialize it // update is array which put node that the node->forward[i] should be operated later Node<K, V> *update[max_level+1]; memset(update, 0, sizeof(Node<K, V>*)*(max_level+1)); // start form highest level of skip list for(int i = current_level; i >= 0; i--) { while(current->forward[i] != NULL && current->forward[i]->get_key() < key) { current = current->forward[i]; } update[i] = current; } // reached level 0 and forward pointer to right node, which is desired to insert key. current = current->forward[0]; // if current node have key equal to searched key, we get it if (current != NULL && current->get_key() == key) { std::cout << "key: " << key << ", exists" << std::endl; mtx.unlock(); return 1; } // two cases: // 1) if current is NULL that means we have reached to end of the level // 2) if current's key is not equal to key that means we have to insert node between update[0] and current node if (current == NULL || current->get_key() != key ) { // Generate a random level for node int random_level = getRandomLevel(); // If random level is greater thar skip list's current level, initialize update value with pointer to header if (random_level > current_level) { for (int i = current_level+1; i < random_level+1; i++) { update[i] = header; } //update current level current_level = random_level; } // create new node with random level generated Node<K, V>* inserted_node = create_node(key, value, random_level); // insert node for (int i = 0; i <= random_level; i++) { inserted_node->forward[i] = update[i]->forward[i]; update[i]->forward[i] = inserted_node; } std::cout << "Successfully inserted element with key:" << key << ", value:" << value << std::endl; element_count++; } mtx.unlock(); return 0; } template<typename K, typename V> void Skiplist<K, V>::delete_element(K key) { mtx.lock(); Node<K, V> *current = this->header; Node<K, V> *update[max_level+1]; memset(update, 0, sizeof(Node<K, V>*)*(max_level+1)); // start from highest level of skip list for (int i = current_level; i >= 0; i--) { while (current->forward[i] !=NULL && current->forward[i]->get_key() < key) { current = current->forward[i]; } update[i] = current; } current = current->forward[0]; if (current != NULL && current->get_key() == key) { // start for lowest level and delete the current node of each level for (int i = 0; i <= current_level; i++) { // if at level i, next node is not target node, break the loop. if (update[i]->forward[i] != current) break; update[i]->forward[i] = current->forward[i]; } // Remove levels which have no elements while (current_level > 0 && header->forward[current_level] == nullptr) { current_level --; } std::cout << "Successfully deleted element with key:"<< key << std::endl; current_level--; mtx.unlock(); return; } std::cout << "Failed deleted, No element with key: "<< key << std::endl; mtx.unlock(); return; } template<typename K, typename V> bool Skiplist<K, V>::search_element(K key) { Node<K, V> *current = this->header; // start from highest level of skip list for (int i = current_level; i >= 0; i--) { while (current->forward[i] !=NULL && current->forward[i]->get_key() < key) { current = current->forward[i]; } } current = current->forward[0]; if (current != NULL && current->get_key() == key) { std::cout << "Successfully found element with key:"<< key << ", value:"<< current->get_value() << std::endl; return true; } std::cout << "Failed searched, No element with key: "<< key << std::endl; return false; } template<typename K, typename V> void Skiplist<K, V>::display_list() { std::cout << "---Start display the SkipList---" << std::endl; for (int i = current_level; i > 0; i--) { Node<K, V> * node = this->header->forward[i]; std::cout << "Level " << i << ": "; while (node != nullptr) { std::cout << node->get_key() << ":" << node->get_value() << "; "; node = node->forward[i]; } std::cout << std::endl; } std::cout << "---Finish display the SkipList---\n" << std::endl; } template<typename K, typename V> void Skiplist<K, V>::dumpToFile() { std::cout << "---Start dump data in memory to file---" << std::endl; file_writer.open(DUMPFIEL); Node<K, V> *node = this->header->forward[0]; while (node != nullptr) { file_writer << node->get_key() << ":" << node->get_value() << "\n"; std::cout << node->get_key() << ":" << node->get_value() << ";\n"; node = node->forward[0]; } file_writer.flush(); file_writer.close(); std::cout << "---Finish dump data in memory to file---\n" << std::endl; return; } template<typename K, typename V> void Skiplist<K, V>::loadFromFile() { std::cout << "---Start load data from file---" << std::endl; file_reader.open(DUMPFIEL); std::string one_line; std::string* key = new std::string(); std::string* value = new std::string(); while (getline(file_reader, one_line)) { getKeyAndValueFromStr(one_line, key, value); if(key->empty() || value->empty()){ continue; } int key_int = std::stoi(*key); insert_element(key_int, *value); // insert_element(*key, *value); // std::cout << "key:" << key << "value:" << *value << std::endl; } file_reader.close(); std::cout << "---Finish load data from file---\n" << std::endl; } template<typename K, typename V> void Skiplist<K, V>::getKeyAndValueFromStr(const std::string& str, std::string* key, std::string* value) { if(!isValidStr(str)) { return; } *key = str.substr(0, str.find(":")); *value = str.substr(str.find(":")+1, str.length()); } template<typename K, typename V> bool Skiplist<K, V>::isValidStr(const std::string& str) { if(str.empty()) { return false; } if(str.find(":") == std::string::npos) { return false; } return true; } template<typename K, typename V> int Skiplist<K, V>::getRandomLevel() { int k = 1; while (rand() % 2) { k++; } k = (k < max_level) ? k : max_level; return k; } #endif /* __SKIPLIST_H__ */
package com.company.youse.services.query.yousepay; import com.company.youse.platform.decorator.query.QueryBaseService; import com.company.youse.platform.result.QueryResult; import com.company.youse.pojo.B2CRequestResult; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; @Slf4j @Service public class B2CResultExtractionService extends QueryBaseService<B2CResultExtractionQuery, B2CRequestResult> { @Override @SuppressWarnings("unchecked") public QueryResult<B2CRequestResult> execute(B2CResultExtractionQuery query) { B2CRequestResult b2CTransaction = new B2CRequestResult(); Map<String, Object> b2cResult = query.getB2CResultCommand().getResult(); String resultCode = String.valueOf(b2cResult.get("ResultCode")); String resultType = String.valueOf(b2cResult.get("ResultType")); String resultDesc = String.valueOf(b2cResult.get("ResultDesc")); String originatorConversationID = String.valueOf(b2cResult.get("OriginatorConversationID")); String conversationID = String.valueOf(b2cResult.get("ConversationID")); String transactionID = String.valueOf(b2cResult.get("TransactionID")); b2CTransaction.setOriginatorConversationID(originatorConversationID); b2CTransaction.setConversationID(conversationID); b2CTransaction.setTransactionID(transactionID); b2CTransaction.setResultCode(resultCode); b2CTransaction.setResultType(resultType); b2CTransaction.setResultDescription(resultDesc); if(Optional.ofNullable(b2cResult.get("ResultParameters")).isPresent()){ Map<String, Object> resultParams = (Map<String, Object>) b2cResult.get("ResultParameters"); List<Map<String, Object>> resultParamValue = (List<Map<String, Object>>) resultParams.get("ResultParameter"); for (Map<String, Object> resultParamVal : resultParamValue) { String key = String.valueOf(resultParamVal.get("Key")); String value = String.valueOf(resultParamVal.get("Value")); switch (key) { case "TransactionAmount": case "Amount": b2CTransaction.setTransactionAmount(new BigDecimal(value)); break; case "TransactionReceipt": case "ReceiptNo": b2CTransaction.setTransactionReceipt(value); break; case "B2CRecipientIsRegisteredCustomer": b2CTransaction.setB2CRecipientIsRegisteredCustomer(value); break; case "B2CChargesPaidAccountAvailableFunds": b2CTransaction.setB2CChargesPaidAccountAvailableFunds(new BigDecimal(value)); break; case "ReceiverPartyPublicName": b2CTransaction.setReceiverPartyPublicName(value); break; case "TransactionCompletedDateTime": case "FinalisedTime": SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); try { Date date; try{ date = dateFormatter.parse(value); }catch (ParseException e){ date = new Date(Long.parseLong(value)); } b2CTransaction.setTransactionCompletedDateTime(dateFormatter.parse( dateFormatter.format(date))); } catch (Exception e) { log.info("Failed to parse date string, setting current date for transaction " + b2CTransaction); try { b2CTransaction.setTransactionCompletedDateTime(dateFormatter.parse(dateFormatter .format(new Date()))); } catch (ParseException parseException) { parseException.printStackTrace(); } } break; case "B2CUtilityAccountAvailableFunds": b2CTransaction.setB2CUtilityAccountAvailableFunds(new BigDecimal(value)); break; case "B2CWorkingAccountAvailableFunds": b2CTransaction.setB2CWorkingAccountAvailableFunds(new BigDecimal(value)); break; case "TransactionStatus": b2CTransaction.setTransactionStatus(value); break; case "ReasonType": b2CTransaction.setReasonType(value); break; case "DebitPartyName": b2CTransaction.setDebitPartyName(value); break; case "CreditPartyName": b2CTransaction.setCreditPartyName(value); break; } } } return new QueryResult.Builder<B2CRequestResult>().data(b2CTransaction).ok().build(); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/views/layouts/user/taglib.jsp" %> <head> <title>Sản Phẩm</title> <style> .pagination { display: flex; justify-content: center; } .pagination a { color: black; float: left; padding: 8px 16px; text-decoration: none; } .pagination a.active { background-color: #4CAF50; color: white; border-radius: 5px; } .pagination a:hover:not(.active) { background-color: #ddd; border-radius: 5px; } </style> </head> <body> <div class="well well-small"> <div class="row"> <span style="margin-left: 25px;">Danh sách sản phẩm</span> <select class="pull-right"> <option>A - Z</option> <option>Cao - Thấp</option> </select> </div> <c:if test="${ProductsPaganite.size() > 0 }"> <div class="row-fluid"> <ul class="thumbnails"> <c:forEach var="item" items="${ProductsPaganite }" varStatus="loop"> <li class="span4"> <div class="thumbnail"> <a href="product_details.html" class="overlay"></a> <a class="zoomTool" href="<c:url value="/chi-tiet-san-pham/${ item.id }"/>" title="add to cart"><span class="icon-search"></span> Xem</a> <a href="<c:url value="/chi-tiet-san-pham/${ item.id }"/>"><img src="<c:url value="/assets/user/img/nt/${ item.img }"/>" alt=""></a> <div class="caption cntr"> <p>${item.name }</p> <p> <strong> <fmt:formatNumber type="number" groupingUsed="true" value="${item.price}" /> đ</strong> </p> <h4> <a class="shopBtn" href="<c:url value="/chi-tiet-san-pham/${ item.id }"/>" title="add to cart">Chi Tiết</a> </h4> <br class="clr"> </div> </div> </li> <c:if test="${(loop.index + 1) % 3 == 0 || (loop.index + 1) == ProductsPaganite.size()}"> </ul> <c:if test="${(loop.index + 1) < ProductsPaganite.size() }"> <div class="row-fluid"> <ul class="thumbnails"> </c:if> </c:if> </c:forEach> </c:if> </div> </div> <div class="pagination"> <c:forEach var="item" begin="1" end="${paginatesInfo.totalPage }" varStatus="loop"> <c:if test="${(loop.index) == paginatesInfo.currentPage }"> <a href="<c:url value="/san-pham/${ idCategory }/${ loop.index }"/>" class="active">${loop.index }</a> </c:if> <c:if test="${(loop.index) != paginatesInfo.currentPage }"> <a href="<c:url value="/san-pham/${ idCategory }/${ loop.index }"/>">${loop.index }</a> </c:if> </c:forEach> </div> </body>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateHallsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('halls', function (Blueprint $table) { $table->id(); $table->string('hall_number'); $table->text('description'); $table->string('hall_scheme')->nullable(); $table->string('top_banner')->nullable(); $table->foreignId('seo_block_id')->constrained('seo_block')->onDelete('cascade')->onUpdate('cascade'); $table->foreignId('cinema_id')->constrained('cinemas')->onDelete('cascade')->onUpdate('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('halls'); } }
package com.example.moviebooking.controller; import java.util.List; import ch.qos.logback.core.CoreConstants; import com.example.moviebooking.util.BMSConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.moviebooking.data.dto.BookSeatsDto; import com.example.moviebooking.data.dto.MovieDetailsDto; import com.example.moviebooking.domain.MovieScreening; import com.example.moviebooking.service.MovieScreeningService; @RequestMapping("/movie/screening") @RestController public class MovieScreeningController { @Autowired private MovieScreeningService movieScreeningService; Logger log = LoggerFactory.getLogger(MovieScreeningController.class); @CrossOrigin @GetMapping("/details") public List<MovieScreening> getUiDetails(@RequestBody MovieDetailsDto movieDetailsDto) { log.info("Screening details endPoint called"); if (movieDetailsDto != null) { return movieScreeningService.getAllMovieDetails(movieDetailsDto.getMovieName(), movieDetailsDto.getMovieCity(), movieDetailsDto.getScreeningDate()); } return null; } @CrossOrigin @PostMapping("/bookseats") public String bookSeats(@RequestBody BookSeatsDto bookSeatsDto) { int bookedSeats = this.movieScreeningService.getBookedSeats(bookSeatsDto); log.info("Booked Seats " + bookedSeats); int totalSeats = this.movieScreeningService.getTotalSeats(bookSeatsDto); log.info("Total Seats " + totalSeats); if ((bookedSeats + bookSeatsDto.getNumSeats()) > totalSeats) return "Sorry " +bookSeatsDto.getNumSeats()+ " Seats Not Avaliable"; try { //generate the order id long userId = bookSeatsDto.getUserDetailsDTO().getUserId(); long orderId = this.movieScreeningService.generateOrder(userId,bookSeatsDto.getNumSeats()); System.out.println("Order ID ********** " + orderId); //Initiate Payment String paymentResult = this.movieScreeningService.submitPaymentDetail(userId,bookSeatsDto.getUserDetailsDTO().getPaymentDto().getTransactionAmount(),orderId); if(BMSConstants.PAYMENT_SUCCESS.equalsIgnoreCase(paymentResult)) { //append the number of seat's with booked seats to update new booked seats this.movieScreeningService.bookSeats(bookSeatsDto, bookedSeats + bookSeatsDto.getNumSeats(), orderId); //update order status as completed and payment as Success this.movieScreeningService.updateOrderStatus(orderId,BMSConstants.ORDER_COMPLETED,BMSConstants.PAYMENT_SUCCESS); }else{ log.error("Error during Payment for Order " + orderId); //update order status as Failed and payment as Failed this.movieScreeningService.updateOrderStatus(orderId,BMSConstants.ORDER_FAILED,BMSConstants.PAYMENT_FAILED); return "Sorry Payment Service is Down, Try after Sometime"; } } catch (Exception e) { log.error("Error Saving the Transaction, Please try later! "); return "Sorry Unable to Book Seats Currently"; } return bookSeatsDto.getNumSeats() + " Tickets Succesfully booked for Movie " + bookSeatsDto.getMovieName() + "!"; } }
import { Button, Grid, IconButton, SwipeableDrawer } from '@mui/material' import { Box } from '@mui/system' import { useState } from 'react' import { useLocation, useNavigate } from 'react-router' import logo from '../../assets/logo.svg' import menuIcon from '../../assets/menu.svg' import useStyles from './useStyles' const NavBar = () => { const classes = useStyles() const navigate = useNavigate() const { pathname } = useLocation() const [displayDrawer, setDisplayDrawer] = useState(false) const [active, setActive] = useState('/') const toggleDrawer = (open) => (event) => { if ( event && event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift') ) { return } setDisplayDrawer(open) } return ( <Grid id="home" container className={classes.navBar}> <Grid item xs={10} sm={2} md={2.5} className={classes.logoWrapper} data-aos="fade-down" > <img src={logo} alt="fasta" className={classes.logo} /> </Grid> <Grid item md={5} lg={4} className={classes.navBtnWrapper} data-aos="fade-down" > <Button className={active === '/' ? classes.activeNavBtn : classes.navBtn} onClick={() => { setActive('/') navigate('/') }} disableRipple > Home </Button> <Button className={ active === '/business' ? classes.activeNavBtn : classes.navBtn } onClick={() => { setActive('/business') navigate('/business') }} disableRipple > Fastapay for Bussiness </Button> {pathname === '/' && ( <Button className={ active === '/services' ? classes.activeNavBtn : classes.navBtn } onClick={() => setActive('/services')} href="#services" disableRipple > Services </Button> )} </Grid> <Grid item md={3} lg={2} className={classes.contactBtnWrapper} data-aos="fade-left" > {pathname === '/' && ( <Button onClick={() => setActive('/contact')} variant="contained" href="#footer" size="medium" > Contact us </Button> )} </Grid> <Grid item xs={2} className={classes.menuWrapper}> <IconButton onClick={toggleDrawer(true)}> <img src={menuIcon} alt="menu" /> </IconButton> <SwipeableDrawer anchor="right" open={displayDrawer} onClose={toggleDrawer(false)} onOpen={toggleDrawer(true)} > <Box className={classes.menuItems} onClick={toggleDrawer(false)} onKeyDown={toggleDrawer(false)} > <Button onClick={() => { setActive('/') navigate('/') }} className={active === '/' ? classes.activeNavBtn : classes.navBtn} disableRipple > Home </Button> <Button onClick={() => { setActive('/business') navigate('/business') }} className={ active === '/business' ? classes.activeNavBtn : classes.navBtn } disableRipple > Fastapay for Bussiness </Button> {pathname === '/' && ( <> <Button className={classes.navBtn} href="#services" disableRipple > Services </Button> <Button variant="contained" href="#footer"> Contact us </Button> </> )} </Box> </SwipeableDrawer> </Grid> </Grid> ) } export default NavBar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Power of Two</title> </head> <body> <script language="javascript"> /* Power of Two Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2^x. Input: n = 1 Output: true Explanation: 2^0 = 1 Input: n = 16 Output: true Explanation: 2^4 = 16 Input: n = 3 Output: false */ var isPowerOfTwo = function(n) { if(n === 1) { return true; } if((n % 2) === 1) { return false; } for(let i = 0; i <= 32; i++) { if(Math.pow(2, i) === n) { return true; } } return false; }; // Output: true console.log(isPowerOfTwo(1)); // Output: true console.log(isPowerOfTwo(16)); // Output: false console.log(isPowerOfTwo(3)); // Output: false console.log(isPowerOfTwo(2147483646)); </script> </body> </html>
#include <Arduino.h> #include <StateManager.h> StateManager::StateManager() : state_(nullptr), currentStateIndex(0), blinking_period(0), motor(2, 1000), led(5) { // MotorController ; led.init(); motor.init(21); // motor.set(0.0); this->transitionToState(new InitializationState); this->loopAction(); this->transitionToState(new PreOperationalState); currentStateIndex = 1; Serial.print("\nEnter a value for Kp: "); char chars[20]; char character; int i = 0; while(1){ if(Serial.available()) { character = Serial.read(); if(character == 13){ break; } chars[i] = character; i++; } if(i==20){ break; } } float kp = strtod(chars, nullptr); Serial.println(kp); Serial.print("Enter a value for Ti: "); char chars2[20]; char character2; int j = 0; while(1){ if(Serial.available()) { character2 = Serial.read(); if(character2 == 13){ break; } chars2[j] = character2; j++; } if(j==20){ break; } } float ti = strtod(chars2, nullptr); Serial.println(ti); Serial.print("Use integrated speed controller ? [y/n] : "); char character3[2]; int k = 0; while(1){ if(Serial.available()) { character3[k] = Serial.read(); k++; if(k == 3){ break; } } } Serial.println(character3[1]); if(character3[1] == 'y' || character3[1] == 'Y'){ motor.useIntegrated = true; } else { motor.useIntegrated = false; } motor.speedController.changeParameters(kp, ti); } StateManager::~StateManager(){ delete state_; } void StateManager::loopAction() { state_->action_looped(&motor); } void StateManager::transitionToState(State* nextState) { if (this->state_ != nullptr) { // this->state_->on_exit(); delete this->state_; } state_ = nextState; state_->on_entry(); } void StateManager::receive_command(char cmd) { if(cmd == 's'){ this->transitionToState(new OperationalState); currentStateIndex = 2; blinking_period = 0; led.set_hi(); } else if (cmd == 'r'){ motor.set(0.0); motor.brake(); this->transitionToState(new InitializationState); this->loopAction(); this->transitionToState(new PreOperationalState); this->loopAction(); currentStateIndex = 1; blinking_period = 48; //1Hz Serial.print("\nEnter a value for Kp: "); char chars[20]; char character; int i = 0; while(1){ if(Serial.available()) { character = Serial.read(); if(character == 13){ break; } chars[i] = character; i++; } if(i==20){ break; } } double kp = strtod(chars, nullptr); Serial.println(kp); Serial.print("Enter a value for Ti: "); char chars2[20]; char character2; int j = 0; while(1){ if(Serial.available()) { character2 = Serial.read(); if(character2 == 13){ break; } chars2[j] = character2; j++; } if(j==20){ break; } } double ti = strtod(chars2, nullptr); Serial.println(ti); Serial.print("Use integrated speed controller ? [y/n] : "); char character3[2]; int m = 0; while(1){ if(Serial.available()) { character3[m] = Serial.read(); m++; } if(m == 3){ break; } } Serial.println(character3[1]); if(character3[1] == 'y' || character3[1] == 'Y'){ motor.useIntegrated = true; } else { motor.useIntegrated = false; } motor.speedController.changeParameters(kp, ti); } else if (cmd == 'S'){ this->transitionToState(new StoppedState); currentStateIndex = 3; blinking_period = 24; //2Hz } else if (cmd == 'p'){ motor.set(0.0); motor.brake(); this->transitionToState(new PreOperationalState); currentStateIndex = 1; blinking_period = 48; //1Hz Serial.print("\nEnter a value for Kp: "); char chars[20]; char character; int i = 0; while(1){ if(Serial.available()) { character = Serial.read(); if(character == 13){ break; } chars[i] = character; i++; } if(i==20){ break; } } double kp = strtod(chars, nullptr); Serial.println(kp); Serial.print("Enter a value for Ti: "); char chars2[20]; char character2; int j = 0; while(1){ if(Serial.available()) { character2 = Serial.read(); if(character2 == 13){ break; } chars2[j] = character2; j++; } if(j==20){ break; } } double ti = strtod(chars2, nullptr); Serial.println(ti); Serial.print("Use integrated speed controller ? [y/n] : "); char character3[2]; int m = 0; while(1){ if(Serial.available()) { character3[m] = Serial.read(); m++; } if(m == 3){ break; } } Serial.println(character3[1]); if(character3[1] == 'y' || character3[1] == 'Y'){ motor.useIntegrated = true; } else { motor.useIntegrated = false; } motor.speedController.changeParameters(kp, ti); } else{ Serial.println("Command unknown ..."); } } int StateManager::get_blinking_period(){ return blinking_period; }
// Last modified: 25/12/2023 16:50 by Draggie306 // Converts Kaspersky Password Manager export to Chromium Password Manager CSV export // Permission is granted to anyone to use this software for any purpose, including commercial applications, providing that the following conditions are met: // 1. Give appropriate credit, provide a link to the original source (https://github.com/Draggie306/kaspersky-to-csv) and indicate if changes were made. // 2. Do not use this software for illegal purposes. // 3. If you find a bug, report it to me so I can fix it. // 4. If you make any changes, you must release them under the same license. // 5. Do not claim this software as your own. // 6. Have fun! // on DOM load document.addEventListener('DOMContentLoaded', function() { document.getElementById('Status').innerHTML = 'Status: Script loaded, ready to convert'; // Ensure the element exists before attaching event listener var convertButton = document.getElementById('convertButton'); if (convertButton) { convertButton.addEventListener('click', function() { var time_ms_start = Date.now(); // This looks much worse compared to the Python version. // The CSV is generated in-memory and then downloaded. // I experienced some issues with string manipulation edge cases with this version below, but I think they're all fixed now. // that's why it looks messy, the string manipulation fixes these edge cases. var accountCount = 0; var countOfAccounts = document.getElementById('countOfAccounts'); var fileInput = document.getElementById('fileInput'); try { var file = fileInput.files[0]; } catch (e) { document.getElementById('Status').innerHTML = 'Status: No file selected'; return; } var reader = new FileReader(); reader.onload = function(e) { var lines = e.target.result.split('\n'); var websites = []; var i = 0; while (i < lines.length) { var line = lines[i].trim(); if (line.includes('Websites')) { i++; while (i < lines.length && !lines[i].includes('Applications')) { if (lines[i].includes('---')) { // dashes mark new account i++; continue; } var record = {}; while (i < lines.length && !lines[i].includes('---')) { // holy this is ugly if (lines[i].includes('Website name:')) { let value = lines[i].split(':', 2)[1].trim(); record['Website name'] = `"${value.replace(/"/g, '""')}"`; } else if (lines[i].includes('Website URL:')) { let fixed_url = lines[i].replace('Website URL: ', '').trim(); if (!fixed_url.startsWith('http')) { fixed_url = 'https://' + fixed_url; } record['Website URL'] = `"${fixed_url}"`; // record['Website URL'] = `"${lines[i].replace('Website URL: ', '').trim()}"`; } else if (lines[i].includes('Login:')) { let value = lines[i].split(':', 2)[1].trim(); record['Login'] = `"${value.replace(/"/g, '"')}"`; } else if (lines[i].includes('Password:')) { let value = lines[i].split(':').slice(1).join(':').trim(); record['Password'] = `"${value.replace(/"/g, '""')}"`; } else if (lines[i].includes('Application:')) { let value = lines[i].split(':', 2)[1].trim(); record['Application'] = `"${value.replace(/"/g, '""')}"`; } else if (lines[i].includes('Comment:')) { let value = lines[i].split(':', 2)[1].trim(); record['Comment'] = `"${value.replace(/"/g, '""')}"`; } i++; } accountCount++; countOfAccounts.innerHTML = `Accounts found: ${accountCount}`; websites.push(record); } } i++; } var csvContent = 'name,url,username,password,note,isApplication\n'; for (var website of websites) { var note = website['Comment'] || ''; if (website['Website name'] && website['Website URL']) { csvContent += `${website['Website name']},${website['Website URL']},${website['Login']},${website['Password']},${note},false\n`; } else if (website['Application']) { csvContent += `${website['Application']},,${website['Login']},${website['Password']},${note},true\n`; } } var time_ms_end = Date.now(); var time_ms = time_ms_end - time_ms_start; console.log(`Conversion took ${time_ms}ms`); countOfAccounts.innerHTML = `Action completed for ${accountCount} accounts in ${time_ms}ms`; var blob = new Blob([csvContent], {type: 'text/csv'}); var url = URL.createObjectURL(blob); var downloadLink = document.getElementById('downloadLink'); downloadLink.href = url; downloadLink.download = 'kaspersky_export.csv'; downloadLink.click(); }; reader.readAsText(file); } )} } );
import React, { useState, useEffect } from "react"; import Header from "../components/Header"; import Footer from "../components/Footer"; import firebase from "../../firebase"; import { Link } from "react-router-dom"; import swal from "sweetalert"; function IniciarSesion({ usuarioAutenticado, guardarUsuarioAutenticado }) { const [visible, setVisible] = useState(false); const [loading, setLoading] = useState(false); const [user, setUser] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); try { await firebase.login(user, password); await firebase.auth.onAuthStateChanged((user) => { if (user) { console.log("autenticado", user); guardarUsuarioAutenticado(user); setUser(""); setPassword(""); setError(null); swal({ title: "Ingreso Correcto", icon: "success" }); } }); return "ok"; } catch (error) { console.log("Hubo un error al iniciar la sesion", error.message); setError(error.message); return error.message; } }; return ( <div className="container-fluid mx-auto"> <Header /> {visible && ( <div className=" z-10 absolute top-0 left-0 w-full h-screen "> <div className="bg-slate-500 opacity-50 w-full h-screen relative z-0 top-0 left-0"></div> <div className="bg-white w-2/3 md:w-3/12 h-screen p-5 opacity-100 absolute top-0 left-0 z-10 mx-auto"> <div className="flex justify-between"> <h2 className="text-center font-bold text-lg ">Menu </h2> <button onClick={() => setVisible(!visible)}>Cerrar</button> </div> <nav className="flex flex-col" onClick={() => setVisible(false)}> <Link to="/registro">Sorteo</Link> <Link to="/jugadores">Jugadores</Link> {usuarioAutenticado && ( <> <Link to="/jugadores/nuevo">Agregar Jugadores</Link> <Link to="/registro/nuevo">Agregar Participante</Link> </> )} </nav> </div> </div> )} <div> {!usuarioAutenticado ? ( <div className=" container mx-auto mt-12 md:flex contenido-principal flex justify-center"> <form onSubmit={handleSubmit} className="bg-white shadow-md rounded-lg mb-10 py-2 px-3 mx-2 lg:py-10 lg:px-10 w-full md:w-5/12 lg:mx-10" > <div className="mb-5"> <label htmlFor="user" className="block text-gray-700 uppercase"> Usuario </label> <input id="user" type="text" value={user} placeholder="Usuario" className="border-2 w-full p-2 mt-2 rounded-md" onChange={(e) => setUser(e.target.value)} /> </div> <div className="mb-5"> <label htmlFor="password" className="block text-gray-700 uppercase" > Contraseña </label> <input id="password" type="password" value={password} placeholder="Contraseña" className="border-2 w-full p-2 mt-2 rounded-md" onChange={(e) => setPassword(e.target.value)} /> </div> <input type="submit" value="Ingresar" className="text-white uppercase font-bold bg-red-600 w-full p-3 hover:bg-red-900 cursor-pointer rounded-lg transition-color" /> <button type="button" className="text-white font-bold uppercase bg-gray-700 hover:bg-gray-800 rounded-lg p-3 w-full mt-5" onClick={() => setVisible(!visible)} > Menu </button> {error && ( <p className="mt-2 bg-red-500 p-2 text-center uppercase text-white"> Hubo un error </p> )} </form> </div> ) : ( <div className="container contenido-principal mt-20 mx-auto"> <h1 className="text-center text-white font-bold"> Bienvenido {usuarioAutenticado.email} </h1> <div className="flex justify-center mt-10 mx-auto"> <div className="bg-white shadow-md rounded-lg mb-10 py-2 px-3 mx-2"> <Link to="/registro/nuevo">Sorteos</Link> </div> <div className="bg-white shadow-md rounded-lg mb-10 py-2 px-3 mx-2"> <Link to="/jugadores">Jugadores</Link> </div> </div> </div> )} </div> <Footer /> </div> ); } export default IniciarSesion;
<!DOCTYPE html> <html lang="es"> <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"> <meta name="description" content="Tienda Informatica: Las mejores propuestas para hacer realidad tu PC GAMER."> <meta name="keywords" content="COMPUTADORA, PC, INFORMATICA, GAMER, CPU, MICROPROCESADOR, AMD, INTEL, MOTHERBOARD, MEMORIA RAM, RYZEN, i5, i7, i9"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="icon" href="../img/logos/compu-logo.png"> <title>CARRITO | MAD-STORE®</title> <link rel="stylesheet" href="../css/styles.css"> <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" /> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Electrolize&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> </head> <body> <header class="header"> <nav class="navbar navbar-expand-lg navbar-dark header__navbar"> <div class="container-fluid" id="header__animation"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="../index.html"> <img src="../img/logos/compu-logo.png" alt="logo" width="30" height="24" class="d-inline-block align-text-top"> <span>MAD-STORE</span> </a> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link header__hover" href="../index.html">HOME</a> </li> <li class="nav-item"> <a class="nav-link header__hover" href="../index.html#componentes">COMPONENTES</a> </li> <li class="nav-item"> <a class="nav-link header__hover" href="../index.html#contacto">CONTACTO</a> </li> </ul> </div> <form class="d-flex header__navbarForm"> <button class="btn btn-outline-success navbarForm__button" type="submit" id="btnInnerCarrito"> <a href="#" class="header__button__link"> <i class="fa fa-shopping-cart"></i> Carrito </a> </button> </form> </div> </nav> </header> <main class="main"> <div class="main__texto"> <div class="main__carrito"> <p class="main__carritoTitulo">CARRITO DE COMPRAS</p> <p class="main__carritoTitulo--subtitulo">Aqui encontraras los productos que seleccionaste:</p> <div id="carritoVacio" class="escondido"> <br><br> <h3><strong>¡VACIASTE EL CARRITO!</strong></h3> <p>(Podes volver a seleccionar los productos en la pagina de inicio.)</p> </div> </div> </div> <!-- carrito inicio --> <div id="carritoContainer"> <!-- productos seleccionados --> <div class="row row-cols-1 row-cols-md-2 g-4 galeria" id="seleccionados"> </div> <br><br> <button type="button" class="btn btn-danger" id="vaciarCarrito">Vaciar carrito</button> <button type="button" class="btn__homeCarrito escondido"> <a href="../index.html" class="link">HOME</a> </button> <!-- Cotizacion --> <div id="totales"> <hr style="width: 100%; border: solid 2px"><br> <!-- Iva --> <h5>¿Desea factura A?</h5> <form id="iva"> <input type="radio" name="iva" value="SI">SI <input type="radio" name="iva" value="NO" checked>NO </form> <br> <!-- Cuotas --> <h5>Por favor seleccione la cantidad de cuotas</h5> <div> <select id="cuota" class="form-select" aria-label="Default select example"> <option value="1" selected>1 cuota</option> <option value="3">3 cuotas</option> <option value="6">6 cuotas</option> <option value="12">12 cuotas</option> </select> </div> <br><br> <!-- Total --> <div> <button type="button" id="btnEjecutarCotizacion" class="btn btn-danger btn__total">CONOCER COTIZACION</button> <br><br> <div id="resultadoCotizacion" style="display: none;"> </div> </div> <hr style="width: 100%; border: solid 2px"> </div> </div> <!-- carrito fin --> </main> <!-- Bootstrap 5 --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <!-- AOS Animaciones --> <script src="https://unpkg.com/aos@next/dist/aos.js"></script> <script>AOS.init();</script> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <!-- Mis scripts --> <script src="../js/views/carrito.js"></script> <script src="../js/animations/animations.js"></script> </body> </html>
package com.bravedeveloper.sandbase.presentation.base.views import android.content.Context import android.content.res.TypedArray import android.os.Parcelable import android.text.InputType import android.text.method.DigitsKeyListener import android.util.AttributeSet import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.view.isVisible import com.bravedeveloper.domain.model.city.order.OrderStatusEnum import com.bravedeveloper.sandbase.R import com.bravedeveloper.sandbase.presentation.base.phoneedittext.PhoneTextWatcher import com.google.android.material.textfield.TextInputEditText class InfoItemView(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) { companion object { private const val DEFAULT_INPUT_TYPE = 17 } private var infoItemTitle: TextView private var infoItemDescription: TextInputEditText private var divider: View private var isDividerVisible: Boolean private var isEditable: Boolean private var isDisabled: Boolean private var isHidden: Boolean private var inputType: Int private var hint: String? private var digits: String? init { LayoutInflater.from(context).inflate(R.layout.order_info_item, this, true) infoItemTitle = findViewById(R.id.info_title) infoItemDescription = findViewById(R.id.info_description) divider = findViewById(R.id.divider) val attributesArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.InfoItemView) infoItemTitle.text = attributesArray.getText(R.styleable.InfoItemView_titleText) infoItemDescription.setText(attributesArray.getText(R.styleable.InfoItemView_descriptionText)) infoItemDescription.maxEms = attributesArray.getInteger(R.styleable.InfoItemView_maxEms, Integer.MAX_VALUE) isDividerVisible = attributesArray.getBoolean(R.styleable.InfoItemView_dividerIsVisible, true) isEditable = attributesArray.getBoolean(R.styleable.InfoItemView_descriptionIsEditable, false) isDisabled = attributesArray.getBoolean(R.styleable.InfoItemView_disabledStyle, false) isHidden = attributesArray.getBoolean(R.styleable.InfoItemView_hiddenStyle, false) inputType = attributesArray.getInt(R.styleable.InfoItemView_android_inputType, DEFAULT_INPUT_TYPE) hint = attributesArray.getString(R.styleable.InfoItemView_android_hint) digits = attributesArray.getString(R.styleable.InfoItemView_android_digits) val textSize = attributesArray.getDimension(R.styleable.InfoItemView_descriptionTextSize, 18f) infoItemDescription.textSize = textSize setDigits(digits) setHint(hint) setDescriptionInputType(inputType) disableDivider(isDividerVisible) setEditable(isEditable) setDisabledStyle(isDisabled) setHiddenStyle(isHidden) attributesArray.recycle() } private fun disableDivider(isVisible: Boolean) { if (isVisible) { divider.visibility = View.VISIBLE } else { divider.visibility = View.GONE } } private fun setDigits(digits: String?) { if (digits != null) infoItemDescription.keyListener = DigitsKeyListener.getInstance(digits) } private fun setHint(hintText: String?) { infoItemDescription.hint = hintText } fun setPhoneNumberTextWatcher() { infoItemDescription.addTextChangedListener(PhoneTextWatcher(infoItemDescription)) } fun setEditable(isEditable: Boolean) { infoItemDescription.isEnabled = isEditable if (isEditable) { setDescriptionInputType(inputType) } else { setDescriptionInputType(InputType.TYPE_NULL) } } fun setDisabledStyle(isDisabled: Boolean) { if (isDisabled) { infoItemDescription.setTextColor(ContextCompat.getColor(context, R.color.dark_gray)) } else { infoItemDescription.setTextColor(ContextCompat.getColor(context, R.color.black)) } } private fun setHiddenStyle(isHidden: Boolean) { if (isHidden) { infoItemDescription.setTextColor(ContextCompat.getColor(context, R.color.grey3)) } else { infoItemDescription.setTextColor(ContextCompat.getColor(context, R.color.black)) } } fun setDescription(description: String?) { infoItemDescription.setText(description) } fun getDescription(): String { return infoItemDescription.text.toString() } fun setTitle(title: String?) { infoItemTitle.text = title } fun getTitle(): String { return infoItemTitle.text.toString() } fun hideDivider(hide: Boolean) { divider.isVisible = !hide } private fun setDescriptionInputType(inputType: Int) { infoItemDescription.inputType = inputType } fun setStatus(status: OrderStatusEnum?) { infoItemDescription.setText(when (status) { OrderStatusEnum.NEW -> context.getString(R.string.active_order) OrderStatusEnum.IN_PROGRESS -> context.getString(R.string.exec_orders) OrderStatusEnum.CANCELED -> context.getString(R.string.cancelled) OrderStatusEnum.CLOSED -> context.getString(R.string.closed) OrderStatusEnum.DONE -> context.getString(R.string.done) OrderStatusEnum.ON_MODERATION -> context.getString(R.string.on_moderation) OrderStatusEnum.WAITING_FOR_CONFIRMATION -> context.getString(R.string.evaluating_orders) else -> context.getString(R.string.no_data) }) } override fun setOnFocusChangeListener(l: OnFocusChangeListener?) { infoItemDescription.setOnFocusChangeListener { view, b -> l?.onFocusChange(view, b) refreshDrawableState() } } override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) { dispatchFreezeSelfOnly(container) } override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) { dispatchThawSelfOnly(container) } }
const express = require('express'); const router = express.Router(); const { User } = require("../models/User") const { auth } = require("../middleware/auth"); router.post('/signup', (req, res) => { const user = new User(req.body); user.save((err, userInfo) => { if (err) return res.json({ success: false, err }); res.status(200).json({ success: true, userInfo }); }); }); router.post('/signin', (req, res) => { // 요청된 정보가 DB에 있는지 찾음 User.findOne({ id: req.body.id }, (err, user) => { if (!user) return res.json({ loginSuccess: false, message: '가입되어 있지 않습니다' }); // DB에 있다면 비밀번호가 맞는지 확인 user.comparePassword(req.body.password, (err, isMatch) => { if (!isMatch) return res.json({ loginSuccess: false, message: '비밀번호가 일치하지 않습니다' }) }) // 비밀번호가 맞으면 토큰 생성 user.generateToken((err, user) => { if (err) return res.status(400).send(err); // 토큰을 쿠키에 저장 res.cookie("auth", user.token) .status(200) .json({ loginSuccess: true, userID: user._id }) }) }) }) router.get('/auth', auth, (req, res) => { res.status(200).json({ _id: req.user._id, isAdmin: req.user.role === 0 ? false : true, isAuth: true, id: req.user.idy, role: req.user.role }) }) router.get('/logout', auth, (req, res) => { User.findOneAndUpdate({ _id: req.user._id }, { token: '' } , (err, user) => { if (err) return res.json({ success: false, err }); res.status(200).send({ success: true }) } ) }) module.exports = router;
import { styled } from 'styled-components'; import { CardInnerProps } from './Card'; const Card = styled.article` position: relative; display: flex; flex-basis: 100%; overflow: hidden; ${({ theme }) => ({ borderRadius: theme.global.borderRadius, })}; `; const Inner = styled.div.withConfig({ shouldForwardProp: (prop) => !['warning'].includes(prop), })<CardInnerProps>` width: 100%; display: flex; flex-direction: column; padding: 0; ${({ warning }) => ({ filter: warning ? 'blur(0.25rem)' : 'none', })}; `; type HeaderProps = { owned?: boolean }; const Header = styled.div.withConfig({ shouldForwardProp: (prop) => !['owned'].includes(prop), })<HeaderProps>` display: flex; justify-content: space-between; align-items: flex-start; ${({ theme, owned }) => ({ backgroundColor: owned ? theme.colors.secondary : theme.colors.grey, padding: theme.spacing.lg, })}; h2, h3, h4 { margin: 0; padding: 0; text-overflow: ellipsis; overflow: hidden; background-color: transparent; color: inherit; ${({ theme }) => ({ ...theme.fonts.h2, fontFamily: theme.global.fontFamily, })}; } > :first-child { margin-right: ${({ theme }) => theme.spacing.lg}; } `; const Body = styled.div` display: flex; flex-direction: column; flex: 1; ${({ theme }) => ({ backgroundColor: theme.colors.greyVariant, padding: theme.spacing.lg, })}; `; const Edit = styled.footer` display: flex; justify-content: space-between; ${({ theme }) => ({ marginTop: theme.spacing.xl, })}; `; const IconControls = styled.div` display: flex; flex-direction: row; justify-content: flex-start; ${({ theme }) => ({ paddingTop: theme.spacing.lg, ['> *']: { marginRight: theme.spacing.xl, }, })} `; const InputError = styled.span` ${({ theme }) => ({ color: theme.colors.danger, marginTop: theme.spacing.md, fontSize: theme.fonts.detail.fontSize, })}; `; const CardStyled = { Card, Inner, Header, Body, Edit, IconControls, InputError, }; export default CardStyled;
#include "lists.h" #include <stdlib.h> /** *insert_nodeint_at_index - inserts node at a given position *@head: input link list *@idx: index of list where the new node added *@n: integer value to be added *Return: address of the new code */ listint_t *insert_nodeint_at_index(listint_t **head, unsigned int idx, int n) { listint_t *new, *temp, *current; int i; temp = *head; if (temp == NULL) return (NULL); new = malloc(sizeof(listint_t)); if (new == NULL) return (NULL); new->n = n; if (idx == 0) { new->next = temp; *head = new; return (*head); } for (i = 0; temp; i++) { if (i == (int) idx - 1) { current = temp->next; temp->next = new; new->next = current; return (new); } temp = temp->next; } return (NULL); }
/* A string identifier for a probabilistic annotation object. */ typedef string probanno_id; /* A string identifier for a genome. */ typedef string genome_id; /* A string identifier for a workspace. Any string consisting of alphanumeric characters and "-" is acceptable. */ typedef string workspace_id; /* A string identifier for a feature. */ typedef string feature_id; /* A function_probability is a (annotation, probability) pair associated with a gene An annotation is a "///"-delimited list of roles that could be associated with that gene. */ typedef tuple<string, float> function_probability; /* Object to carry alternative functions and probabilities for genes in a genome probanno_id id - ID of the probabilistic annotation object genome_id genome - ID of the genome the probabilistic annotation was built for workspace_id genome_workspace - ID of the workspace containing genome mapping<feature_id, list<function_probability>> roleset_probabilities - mapping of features to list of alternative function_probability objects list<feature_id> skipped_features - list of features in genome with no probability */ typedef structure { probanno_id id; genome_id genome; workspace_id genome_workspace; mapping<feature_id, list<function_probability>> roleset_probabilities; list<feature_id> skipped_features; } ProbAnno;
//{ Driver Code Starts //Initial Template for C++ #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *next, *prev; Node(int val) : data(val), next(NULL), prev(NULL) { } }; // } Driver Code Ends //User function Template for C++ /* Doubly linked list node class class Node { public: int data; Node *next, *prev; Node(int val) : data(val), next(NULL), prev(NULL) { } }; */ class Solution { public: vector<pair<int,int>>ans; Node* findLastNode(Node* head) { Node* prev; while(head) { prev=head; head=head->next; } return prev; } vector<pair<int, int>> findPairsWithGivenSum(Node *head, int target) { //unordered_map<int,int>mp; Node* last=findLastNode(head); // // cout<<last->data<<endl; // while(head!=NULL) // { // if(mp.find(target-head->data)!=mp.end()) // { // ans.push_back({target-head->data,head->data}); // } // mp[head->data]++; // head=head->next; // } // sort(ans.begin(),ans.end()); while(head!=last && head!=NULL && last!=NULL) { if(head->data+last->data==target && head->data<last->data) { ans.push_back({head->data,last->data}); head=head->next; last=last->prev; } else if(head->data+last->data<target) { head=head->next; } else { last=last->prev; } } return ans; } }; //{ Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n, target; cin >> target >> n; int a; cin >> a; Node *head = new Node(a); Node *tail = head; for (int i = 0; i < n - 1; i++) { cin >> a; tail->next = new Node(a); tail->next->prev = tail; tail = tail->next; } Solution ob; auto ans = ob.findPairsWithGivenSum(head, target); if (ans.size() == 0) cout << "-1"; else { for (int i = 0; i < ans.size(); i++) { cout << "(" << ans[i].first << "," << ans[i].second << ")" << " "; } } cout << "\n"; } return 0; } // } Driver Code Ends
import unittest import numpy as np from Financial_Growth_Trends import financialGrowthTrends class TestFinancialGrowthTrends(unittest.TestCase): # Test 1: Empty input def test_empty_input(self): with self.assertRaises(ValueError) as context: financialGrowthTrends([]) self.assertTrue("The input array is empty. Please provide a non-empty array." in str(context.exception)) # Test 2: Non-numeric values def test_non_numeric_values(self): with self.assertRaises(ValueError) as context: financialGrowthTrends(['a', 'b', 'c']) self.assertTrue("The input array should contain only numeric values (int or float)." in str(context.exception)) # Test 3: Single value def test_single_value(self): result = financialGrowthTrends([2]) expected = np.array([4]) np.testing.assert_array_equal(result, expected) # Test 4: All positive values def test_all_positive_values(self): result = financialGrowthTrends([1, 2, 3]) expected = np.array([1, 4, 9]) np.testing.assert_array_equal(result, expected) # Test 5: All negative values def test_all_negative_values(self): result = financialGrowthTrends([-1, -2, -3]) expected = np.array([1, 4, 9]) np.testing.assert_array_equal(result, expected) # Test 6: Mixed positive and negative values def test_mixed_values(self): result = financialGrowthTrends([-2, -1, 0, 1, 2]) expected = np.array([0, 1, 1, 4, 4]) np.testing.assert_array_equal(result, expected) # Test 7: Contains zero def test_contains_zero(self): result = financialGrowthTrends([0, 1, 2]) expected = np.array([0, 1, 4]) np.testing.assert_array_equal(result, expected) # Test 8: Duplicates in input def test_duplicates_in_input(self): result = financialGrowthTrends([2, 2, -2, -2]) expected = np.array([4, 4, 4, 4]) np.testing.assert_array_equal(result, expected) # Test 9: Large values def test_large_values(self): result = financialGrowthTrends([1000, -1000]) expected = np.array([1000000, 1000000]) np.testing.assert_array_equal(result, expected) # Test 10: Float values def test_float_values(self): result = financialGrowthTrends([1.5, -1.5, 2.5]) expected = np.array([2.25, 2.25, 6.25]) np.testing.assert_array_equal(result, expected) if __name__ == '__main__': unittest.main()
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity.Core.Objects; using System.Linq; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Web.Http; using System.Web.Http.Results; using Jose; using NCMSystem.Filter; using NCMSystem.Models; using NCMSystem.Models.CallAPI; using NCMSystem.Models.CallAPI.User.ChangePassword; using NCMSystem.Models.CallAPI.User.ForgotPassword; using NCMSystem.Models.CallAPI.User.RefreshToken; using NCMSystem.Models.CallAPI.User.UserLogin; using Newtonsoft.Json; namespace NCMSystem.Controllers { public class UserController : ApiController { private NCMSystemEntities db = new NCMSystemEntities(Environment.GetEnvironmentVariable("NCMSystemEntities")); [HttpPost] [Route("api/auth/login")] public ResponseMessageResult Login([FromBody] UserRequest request) { string email = request.Email; string password = request.Password; // check null email or password if (email == null || password == null) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0004", }), Encoding.UTF8, "application/json") }); } var user = db.users.FirstOrDefault(x => x.email == email); // check user exist if (user == null ) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0003", }), Encoding.UTF8, "application/json") }); } if (!BCrypt.Net.BCrypt.Verify(password, user.password)) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0003", }), Encoding.UTF8, "application/json") }); } // check user is active if (user.isActive == false) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0002", }), Encoding.UTF8, "application/json") }); } // init date create-expire for token and refresh token DateTimeOffset dateCreateToken = DateTimeOffset.Now; DateTimeOffset dateExpireToken = dateCreateToken.AddMinutes(30); DateTimeOffset dateExpireRefreshToken = dateCreateToken.AddMonths(1); var token = GenerateToken(user.id, dateCreateToken.ToUnixTimeSeconds(), dateExpireToken.ToUnixTimeSeconds(), user.role_id); var refreshToken = GenerateRefreshToken(user.id, dateCreateToken.ToUnixTimeSeconds(), dateExpireRefreshToken.ToUnixTimeSeconds()); // add refresh token to database db.tokens.Add(new token() { user_id = user.id, refresh_token = refreshToken, created_date = dateCreateToken.DateTime, expired_date = dateExpireRefreshToken.DateTime }); db.SaveChanges(); // return success response return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0001", Data = new UserToken() { Token = token, RefreshToken = refreshToken }, }), Encoding.UTF8, "application/json") }); } [HttpPost] [Route("api/auth/refresh-token")] public ResponseMessageResult PostRefreshToken([FromBody] RefreshTokenRequest request) { string refreshToken = request.RefreshToken; // check null refresh token if (refreshToken == null) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0010", }), Encoding.UTF8, "application/json") }); } var selectToken = db.tokens.FirstOrDefault(e => e.refresh_token == refreshToken); // check token exist if (selectToken == null) { return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0005", }), Encoding.UTF8, "application/json") }); } var selectUser = db.users.FirstOrDefault(e => e.id == selectToken.user_id); // check refresh token exist if (selectToken.expired_date < DateTime.Now) { // delete refresh token db.tokens.Remove(selectToken); db.SaveChanges(); return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "U0009", }), Encoding.UTF8, "application/json") }); } // init date create-expire for token DateTimeOffset dateCreateToken = DateTimeOffset.Now; DateTimeOffset dateExpireToken = dateCreateToken.AddMinutes(30); var token = GenerateToken(selectToken.user_id, dateCreateToken.ToUnixTimeSeconds(), dateExpireToken.ToUnixTimeSeconds(), selectUser.role_id); // return success response return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "Get new token success", Data = new RefreshTokenResponse() { Token = token, }, }), Encoding.UTF8, "application/json") }); } [HttpPost] [Route("api/auth/change-password")] [JwtAuthorizeFilter(NcmRoles = new[] { NcmRole.Staff, NcmRole.Manager, NcmRole.SaleDirector })] public ResponseMessageResult ChangePassword([FromBody] ChangePasswordRequest request) { string newPassword = request.NewPassword; string oldPassword = request.OldPassword; // check null new password if (string.IsNullOrWhiteSpace(newPassword) || string.IsNullOrWhiteSpace(oldPassword)) { return Common.ResponseMessage.BadRequest("U0004"); } newPassword = newPassword.Trim(); oldPassword = oldPassword.Trim(); int userId = ((JwtToken)Request.Properties["payload"]).Uid; var selectUser = db.users.FirstOrDefault(e => e.id == userId); if (selectUser == null) { return Common.ResponseMessage.BadRequest("C0018"); } if (!selectUser.password.Equals(oldPassword)) { return Common.ResponseMessage.BadRequest("U0007"); } // check match new password and old password if (newPassword == oldPassword) { return Common.ResponseMessage.BadRequest("U0005"); } // check new password regex if (!Regex.IsMatch(newPassword, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}$")) { return Common.ResponseMessage.BadRequest("U0006"); } selectUser.password = BCrypt.Net.BCrypt.HashPassword(newPassword); db.tokens.RemoveRange(db.tokens.Where(e => e.user_id == userId)); // init date create-expire for token and refresh token DateTimeOffset dateCreateToken = DateTimeOffset.Now; DateTimeOffset dateExpireToken = dateCreateToken.AddMinutes(30); DateTimeOffset dateExpireRefreshToken = dateCreateToken.AddMonths(1); var token = GenerateToken(userId, dateCreateToken.ToUnixTimeSeconds(), dateExpireToken.ToUnixTimeSeconds(), selectUser.role_id); var refreshToken = GenerateRefreshToken(userId, dateCreateToken.ToUnixTimeSeconds(), dateExpireRefreshToken.ToUnixTimeSeconds()); // add refresh token to database db.tokens.Add(new token() { user_id = userId, refresh_token = refreshToken, created_date = dateCreateToken.DateTime, expired_date = dateExpireRefreshToken.DateTime }); db.SaveChanges(); return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "Change password success", Data = new UserToken() { Token = token, RefreshToken = refreshToken }, }), Encoding.UTF8, "application/json") }); } [HttpPost] [Route("api/auth/forgot-password/send-email")] public ResponseMessageResult ForgotPasswordSendEmail([FromBody] ForgotPasswordSendEmailRequest request) { if (request == null) return Common.ResponseMessage.BadRequest("Request must contain body"); string email = request.Email; // check null email if (string.IsNullOrWhiteSpace(email)) return Common.ResponseMessage.BadRequest("U0004"); email = email.Trim(); // check email regex var isValidate = Validator.Validator.CheckEmailCorrect(email); if (!isValidate) return Common.ResponseMessage.BadRequest("U0004"); var selectUser = db.users.FirstOrDefault(e => e.email == email); if (selectUser == null) return Common.ResponseMessage.NotFound("C0018"); // random number length 6 var randomNumber = new Random().Next(100000, 999999).ToString(); var expireTime = DateTime.Now.AddMinutes(10); // add forgot password to database selectUser.code_resetPw = randomNumber; selectUser.exp_code = expireTime; db.SaveChanges(); // send email SendGridConfig.SendCodeResetPassword(email, randomNumber); return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "Send email success", }), Encoding.UTF8, "application/json") }); } [HttpPost] [Route("api/auth/forgot-password/check-code")] public ResponseMessageResult ForgotPasswordCheckCode([FromBody] ForgotPasswordCheckCodeRequest request) { if (request == null) return Common.ResponseMessage.BadRequest("Request must contain body"); string code = request.Code; string email = request.Email; // check null code if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(email)) return Common.ResponseMessage.BadRequest("U0004"); code = code.Trim(); email = email.Trim(); // get user by email var selectUser = db.users.FirstOrDefault(e => e.email == email && e.code_resetPw == code); if (selectUser == null) return Common.ResponseMessage.NotFound("U0011"); if (selectUser.exp_code < DateTime.Now) return Common.ResponseMessage.BadRequest("U0008"); return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "Code is correct", }), Encoding.UTF8, "application/json") }); } [HttpPost] [Route("api/auth/forgot-password/submit")] public ResponseMessageResult ForgotPasswordSubmit([FromBody] ForgotPasswordSubmitRequest request) { if (request == null) return Common.ResponseMessage.BadRequest("Request must contain body"); string code = request.Code; string email = request.Email; string password = request.Password; // check null code or email or password if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) return Common.ResponseMessage.BadRequest("U0004"); code = code.Trim(); email = email.Trim(); password = password.Trim(); // get user by email var selectUser = db.users.FirstOrDefault(e => e.email == email && e.code_resetPw == code); if (selectUser == null) return Common.ResponseMessage.NotFound("U0011"); if (selectUser.exp_code < DateTime.Now) return Common.ResponseMessage.BadRequest("U0008"); // check password regex if (!Regex.IsMatch(password, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}$")) return Common.ResponseMessage.BadRequest( "U0006"); selectUser.password = BCrypt.Net.BCrypt.HashPassword(password); selectUser.code_resetPw = null; selectUser.exp_code = null; db.tokens.RemoveRange(db.tokens.Where(e => e.user_id == selectUser.id)); // generate new token DateTimeOffset dateCreateToken = DateTimeOffset.Now; DateTimeOffset dateExpireToken = dateCreateToken.AddMinutes(30); DateTimeOffset dateExpireRefreshToken = dateCreateToken.AddMonths(1); var token = GenerateToken(selectUser.id, dateCreateToken.ToUnixTimeSeconds(), dateExpireToken.ToUnixTimeSeconds(), selectUser.role_id); var refreshToken = GenerateRefreshToken(selectUser.id, dateCreateToken.ToUnixTimeSeconds(), dateExpireRefreshToken.ToUnixTimeSeconds()); db.tokens.Add(new token() { user_id = selectUser.id, refresh_token = refreshToken, created_date = dateCreateToken.DateTime, expired_date = dateExpireRefreshToken.DateTime }); db.SaveChanges(); return new ResponseMessageResult(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new CommonResponse() { Message = "Reset password success", Data = new UserToken() { Token = token, RefreshToken = refreshToken } }), Encoding.UTF8, "application/json") }); } private string GenerateToken(int userId, long createTime, long expireTime, int userRole) { Jwk keyToken = new Jwk(Encoding.ASCII.GetBytes(Environment.GetEnvironmentVariable("JWT_SECRET_KEY_TOKEN") ?? string.Empty)); // init date create-expire for token and refresh token string token = Jose.JWT.Encode(new Dictionary<string, object>() { { "uid", userId }, { "iat", createTime }, { "exp", expireTime }, { "role", userRole } }, keyToken, JwsAlgorithm.HS256); return token; } private string GenerateRefreshToken(int userId, long createTime, long expireTime) { Jwk keyRefreshToken = new Jwk(Encoding.ASCII.GetBytes(Environment.GetEnvironmentVariable("JWT_SECRET_KEY_REFRESH_TOKEN") ?? string.Empty)); // init date create-expire for token and refresh token DateTimeOffset dateCreateToken = DateTimeOffset.Now; DateTimeOffset dateExpireRefreshToken = dateCreateToken.AddMonths(1); string refreshToken = Jose.JWT.Encode(new Dictionary<string, object>() { { "uid", userId }, { "iat", createTime }, { "exp", expireTime } }, keyRefreshToken, JwsAlgorithm.HS256); return refreshToken; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IMDB Clone - Watchlist</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <header class="bg-dark text-white p-2"> <div class="container d-flex justify-content-between align-items-center"> <div class="d-flex align-items-center"> <img src="{% static 'images/IMDB_Logo_2016.png' %}" alt="IMDB Logo" height="40"> <nav class="ml-4"> <a href="{% url 'home' %}" class="text-white mr-3">Home</a> </nav> </div> <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="get"> <input class="form-control mr-sm-2" type="search" name="query" placeholder="Search IMDB" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> <div class="d-flex align-items-center"> <img src="{% static 'images/IMDB_Pro_Logo.png' %}" alt="IMDB Pro Logo" height="40"> <a href="{% url 'watchlist' %}" class="text-white ml-3">Watchlist</a> {% if user.is_authenticated %} <span class="text-white ml-3">Welcome, {{ user.first_name }}</span> <a href="{% url 'logout' %}" class="text-white ml-3">Logout</a> {% else %} <a href="{% url 'login' %}" class="text-white ml-3">Sign In</a> {% endif %} <div class="dropdown ml-3"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> TR <i class="fa fa-globe"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#" data-lang="TR">TR</a> <a class="dropdown-item" href="#" data-lang="EN">EN</a> </div> </div> </div> </div> </header> <main class="container mt-4"> <section class="watchlist"> <h2 class="mb-4">Watchlist</h2> {% if movies %} <ul class="list-group"> {% for movie in movies %} <li class="list-group-item d-flex justify-content-between align-items-center"> <a href="{% url 'movie_detail' movie.id %}">{{ movie.title }}</a> <form action="{% url 'remove_from_watchlist' movie.id %}" method="POST" class="ml-auto"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Remove</button> </form> </li> {% endfor %} </ul> {% else %} <p>No movies in your watchlist.</p> {% endif %} </section> </main> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html>
import { Component, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { MessageService } from 'primeng-lts'; import { EMPTY, of } from 'rxjs'; import { catchError, switchMap } from 'rxjs/operators'; import { A4gMessages, A4gSeverityMessage } from 'src/app/a4g-common/a4g-messages'; import { ErrorDTO } from 'src/app/a4g-common/interfaces/error.model'; import { PaginatorA4G } from 'src/app/a4g-common/interfaces/paginator.model'; import { ErrorService } from 'src/app/a4g-common/services/error.service'; import { PaginatorEvent, Paginazione, SortDirection } from 'src/app/a4g-common/utility/paginazione'; import { GruppoLavorazioneDto, LavorazioneDto } from 'src/app/uma/core-uma/models/dto/ConfigurazioneDto'; import { TipologiaLavorazioneEnum } from 'src/app/uma/core-uma/models/enums/TipologiaLavorazione.enum'; import { UnitaMisura } from 'src/app/uma/core-uma/models/enums/UnitaMisura.enum'; import { HttpClientConfigurazioneUmaService } from 'src/app/uma/core-uma/services/http-client-configurazione-uma.service'; import { UMA_MESSAGES } from 'src/app/uma/uma.messages'; @Component({ selector: 'app-lavorazioni', templateUrl: './lavorazioni.component.html', styleUrls: ['./lavorazioni.component.css'] }) export class LavorazioniComponent implements OnInit { lavorazioni: PaginatorA4G<Array<LavorazioneDto>>; lavorazione: LavorazioneDto; gruppiLavorazione: GruppoLavorazioneDto[]; cols: any; displayDialog: boolean; newLavorazione: boolean; selectedLavorazione: LavorazioneDto; elementiPagina = 10; sortBy: string = 'nome'; sortDirection: SortDirection; unitaMisuraEnum = Object.keys(UnitaMisura).map(key => ({ label: UnitaMisura[key], value: key })); selectedUnitaMisura: any; tipologiaLavorazioneEnum = Object.keys(TipologiaLavorazioneEnum).map(key => ({ label: TipologiaLavorazioneEnum[key], value: key })); selectedTipologiaLavorazione: any; constructor( private messageService: MessageService, private httpClientConfigurazioneUmaService: HttpClientConfigurazioneUmaService, private translateService: TranslateService, private errorService: ErrorService ) { } ngOnInit() { this.setCols(); this.lavorazioni = {} as PaginatorA4G<Array<LavorazioneDto>>; this.lavorazioni.count = 0; this.lavorazioni.risultati = []; this.getGruppiLavorazione(); } private setCols() { this.cols = [ { field: 'indice', header: 'Indice' }, { field: 'nome', header: 'Nome' }, { field: 'tipologia', header: 'Tipologia' }, { field: 'unitaDiMisura', header: 'Unità di misura' }, { field: 'gruppoLavorazione', header: 'Gruppo lavorazione' } ]; } private getGruppiLavorazione() { let paginazione: Paginazione = Paginazione.of(0, 1000, 'nome', SortDirection.ASC); this.httpClientConfigurazioneUmaService.getGruppiLavorazioni(paginazione).subscribe({ next: value => this.gruppiLavorazione = value.risultati, error: e => { if (e.status === 404) { this.messageService.add(A4gMessages.getToast('tst-lav', A4gSeverityMessage.error, this.translateService.instant('NO_CONTENT'))); } else { this.messageService.add(A4gMessages.getToast('tst-lav', A4gSeverityMessage.error, e)); } } }); } canSave(lavorazione: LavorazioneDto) { return lavorazione.gruppoLavorazione && lavorazione.indice && lavorazione.nome && lavorazione.tipologia && lavorazione.unitaDiMisura; } showDialogToAdd() { this.selectedUnitaMisura = null; this.selectedTipologiaLavorazione = null; this.newLavorazione = true; this.lavorazione = {} as LavorazioneDto; this.lavorazione.id = null; this.displayDialog = true; } save() { this.lavorazione.unitaDiMisura = (this.selectedUnitaMisura && this.selectedUnitaMisura.value) ? this.selectedUnitaMisura.value : null; this.lavorazione.tipologia = (this.selectedTipologiaLavorazione && this.selectedTipologiaLavorazione.value) ? this.selectedTipologiaLavorazione.value : null; if (this.canSave(this.lavorazione)) { this.httpClientConfigurazioneUmaService.postLavorazione(this.lavorazione) .subscribe({ next: resp => { this.messageService.add(A4gMessages.getToast('tst-lav', A4gSeverityMessage.success, UMA_MESSAGES.salvataggioOK)); this.changePage(null); this.lavorazione = null; this.displayDialog = false; }, error: e => this.messageService.add(A4gMessages.getToast('tst-lav', A4gSeverityMessage.error, e)) }) } else this.messageService.add(A4gMessages.getToast('tst-lav', A4gSeverityMessage.warn, UMA_MESSAGES.mandatoryAll)); } onRowSelect(event) { this.newLavorazione = false; this.lavorazione = this.cloneLavorazione(event.data); this.displayDialog = true; } cloneLavorazione(c: LavorazioneDto): LavorazioneDto { var lavorazione = {} as LavorazioneDto; for (let prop in c) { lavorazione[prop] = c[prop]; } this.selectedUnitaMisura = this.unitaMisuraEnum.find(x => x.value === lavorazione.unitaDiMisura); this.selectedTipologiaLavorazione = this.tipologiaLavorazioneEnum.find(x => x.value === lavorazione.tipologia); return lavorazione; } changePage(event: PaginatorEvent) { if (event != null) { this.sortDirection = event.sortOrder === 1 ? SortDirection.ASC : SortDirection.DESC; this.sortBy = event.sortField || this.sortBy; } let paginazione: Paginazione = Paginazione.of( Math.floor(event.first / this.elementiPagina), this.elementiPagina, this.sortBy, this.sortDirection || SortDirection.ASC ); this.httpClientConfigurazioneUmaService.getLavorazioni(paginazione) .pipe(switchMap((res: PaginatorA4G<Array<LavorazioneDto>>) => { return of(res); }), catchError((err: ErrorDTO) => { this.errorService.showError(err, 'tst-gruppi-lav'); return EMPTY; }) ) .subscribe((result: PaginatorA4G<Array<LavorazioneDto>>) => { this.lavorazioni = result; }, error => this.errorService.showError(error, 'tst-gruppi-lav')); } }
import React, { FormEvent, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAuth } from '../../hooks/useAuth'; import api from '../../services/api'; import Logo from '../../assets/LOGO (1).png'; import { Container } from './styles'; function RegisterUser() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const navigate = useNavigate(); const { Login, signed } = useAuth(); async function handleRegisterNewUser(e: FormEvent) { e.preventDefault(); const response = await api.post('api/register', { name, email, password, }); if (response.data.status === 'sucess') { await Login({ email, password, }); } console.log(response.data); } if (signed) { navigate('/'); } return ( <Container> <img src={Logo} alt="cryto_racing" /> <form onSubmit={handleRegisterNewUser}> <fieldset> <label htmlFor="">Name: </label> <input type="text" value={name} onChange={(e) => setName(e.target.value)} required /> </fieldset> <fieldset> <label htmlFor="">Email: </label> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /> </fieldset> <fieldset> <label htmlFor="">Password: </label> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required /> </fieldset> <button type="submit">Sign-Up</button> </form> </Container> ); } export default RegisterUser;
using System.Collections; using System.Collections.Generic; using UnityEngine; using Define; using DataContents; public class PlayerStat : BaseStat { protected float _mp; protected float _maxmp; protected float _exp; protected int _gold; protected float _plushp; protected float _plusmp; protected float _plusdamage; protected float _plusdefense; #region [ Property ] public float MP { get { return _mp; } set { _mp = value; } } public float MaxMP { get { return _maxmp; } set { _maxmp = value; } } public int Gold { get { return _gold; } set { _gold = value; } } public float PlusHP { get { return _plushp; } } public float PlusMP { get { return _plusmp; } } public float PlusDamage { get { return _plusdamage; } } public float PlusDefense { get { return _plusdefense; } } public float EXP { get { if(_level == 1) { return _exp; } else { if (Managers._data.Dict_Stat.TryGetValue(_level, out DataByLevel stat)) { return _exp - stat.exp; } else return -1; } } set { _exp = value; int level = 1; while (true) { if (Managers._data.Dict_Stat.TryGetValue(level + 1, out DataByLevel stat) == false) break; if (_exp < stat.exp) break; level++; } if(level != _level) { _level = level; } } } public float TotalEXP { get { if (Managers._data.Dict_Stat.TryGetValue(_level, out DataByLevel stat) == false) { return -1; } else { if (Managers._data.Dict_Stat.TryGetValue(_level + 1, out DataByLevel Nextstat) == false) { return -1; } else { return Nextstat.exp - stat.exp; } } } } #endregion [ Property ] void Init() { _level = 1; _hp = _maxhp = 200; _mp = _maxmp = 200; _damage = 20; _defense = 5; _exp = 0; _gold = 0; _moveSpeed = 10; _plushp = 0; _plusmp = 0; _plusdamage = 0; _plusdefense = 0; } public void SetStat(int level) { DataByLevel stat = Managers._data.Dict_Stat[level]; _hp = _maxhp = stat.hp; _mp = _maxmp = stat.mp; _damage = stat.damage; _defense = stat.defense; SetMaxData(); } public void LoadPlayer() { PlayerData stat = Managers._data.playerData; if(stat != null) { _level = stat.level; if(Managers._data.Dict_Stat.TryGetValue(_level, out DataByLevel DBL)) { SetPlayerData(stat.nowhp, DBL.hp, stat.nowmp, DBL.mp, DBL.damage, DBL.defense, stat.nowexp, stat.gold); SetPlusData(stat.plushp, stat.plusmp, stat.plusdamage, stat.plusdefense); } else { Init(); } } else { Init(); } } public PlayerData SavePlayer() { if(_hp <= 0) { Init(); } PlayerData save = new PlayerData() { level = _level, nowhp = _hp, nowmp = _mp, nowexp = _exp, gold = _gold, plushp = _plushp, plusmp = _plusmp, plusdamage = _plusdamage, plusdefense = _plusdefense }; return save; } void SetPlayerData(float hp, float maxhp, float mp, float maxmp, float damage,float defense, float exp, int gold) { _hp = Mathf.Min(hp, maxhp); _mp = Mathf.Min(mp, maxmp); _maxhp = maxhp; _maxmp = maxmp; _damage = damage; _defense = defense; _exp = exp; _gold = gold; _moveSpeed = 10; } void SetPlusData(float hp, float mp, float dam, float def) { _plushp = hp; _plusmp = mp; _plusdamage = dam; _plusdefense = def; SetMaxData(); } void SetMaxData() { _maxhp += _plushp; _maxmp += _plusmp; _damage += _plusdamage; _defense += _plusdefense; } public void AddPlusStat(eStat type, float value) { switch (type) { case eStat.HP: _plushp += value; _hp = Mathf.Min(_hp, _maxhp); _maxhp += value; break; case eStat.MP: _plusmp += value; _mp = Mathf.Min(_mp, _maxhp); _maxmp += value; break; case eStat.Damage: _plusdamage += value; _damage += value; break; case eStat.Defense: _plusdefense += value; _defense += value; break; } } public void BuffEvent(eStat type, float value) { switch (type) { case eStat.HP: _hp = Mathf.Min(_hp + value, _maxhp); break; case eStat.MP: _mp = Mathf.Min(_mp + value, _maxhp); break; } } public override bool GetHit(BaseStat attacker) { return base.GetHit(attacker); } }
package com.rental.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.rental.entites.UserDtls; import com.rental.service.Email; import com.rental.service.UserService; @RestController @RequestMapping("/api/auth") public class UserController { @Autowired private UserService userService; @Autowired private Email email; @PostMapping("/register") public ResponseEntity<?> createUser(@RequestBody UserDtls user) { if (userService.checkEmail(user.getEmail())) { return new ResponseEntity<>("Email id already Exist", HttpStatus.CONFLICT); } else { email.simpleEmail(user.getEmail(), "Welcome to Aashiyana", "Thank you for registering with us" + "For futher details you can reach us" + "@[email protected]"); return new ResponseEntity<>(userService.createUser(user), HttpStatus.CREATED); } } @PostMapping("/login") public ResponseEntity<?> login(@RequestBody UserDtls userDtls) { return new ResponseEntity<>(userService.signInWithUserReturnJwt(userDtls), HttpStatus.OK); } @GetMapping("/forgotPassword/{em}/{no}") public ResponseEntity<?> checkEmailAndMob(@PathVariable String em, @PathVariable String no) { return new ResponseEntity<>(userService.checkEmailAndMob(em, no), HttpStatus.OK); } @PostMapping("/updatePassword") public ResponseEntity<?> updatePassword(@RequestBody UserDtls user) { return new ResponseEntity<>(userService.resetPassword(user), HttpStatus.OK); } }
import React, { useContext, useEffect, useRef, useState } from 'react' import NoteContext from '../Context/Note/NoteContext' import { toast } from 'react-toastify'; import Home from './Home'; import Spinner from './Spinner'; const Notes = () => { const ref = useRef(null) const closeRef = useRef(null) const context = useContext(NoteContext); const { notes, setNotes, fetchallnotes, deletenote, editnote } = context; const [loading, setLoading] = useState(true); const [noteInfo, setNoteInfo] = useState({ title: '', description: '', tag: '', id: '' }); const handleDelete = async (id) => { const promise = deletenote(id); toast.promise(promise, { pending: 'Deleting Note...', success: 'Note Deleted Successfully', error: 'Failed to Delete Note', }); try { const json = await promise; if (json.success) { const newNotes = notes.filter((note) => note._id !== id); setNotes(newNotes); } } catch (error) { // Errors are already handled by toast.promise } }; const handleEditClick = (note) => { setNoteInfo({ title: note.title, description: note.description, tag: note.tag, id: note._id }); ref.current.click(); }; const handleSaveChanges = async() => { const promise = editnote(noteInfo.title, noteInfo.description, noteInfo.tag, noteInfo.id); closeRef.current.click(); toast.promise(promise, { pending: 'Updating Note...', success: 'Note Updated Successfully', error: 'Failed to Update Note', }); }; useEffect(() => { const fetchData = async () => { try { await fetchallnotes(); setLoading(false); // Set loading to false after fetching notes } catch (error) { toast.error('Error fetching notes.'); } }; fetchData(); }, []); return ( <> <Home /> <button type="button" ref={ref} className="btn btn-primary d-none" data-bs-toggle="modal" data-bs-target="#exampleModal"></button> <div className="modal fade" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h1 className="modal-title fs-5" id="exampleModalLabel">Edit Note</h1> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <div className="container"> <form className='my-4 mx-4'> <div className="mb-1"> <label htmlFor="input1" className="form-label">Title</label> <input type="text" value={noteInfo.title} onChange={(e) => setNoteInfo({ ...noteInfo, title: e.target.value })} className="form-control" id="input1" name='title' /> </div> <div className="mb-1"> <label htmlFor="input2" className="form-label">Note</label> <input type="text" value={noteInfo.description} onChange={(e) => setNoteInfo({ ...noteInfo, description: e.target.value })} className="form-control" name='description' id="input2" /> </div> <div className="mb-1"> <label htmlFor="input3" className="form-label">Set Tag</label> <input type="text" value={noteInfo.tag} onChange={(e) => setNoteInfo({ ...noteInfo, tag: e.target.value })} className="form-control" id="input3" name='tag' /> </div> </form> </div> </div> <div className="modal-footer"> <button ref={closeRef} type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" style={{background: '#f5ba13'}} className="btn text-white" onClick={handleSaveChanges}>Save changes</button> </div> </div> </div> </div> {loading ? ( <div className="con min-vh-100" style={{ textAlign: 'center' }}> <Spinner /> </div> ) : (<div className="container mt-5 justify-content-center min-vh-100"> <div className="row"> {notes.map((note) => ( <div className="col-md-4" key={note._id}> <div className="card mb-3"> <div className="card-header"> {note.title} <span className="float-end"> <i className="fas fa-edit me-2 text-white bg-warning rounded-circle p-2" data-toggle="tooltip" data-placement="top" title="Edit Note" onClick={() => { handleEditClick(note) }} ></i> <i className="fas fa-trash text-white bg-warning rounded-circle p-2" data-toggle="tooltip" data-placement="top" title="Delete Note" onClick={() => { handleDelete(note._id) }} ></i> </span> </div> <div className="card-body"> <p className="card-text">{note.description}</p> </div> </div> </div> ))} </div> </div> )} </> ) } export default Notes;
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Fundamentals { public class GameInfoParser { public GameInfoParser() { } /// <summary> /// Returns the total number of games present in the GameInfo object. /// </summary> /// <returns></returns> public int TotalNumberOfGames(GameInfo games) { return games.MetaData.Count; } /// <summary> /// Determines and returns the most frequent game genre in the GameInfo. /// </summary> /// <returns></returns> public string MostFrequentGenre(GameInfo games) { Dictionary<string, int> genres = new Dictionary<string, int>(); foreach (var game in games.MetaData) { if (genres.ContainsKey(game.Genre)) { genres[game.Genre]++; } else { genres.Add(game.Genre, 0); } } string MostFreqGenre = genres.OrderByDescending(x => x.Value).ToList().FirstOrDefault().Key; return MostFreqGenre; } /// <summary> /// Determines the maps with the longest names excluding whitespace with the game that they belong to. /// </summary> /// <returns></returns> public Dictionary<string, string> MapsWithLongestNames(GameInfo games) { List<string> mapNames = new List<string>(); Dictionary<string, string> LongestMapsWithGame = new Dictionary<string, string>(); foreach (var game in games.MetaData) { mapNames.AddRange(game.MapNames.ToList()); } //sort by length mapNames = mapNames.OrderByDescending(x => Utility.RemoveWhiteSpace(x).Length).ToList(); //find all maps that match the largest element length and print them with the game name foreach (var map in mapNames) { if (Utility.RemoveWhiteSpace(map).Length == Utility.RemoveWhiteSpace(mapNames.First()).Length) { var gameMapIsFrom = games.MetaData.Where(x => x.MapNames.Contains(map)).ToList().First().Name; LongestMapsWithGame.Add(map, gameMapIsFrom); } } return LongestMapsWithGame; } /// <summary> /// Outputs to the screen all game info to the user. /// </summary> public void DisplayAllInfo(GameInfo games) { Dictionary<int, Info> Games = new Dictionary<int, Info>(); foreach (Info info in games.MetaData) { Games.Add(info.Id, info); } //simply loop through each element of the dictionary and print foreach (var game in Games) { Console.WriteLine($"ID: {game.Value.Id}"); Console.WriteLine($" - Name: {game.Value.Name}"); Console.WriteLine($" - Genre: {game.Value.Genre}"); Console.Write(" - Maps: "); foreach (var map in game.Value.MapNames) { Console.Write($"{map}, "); if (map != game.Value.MapNames.LastOrDefault()) { Console.Write(", "); } else { Console.Write("\n"); } } } } /// <summary> /// Method that returns a list of all maps that have the contain the inputted sequence. /// </summary> /// <param name="gameInfo">GameInfo object to be parsed.</param> /// <param name="sequence">String sequence the method is looking for.</param> /// <returns></returns> public List<string> GetAllContainingSequence(GameInfo gameInfo, string sequence) { List<string> maps = new List<string>(); foreach (var game in gameInfo.MetaData) { foreach (var map in game.MapNames) { //turn map name to upper and check for uppercase "Z", so you can check for z once and get both caes of uppercase and lowercase if (map.ToUpper().Contains("Z")) { maps.Add(map); } } } return maps; } } }
import prisma from "../src/prisma" import CryptoJS from "crypto-js" import { LoginDto, UserHandler } from "../src/handler/user.handler" import { AppContext } from "../src/type/common" const passwd = CryptoJS.MD5("passwd").toString() beforeAll(async () => { await prisma.user.deleteMany() await prisma.user.create({ data: { name: 'amen', passwd } }) }) test('only amen can login', async () => { const dto = <LoginDto>{ name: 'amen', passwd } const ctx = <AppContext>{ prisma, request: { body: dto }, body: {} as any } await UserHandler.login(ctx) expect(ctx.body).toBeTruthy() }) test('amen with bad passwd cannot login', async () => { const dto = <LoginDto>{ name: 'amen', passwd: CryptoJS.MD5('wrong passwd').toString() } const ctx = <AppContext>{ prisma, request: { body: dto }, body: {} as any } await UserHandler.login(ctx) expect(ctx.body).toBeFalsy() }) test('other user cannot login', async () => { const dto = <LoginDto>{ name: 'koalayt', passwd } const ctx = <AppContext>{ prisma, request: { body: dto }, body: {} as any } await UserHandler.login(ctx) expect(ctx.body).toBeFalsy() })
import Image from "next/image"; import Link from "next/link"; import { auth } from "@/app/auth"; import { redirect } from "next/navigation"; import Counter from "./components/counter"; export default async function Home() { const session = await auth(); // show login button if not logged in (Should be returning a separate component) if (!session) { return ( <main className="flex min-h-screen flex-col items-center justify-start p-24"> <Link href="/api/auth/signin" className="border-white rounded-md px-3 py-2 bg-slate-900 text-lg" > Sign in </Link> </main> ); } // can also use redirect /* if (!session) { redirect("/api/auth/signin?callbackUrl=/"); } */ return ( <main className="flex min-h-screen flex-col items-center justify-start p-24"> {session.user?.image && ( <Image src={session.user.image} width={200} height={200} alt="user image" /> )} <Counter /> <Link href="/api/auth/signout" className="border-white rounded-md px-3 py-2 bg-slate-900 text-lg" > Sign out </Link> </main> ); }
import 'package:chart_sparkline/chart_sparkline.dart'; import 'package:coin/model/coin_model.dart'; import 'package:coin/provider/getchart_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:http/http.dart' as http; import 'package:lottie/lottie.dart'; import 'package:persian_number_utility/src/extensions.dart'; import 'package:provider/provider.dart'; import 'package:provider/src/provider.dart'; import 'coin_select.dart'; class Chart extends StatefulWidget { const Chart({Key? key}) : super(key: key); @override _ChartState createState() => _ChartState(); } class _ChartState extends State<Chart> { @override void initState() { super.initState(); getcoinMarketLoop(); } bool _isRefreshing = true; getcoinMarketLoop() async { while (true) { await Future.delayed(const Duration(seconds: 5)); context.read<ChartGet>().fetchData; } } List<Color> redColor = [ Colors.red.withOpacity(0.3), Colors.red.withOpacity(0), ]; List<Color> greenColor = [ Colors.green.withOpacity(0.3), Colors.green.withOpacity(0), ]; List<Color> greyColor = [ Colors.grey.withOpacity(0.3), Colors.grey.withOpacity(0), ]; @override Widget build(BuildContext context) { double myHeight = MediaQuery.of(context).size.height; double myWidth = MediaQuery.of(context).size.width; context.read<ChartGet>().fetchData; return Scaffold( body: SafeArea( child: Container( height: myHeight, width: myWidth, child: Column( children: [ Container( height: myHeight * 0.07, child: Center( child: Padding( padding: const EdgeInsets.symmetric( vertical: 12.0, horizontal: 15.0), child: Row( children: const [ Text( "رمز ارزها", style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold), ), SizedBox( width: 25.0, ), Text( "صرافی ها", style: TextStyle(color: Colors.blueGrey), ), ], ), ), ), ), Expanded( child: Consumer<ChartGet>( builder: (context, value, child) { return value.map.length == 0 && !value.error ? Center( child: Lottie.asset("assets/animation/loading.json", height: 40.0), ) : value.error ? Text(value.errorMessage.toString()) : AnimationLimiter( child: ListView.builder( itemCount: value.map.length, itemBuilder: (context, index) { var y = value.map[index].sparklineIn7D!.price!; var x = y .getRange(y.length - 30, y.length) .toList(); return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 375), child: SlideAnimation( verticalOffset: 50.0, child: FadeInAnimation( child: Column( children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 15.0, vertical: 5.0), child: GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => CoinSelect( changePrice: value .map[index] .marketCapChangePercentage24H!, price: value .map[index] .currentPrice, id: value .map[index].id .toString()), )); }, child: Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ Column( children: [ value.map[index] .currentPrice != null ? Text( r'$ ' + value.map[index].currentPrice.toString().toPersianDigit().seRagham(), style: const TextStyle( fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.black, ), ) : const Text( "تعیین نشده") ], ), Container( height: myHeight * 0.07, width: myWidth * 0.2, child: Sparkline( data: x, lineWidth: 1.5, fillGradient: LinearGradient( begin: Alignment .topCenter, end: Alignment .bottomCenter, stops: const [ 0.0, 0.7 ], colors: value .map[index] .marketCapChangePercentage24H != null ? value.map[index].marketCapChangePercentage24H! <= 0 ? redColor : greenColor : greyColor, ), fillMode: FillMode .below, useCubicSmoothing: true, cubicSmoothingFactor: 0.4, enableThreshold: true, lineColor: value .map[ index] .marketCapChangePercentage24H != null ? value.map[index].marketCapChangePercentage24H! <= 0 ? Colors .red : Colors .green : Colors .grey, ), ), ], ), ), ShowOne( value.map[index] .image != null ? value.map[index] .image! : "", value.map[index].name != null ? value.map[index] .name! : "", value.map[index] .symbol != null ? value.map[index] .symbol! : "", value.map[index] .marketCapRank != null ? value.map[index] .marketCapRank! : 0, value.map[index] .marketCapChangePercentage24H != null ? value.map[index] .marketCapChangePercentage24H! : 0, value.map[index] .marketCapChangePercentage24H != null ? value.map[index] .marketCapChangePercentage24H! <= 0 ? Icons .arrow_drop_down_rounded : Icons .arrow_drop_up_rounded : Icons .minimize_sharp, value.map[index] .marketCapChangePercentage24H != null ? value.map[index] .marketCapChangePercentage24H! <= 0 ? Colors.red : Colors.green : Colors.grey, ), ], ), ), ), const Divider( indent: 10, endIndent: 10), ], ), ), ), ); }, ), ); }, ), ) ], ), ), ), ); } Widget ShowOne(String image, String name, String symble, int rank, double darsad, IconData icon, Color color) { double myHeight = MediaQuery.of(context).size.height; double myWidth = MediaQuery.of(context).size.width; return Container( width: myWidth * 0.47, child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( name, style: const TextStyle( fontSize: 13.0, fontWeight: FontWeight.bold), ), Row( children: [ // const Spacer(), Text( " % " + darsad.toStringAsFixed(2).toPersianDigit(), style: const TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.blueGrey, ), ), Icon( icon, color: color, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: Text( symble, style: const TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.blueGrey, ), ), ), Container( decoration: BoxDecoration( color: Colors.grey.withOpacity(0.2), borderRadius: BorderRadius.circular(5)), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: Text( rank.toString(), style: const TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.blueGrey, ), ), ), ), ], ), ], ), const SizedBox(width: 10.0), Container( height: myHeight * 0.04, width: myWidth * 0.08, decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: Colors.grey.withOpacity(0.2)), image: DecorationImage( fit: BoxFit.fill, image: NetworkImage(image))), ), ], ), ); } List? coinMarket = []; List? chartLast = []; var coinMarketList; Future<List<CoinMarket>?> getcoinMarket() async { List<CoinMarket>? himan = []; // const infourl = 'http://128.65.186.187:1989/api/boperation'; const infourl = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=true'; setState(() { _isRefreshing = true; }); var response = await http.get(Uri.parse(infourl), headers: { "Content-Type": "application/json", "Accept": "application/json", }); setState(() { _isRefreshing = false; }); if (response.statusCode == 200) { // var x = json.decode(response.body); var x = response.body; // coinMarketList = x.map((e) => CoinMarket.fromJson(e)).toList(); coinMarketList = coinMarketFromJson(x); setState(() { coinMarket = coinMarketList; }); } } }
class MainController < ApplicationController # Initialize an empty array to store chat messages as a class variable. cattr_accessor :chat_history self.chat_history = [] def index # Read chat history from the file and store it in memory. @chat_history = read_chat_history end def save content = params[:content] # Read the existing chat history from the file existing_chat_history = read_chat_history # Append the new message to the existing chat history with a newline character updated_chat_history = "#{existing_chat_history}\n#{content}" # Save the updated chat history back to the file write_chat_history(updated_chat_history) # Update the chat_history variable for the view self.chat_history = updated_chat_history redirect_to main_index_path end def erase_history # Clear the chat history in memory and save an empty string to the file. self.chat_history = '' write_chat_history('') redirect_to main_index_path, notice: "Chat history has been erased." end def trigger_texting_task ScriptRunner.run redirect_to main_index_path, notice: "Texting task triggered." end private def read_chat_history if File.exist?('yourfile.txt') File.read('yourfile.txt') else '' end end def write_chat_history(content) File.write('yourfile.txt', content) end end
import React, {useState} from 'react'; import { LightModeOutlined, DarkModeOutlined, Menu as MenuIcon, Search, SettingsOutlined, ArrowDropDownOutlined } from '@mui/icons-material'; import FlexBetween from 'components/FlexBetween'; import { useDispatch } from "react-redux"; import { setMode } from "state"; import profileImage from "assets/profile.jpg"; import { AppBar, useTheme, Toolbar, IconButton, Button, Box, Typography, InputBase, Menu, MenuItem} from '@mui/material'; const Navbar = ({ user, isSidebarOpen, setIsSidebarOpen, }) => { const dispatch=useDispatch(); const theme=useTheme(); const [anchorEl, setAnchorEl]=useState(null); const isOpen=Boolean(anchorEl); const handleClick=(event)=> setAnchorEl(event.currentTarget); const handleClose=()=> setAnchorEl(null); return ( <AppBar sx={{ position:"static", background:"none", boxShadow:"none", }} > <Toolbar width="100%" sx={{ justifyContent:"space-between"}}> { /*LEFT SIDE */ } <FlexBetween> <IconButton onClick={() => setIsSidebarOpen(!isSidebarOpen)}> <MenuIcon /> </IconButton> <FlexBetween backgroundColor= {theme.palette.background.alt} borderRadius="9px" gap="3rem" p="0.1rem 1.5rem"> <InputBase placeholder="Search..." /> <IconButton> <Search /> </IconButton> </FlexBetween> </FlexBetween> {/* RIGHT SIDE */} <FlexBetween gap="1.5rem"> <IconButton onClick={() => dispatch(setMode())}> {theme.palette.mode==='dark' ? ( <DarkModeOutlined sx={{ fontSize:"25px"}} /> ):( <LightModeOutlined sx={{ fontSize:"25px"}} /> //this is the size of the icon )} </IconButton> <IconButton> <SettingsOutlined sx={{ fontSize:"25px"}} /> </IconButton> <FlexBetween> <Button onClick={handleClick} sx={{ display:"flex", justifyContent:"space-between", alignItems:"center", textTransform:"none", gap:"1rem" , }} > <Box component="img" alt="profile" src={profileImage} height="32px" width="32px" borderRadius="50%" sx={{ objectFit: "cover" }} /> <Box textAlign="left"> <Typography fontWeight="bold" fontSize="0.85rem" sx={{ color: theme.palette.secondary[100] }} > {user.name} </Typography> <Typography fontSize="0.75rem" sx={{ color: theme.palette.secondary[200] }} > {user.occupation} </Typography> </Box> <ArrowDropDownOutlined sx={{ color:theme.palette.secondary[300], fontSize:"25px"}} /> </Button> <Menu anchorEl={anchorEl} open={isOpen} onClose={handleClose} anchorOrigin={{vertical:"bottom", horizontal:"center"}}> <MenuItem onClick={handleClose}>Log Out</MenuItem> </Menu> </FlexBetween> </FlexBetween> </Toolbar> </AppBar> ); }; export default Navbar
import { Component, Output, EventEmitter } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Question } from 'src/app/types'; @Component({ selector: 'app-question-create', templateUrl: './question-create.component.html', styleUrls: ['./question-create.component.scss'], }) export class QuestionCreateComponent { @Output() questionCreated: EventEmitter<Question> = new EventEmitter(); form: FormGroup; constructor(private fb: FormBuilder) { this.initForm(); } initForm() { this.form = this.fb.group({ questionText: this.fb.control('', [Validators.required]), op0: this.fb.control('', [Validators.required]), op1: this.fb.control('', [Validators.required]), op2: this.fb.control('', [Validators.required]), op3: this.fb.control('', [Validators.required]), answer: this.fb.control('', [Validators.required]), }); } submit() { try { const question: Question = { text: this.form.get('questionText').value, options: [ this.form.get('op0').value, this.form.get('op1').value, this.form.get('op2').value, this.form.get('op3').value, ], answer: Number(this.form.get('answer').value), }; if (new Set(question.options).size !== question.options.length) { alert('Repetetive Options'); return; } this.initForm(); this.questionCreated.emit(question); } catch (e) { console.log('Error: ', e); } } }
import json from boto3 import Session from langchain.memory import DynamoDBChatMessageHistory from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain from langchain.prompts import PromptTemplate from langchain.llms.base import LLM from callback import StreamingAPIGatewayWebSocketCallbackHandler def chat( event: dict, llm: LLM, boto3_session: Session, session_table_name: str, ai_prefix: str, prompt: PromptTemplate, ): # print(json.dumps(event)) # parse event domain = event["requestContext"]["domainName"] stage = event["requestContext"]["stage"] connection_id = event["requestContext"]["connectionId"] body = event["body"] # set callback handler # so that every time the model generates a chunk of response, # it is sent to the client callback = StreamingAPIGatewayWebSocketCallbackHandler( boto3_session, # see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html f"https://{domain}/{stage}", connection_id, on_token=lambda t: json.dumps( {"kind": "token", "chunk": t}, ensure_ascii=False, ), on_end=lambda: json.dumps({"kind": "end"}), on_err=lambda e: json.dumps({"kind": "error"}), ) llm.callbacks = [callback] history = DynamoDBChatMessageHistory( table_name=session_table_name, # use connection_id as session_id for simplicity. # in production, you should design the session_id yourself session_id=connection_id, boto3_session=boto3_session, ) memory = ConversationBufferMemory(ai_prefix=ai_prefix, chat_memory=history) conversation = ConversationChain(llm=llm, memory=memory) conversation.prompt = prompt conversation.predict(input=body["input"])
import 'package:edtech_app/authentication/auth_services.dart'; import 'package:edtech_app/authentication/signin_page_screen.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; class SignupPageScreen extends StatefulWidget { const SignupPageScreen({Key? key}) : super(key: key); @override State<SignupPageScreen> createState() => _SignupPageScreenState(); } class _SignupPageScreenState extends State<SignupPageScreen> { TextEditingController nameController = TextEditingController(); TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController confirmPasswordController = TextEditingController(); bool obsecureText = true; void signUp() async{ final authServices = Provider.of<AuthServices>(context, listen: false); try{ authServices.signUpWithEmailAndPassword( emailController.text.toString(), passwordController.text.toString() ).then((value) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Successfully Created your account"))); Navigator.of(context).push(MaterialPageRoute(builder: (context) => SigninPageScreen())); }).onError((error, stackTrace) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error.toString()))); }); }catch(e){ print(e.toString()); ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString()))); } } @override Widget build(BuildContext context) { var height = MediaQuery.of(context).size.height; var width = MediaQuery.of(context).size.width; return Scaffold( body: Container( height: double.infinity, width: double.infinity, padding: EdgeInsets.only( left: 20, right: 20, ), decoration: BoxDecoration( color: Colors.grey[300], ), child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: height * 0.1,), Stack( children: [ Container( height: 250, width: 250, decoration: BoxDecoration( shape: BoxShape.circle, //image: DecorationImage(image: AssetImage("images/w1.png"),fit: BoxFit.cover) color: Color(0xff4AA4D6) ), ), Positioned( top: 85, right: 70, child: Text("Sign up", style: GoogleFonts.ephesis( fontSize: 50, color: Colors.black, fontWeight: FontWeight.bold, ), ) ) ], ), SizedBox(height: height * 0.05,), TextFormField( controller: nameController, decoration: InputDecoration( labelText: "Name", hintText: "mr. sohel tanvir", prefixIcon: Icon(Icons.person, color: Color(0xff4AA4D6),), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), ), ), SizedBox(height: height * 0.015,), TextFormField( controller: emailController, decoration: InputDecoration( labelText: "Email", hintText: "[email protected]", prefixIcon: Icon(Icons.alternate_email, color: Color(0xff4AA4D6),), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), ), ), SizedBox(height: height * 0.015,), TextFormField( controller: passwordController, obscureText: obsecureText, decoration: InputDecoration( labelText: "Password", hintText: "***************", prefixIcon: Icon(Icons.lock_open_outlined, color: Color(0xff4AA4D6),), suffixIcon: IconButton( onPressed: (){ setState(() { obsecureText = !obsecureText; }); }, icon: Icon(obsecureText == true ? Icons.visibility_off : Icons.visibility) ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), ), ), SizedBox(height: height * 0.015,), TextFormField( controller: confirmPasswordController, obscureText: obsecureText, decoration: InputDecoration( labelText: "Confirm Password", hintText: "***************", prefixIcon: Icon(Icons.lock_open_outlined, color: Color(0xff4AA4D6),), suffixIcon: IconButton( onPressed: (){ setState(() { obsecureText = !obsecureText; }); }, icon: Icon(obsecureText == true ? Icons.visibility_off : Icons.visibility) ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Color(0xff4AA4D6), width: 3, ), ), ), ), SizedBox(height: height * 0.03,), InkWell( onTap: (){ signUp(); }, child: Container( height: 55, width: 250, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Color(0xff4AA4D6), ), child: Center( child: Text("Sign up", style: TextStyle( fontWeight: FontWeight.w900, color: Colors.black, fontSize: 18, letterSpacing: 1, ), ) ) , ) ), SizedBox(height: height * 0.05,), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Already have an account?", style: TextStyle( color: Color(0xff000000), fontWeight: FontWeight.w500, fontSize: 15, ), ), SizedBox(width: width * 0.02,), InkWell( onTap: (){ Navigator.of(context).push(MaterialPageRoute(builder: (context) => SigninPageScreen())); }, child: Text("Sign in", style: TextStyle( color: Color(0xff4AA4D6), fontWeight: FontWeight.bold, fontSize: 16, ), ), ), ], ), // SizedBox(height: height * 0.01,), // // Row( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Text("Forget password?", // style: TextStyle( // color: Color(0xff000000), // fontWeight: FontWeight.w500, // fontSize: 15, // ), // ), // // SizedBox(width: width * 0.02,), // // InkWell( // onTap: (){ // // }, // child: Text("Reset Password", // style: TextStyle( // color: Color(0xff4AA4D6), // fontWeight: FontWeight.bold, // fontSize: 16, // ), // ), // ), // // // ], // ), ], ), ), ), ); } }
const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const scoresPerBinColor = { green: { paper: -5, glass: 10, organic: -5, nonRecyclableWaste: -5, plastic: -5 }, blue: { paper: 10, glass: -5, organic: -5, nonRecyclableWaste: -5, plastic: -5 }, red: { paper: -5, glass: -5, organic: 10, nonRecyclableWaste: -5, plastic: -5 }, yellow: { paper: -5, glass: -5, organic: -5, nonRecyclableWaste: -5, plastic: 10 }, black: { paper: -5, glass: -5, organic: -5, nonRecyclableWaste: 10, plastic: -5 }, } console.log(scoresPerBinColor.blue.plastic) // console.log(scoresPerBinColor[currentBinColor][thingICollidedWith.type]) let recycleBinImage, redBinImage, blackBinImage, yellowBinImage, greenBinImage, blueBinImage; let bottleImage, paperImage, plasticImage, trashImage; let recycleBin, currentItem; let score=0; function selectRandomBin() { const bins = [redBinImage, blackBinImage, yellowBinImage, greenBinImage, blueBinImage]; const colors = ["red", "black", "yellow", "green", "blue"]; const randomIndex = Math.floor(Math.random() * bins.length); recycleBin.color=colors[randomIndex]; recycleBinImage = bins[randomIndex]; } function drawRecycleBin() { ctx.drawImage(recycleBinImage, recycleBin.x, recycleBin.y, recycleBin.width, recycleBin.height); } function drawItem(item) { if (item) { let image; switch (item.type) { case 'paper': image = paperImage; break; case 'plastic': image = plasticImage; break; case 'nonRecyclableWaste': image = trashImage; break; case 'organic': image = organicImage; break; case 'glass': default: image = bottleImage; break; } ctx.drawImage(image, item.x, item.y, item.width, item.height); } } function drawScore() { ctx.fillStyle = 'black'; ctx.font = '24px Arial'; ctx.fillText('Score: ' + score, 10, 30); } function updateGame() {//this is the game tick// let speedIncrease = 1; if (!currentItem) { const items = ['glass', 'paper', 'plastic', 'nonRecyclableWaste', 'organic']; let itemType = items[Math.floor(Math.random() * items.length)]; currentItem = { x: Math.random() * (canvas.width - 50), y: 0, width: 90, height: 90, type: itemType }; } else { currentItem.y += 5 * speedIncrease; if ( currentItem.x < recycleBin.x + recycleBin.width && currentItem.x + currentItem.width > recycleBin.x && currentItem.y < recycleBin.y + recycleBin.height && currentItem.y + currentItem.height > recycleBin.y ) { score += scoresPerBinColor[recycleBin.color][currentItem.type]; console.log(JSON.stringify({ currentBinColor: recycleBin.color, scoresForThisColor: scoresPerBinColor[recycleBin.color], currentItemType: currentItem.type, calculatedScore: `${score} (${scoresPerBinColor[recycleBin.color][currentItem.type]})` })) currentItem = null; } if (currentItem && currentItem.y > canvas.height) { currentItem = null; } } ctx.clearRect(0, 0, canvas.width, canvas.height); drawRecycleBin(); drawItem(currentItem); drawScore(); requestAnimationFrame(updateGame); } function initializeGame() { // Initialize bin images redBinImage = new Image(); redBinImage.src = "./assets/images/red-bin.png"; blackBinImage = new Image(); blackBinImage.src = "./assets/images/black-bin.png"; yellowBinImage = new Image(); yellowBinImage.src = "./assets/images/yellow-bin.png"; greenBinImage = new Image(); greenBinImage.src = "./assets/images/green-bin.png"; blueBinImage = new Image(); blueBinImage.src = "./assets/images/blue-bin.png"; // Initialize other images bottleImage = new Image(); bottleImage.src = "./assets/images/bottle.png"; paperImage = new Image(); paperImage.src = "./assets/images/paper.png"; plasticImage = new Image(); plasticImage.src = "./assets/images/plastic.png"; trashImage = new Image(); trashImage.src = "./assets/images/diaper.png"; organicImage = new Image(); organicImage.src = "./assets/images/banana.png"; // Initialize game state recycleBin = { color:"blue", x: canvas.width / 2 - 75, y: canvas.height - 150, width: 150, height: 150, }; currentItem = null; score = 0; selectRandomBin(); updateGame(); } function resetGame() { location.reload(); } function onCanvasMouseMove(event) { const canvasRect = canvas.getBoundingClientRect(); const mouseX = event.clientX - canvasRect.left; const binHalfWidth = recycleBin.width / 2; recycleBin.x = Math.min(Math.max(mouseX - binHalfWidth, 0), canvas.width - recycleBin.width); } canvas.addEventListener('mousemove', onCanvasMouseMove); function startGame() { document.getElementById('gameSection').style.display = 'block'; } function endGame() { document.getElementById('gameSection').style.display = 'none'; document.getElementById('endSection').style.display = 'block'; document.getElementById('finalScore').textContent = score.toString(); } function restartGame() { document.getElementById('endSection').style.display = 'none'; document.getElementById('welcomeSection').style.display = 'block'; score = 0; resetGame(); } // Initialize the game initializeGame(); const binSwitchHandler = (event) => { if (event.key === "a") { recycleBin.color = "red"; recycleBinImage = redBinImage; } else if (event.key === "s") { recycleBin.color = "green"; recycleBinImage = greenBinImage; } else if (event.key === "d") { recycleBin.color = "blue"; recycleBinImage = blueBinImage; } else if (event.key === "f") { recycleBin.color = "yellow"; recycleBinImage = yellowBinImage; } else if (event.code === "Space") { recycleBin.color = "black"; recycleBinImage = blackBinImage; } }; document.addEventListener("keydown", binSwitchHandler);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Portfolio</title> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="media.css" /> <script src="https://kit.fontawesome.com/b0301dbb6a.js" crossorigin="anonymous"></script> </head> <body> <nav> <div class="navbar"> <div class="div-logo"> <img class="logo" src="./Anishrbg.png" /> </div> <div id="navToggle" class="nav-elements"> <a class="a" href="#">HOME</a> <a class="a" href="#About">ABOUT</a> <a class="a" href="#portfolio">PORTFOLIO</a> <a class="a" href="#contact">CONTACT</a> <span class="darkMode"> <i id="mode" class="fa-solid fa-circle-half-stroke fa-lg"></i> </span> </div> <i id="menuBAR" class="fa-solid fa-bars"></i> </div> </nav> <header id="header"> <div class="header"> <div class="intro"> <h1>Hi, I'm Anish Kushwaha</h1> <h2>Software Developer</h2> <p> Passionate 3rd-year Computer Science student specializing in HTML, CSS, JavaScript, and C, eager to apply theoretical knowledge to real-world software development. </p> <div class="btn"> <button class="hireMe"><a href="mailto:[email protected]">Hire Me</a></button> <button class="CV"><a href="./CV_.pdf" download="resume">Download CV</a></button> </div> </div> <div class="photo"> <img class="me" src="./me.png"/> </div> </div> </header> <section id="About"> <div class="section1"> <div class="about"> <h2>ABOUT ME</h2> <p> Enthusiastic and forward-thinking Computer Science student entering the final year of my BTech program. I have a strong foundation in HTML, CSS, and JavaScript, complemented by a solid understanding of the C language. Eager to contribute my skills and knowledge to the dynamic field of software development. Currently seeking internship opportunities to apply classroom learning to real-world projects and enhance my proficiency in creating robust and innovative solutions. Passionate about continuous learning, collaboration, and staying abreast of the latest industry trends. </p> <p> Keenly interested in front-end development, user experience design, and exploring the intersection of technology and creativity. Actively participating in coding competitions and hackathons to further refine problem-solving skills. </p> <p> Seeking opportunities to contribute to innovative projects, expand my technical skill set, and engage with a community of like-minded professionals. Open to networking and mentorship to accelerate my growth as a software developer. </p> </div> </div> </section> <section> <h2 class="sh">SKILLS</h2> <div class="skills"> <div class="cards"> <div class="card"> <img src="./logo/html-5.png" /> <span>HTML</span> </div> <div class="card"> <img src="./logo/css-3.png" /> <span>CSS</span> </div> <div class="card"> <img src="./logo/js.png" /> <span>JavaScript</span> </div> <div class="card"> <img src="./logo/node-js.png" /> <span>Node.js</span> </div> <div class="card"> <img class="l" src="./logo/mysql.png" /> <span>MySQL</span> </div> <div class="card"> <img src="./logo/python.png" /> <span>Python</span> </div> <div class="card"> <img src="./logo/letter-c.png" /> <span>C</span> </div> <div class="card"> <img src="./logo/java.png" /> <span>JAVA</span> </div> <div class="card"> <img src="./logo/hierarchical.png" /> <span>Data Structure</span> </div> </div> </div> </section> <section id="portfolio"> <div class="sect"> <h2>PORTFOLIO</h2> <div class="portfolio"> <div class="card1"> <img src="./projectIcon/13286.jpg" /> <h4>Age Calculator</h4> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/AgeCalc/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/AgeCalc">See Code</a> </div> <div class="card1"> <h4>Weather App</h4> <img src="./projectIcon/2110.i201.025.F.m004.c9.meteorology weather forecast isometric.jpg" /> <a class="hireMe" href="https://anish2944.github.io/WeatherApp/weatherApp/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WeatherApp/tree/master/weatherApp">See Code</a> </div> <div class="card1"> <h4>Task List</h4> <img src="./projectIcon/2867045.jpg" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/TaskList/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/TaskList">See Code</a> </div> <div class="card1"> <h4>Joke Generator</h4> <img src="./projectIcon/33366.jpg" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/joke%20web/joke.html">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/joke%20web">See Code</a> </div> <div class="card1"> <h4>Digital Clock</h4> <img src="./projectIcon/35136.jpg" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/digiClock/digiclock.html">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/digiClock">See Code</a> </div> <div class="card1"> <h4>English Dictionary</h4> <img src="./projectIcon/8813354.jpg" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/EngDictionary/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/EngDictionary">See Code</a> </div> <div class="card1"> <h4>CLONE</h4> <img class="hub" src="./projectIcon/asset 1.png" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/UsabiltyHubCLONE/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/UsabiltyHubCLONE">See Code</a> </div> <div class="card1"> <h4>Anime Generator</h4> <img src="./projectIcon/anime.webp" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/Anime/anime.html">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/Anime">See Code</a> </div> <div class="card1"> <h4>Abstract CLONE</h4> <img class="hub" src="./projectIcon/Screenshot 2023-11-15 172451.png" /> <a class="hireMe" href="https://anish2944.github.io/WebApps/Web/abstract-Demo/">Test Me</a> <a class="CV" href="https://github.com/Anish2944/WebApps/tree/main/Web/abstract-Demo">See Code</a> </div> <div class="special-item"> <div class="btnCon"> <button id="seeMore" class="hireMe">See More</button> </div> </div> </div> </div> </section> <section> <h2 class="q">Qualifications</h2> <div class="edu"> <table> <tr> <th>Degree</th> <th>Institution</th> <th>Year</th> <!-- <th>Marks</th> --> </tr> <tr> <td>High School</td> <td>Lucknow Public School</td> <td>2018</td> <!-- <td>%</td> --> </tr> <tr> <td>Intermediate</td> <td>Lucknow Public School</td> <td>2020</td> <!-- <td>74%</td> --> </tr> <tr> <td>Bachelor's Degree</td> <td>Babu Banarasi Das University</td> <td>2025</td> <!-- <td>9 CGPA</td> --> </tr> </table> </div> </section> <footer id="contact"> <h2>Contact Me:-</h2> <div class="contact"> <div class="contact-container"> <form name="submit-to-google-sheet" class="contact-form"> <label for="name">Name:</label> <input type="text" id="name" placeholder="Enter Your Name" name="Name" required /> <label for="email">Email:</label> <input type="email" id="email" placeholder="Enter Your E-mail" name="Email" required /> <label for="message">Message:</label> <textarea id="message" placeholder="Write Your Message" name="Message" rows="4" required></textarea> <button type="submit">Send Message</button> </form> <span id="msg"></span> </div> <div class="contact-info"> <div class="address"> <i class="fa-solid fa-phone"></i> <a href="tel:+917905767625">+917905767625</a> </div> <div class="address"> <i class="fa-solid fa-location-dot"></i> <address>A1/1 Sulabh Awash Yojna,Transport Nagar,Lucknow 26012</address> </div> </div> <div class="social"> <div class="icon"> <a href="https://github.com/Anish2944"> <i class="fa-brands fa-github fa-2xl"></i> </a> <a href="https://www.linkedin.com/in/anish-kushwaha-45857b227/"> <i class="fa-brands fa-linkedin fa-2xl"></i> </a> <a href="https://twitter.com/AnishKu30530485"> <i class="fa-brands fa-square-x-twitter fa-2xl"></i> </a> <a href="https://www.instagram.com/anish_kh_007/"> <i class="fa-brands fa-instagram fa-2xl"></i> </a> <a href="https://www.facebook.com/profile.php?id=100081158640573"> <i class="fa-brands fa-facebook fa-2xl"></i> </a> <a href="https://t.me/Anish07082002"> <i class="fa-brands fa-telegram fa-2xl"></i> </a> </div> </div> </div> </footer> <div class="CopyRight"> <p>Copy Right &copy; all Right reserved.</p> </div> <script src="./script.js"></script> </body> </html>
import { Test, TestingModule } from '@nestjs/testing'; import { HttpException, HttpStatus } from '@nestjs/common'; import { CommitsController } from './commits.controller'; import { CommitsService } from '../service/commits.service'; describe('CommitsController', () => { let controller: CommitsController; let service: CommitsService; const commitsServiceMock = { findAllByOwnerAndRepositoryName: jest.fn(), }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [CommitsController], providers: [ { provide: CommitsService, useValue: commitsServiceMock, }, ], }).compile(); controller = module.get<CommitsController>(CommitsController); service = module.get<CommitsService>(CommitsService); }); it('should be defined', () => { expect(controller).toBeDefined(); }); describe('findAllByOwnerAndRepositoryName method', () => { it('should return commits from the service', async () => { const owner = 'exampleOwner'; const repositoryName = 'exampleRepo'; const commits = [ { message: 'Test commit message 1', date: '2022-10-15T22:37:24Z', isVerified: false, authorName: 'Test User 1', authorEmail: '[email protected]', }, { message: 'Test commit message 2', date: '2022-10-15T22:37:24Z', isVerified: false, authorName: 'Test User 2', authorEmail: '[email protected]', }, ]; // Mock the service method to return the commits commitsServiceMock.findAllByOwnerAndRepositoryName.mockResolvedValue( commits, ); const result = await controller.findAllByOwnerAndRepositoryName({ owner, repositoryName, }); // Verify that the controller calls the service method and returns the result expect(service.findAllByOwnerAndRepositoryName).toHaveBeenCalledWith( owner, repositoryName, ); expect(result).toEqual(commits); }); it('should handle errors by throwing an HttpException', async () => { const owner = 'exampleOwner'; const repositoryName = 'exampleRepo'; const errorMessage = 'Service error message'; const errorStatus = HttpStatus.INTERNAL_SERVER_ERROR; // Mock the service method to throw an error commitsServiceMock.findAllByOwnerAndRepositoryName.mockRejectedValue({ message: errorMessage, status: errorStatus, }); // Verify that the controller throws an HttpException with the correct message and status await expect( controller.findAllByOwnerAndRepositoryName({ owner, repositoryName }), ).rejects.toThrowError(new HttpException(errorMessage, errorStatus)); // Verify that the controller calls the service method expect(service.findAllByOwnerAndRepositoryName).toHaveBeenCalledWith( owner, repositoryName, ); }); }); });
#DESCRIPTION # question fran&ccedil;aise produite dans le cadre du projet de math&eacute;matiques # section Entiers - Calcul mental - Puissance # type de question - Appliquer une puissance (complexe) ##ENDDESCRIPTION ## DBsubject('Arithm&eacute;tique') ## DBchapter('Entier') ## DBsection('Puissance') ## Author('Diane Bergeron et Louise Pellerin') ## Institution('CEGEP de Chicoutimi et La Cit&eacute; coll&eacute;giale') ## KEYWORDS('fran&ccedil;ais', 'arithm&eacute;tique', 'entier', 'puissance','exposant', 'calcul mental') ########################################################################### DOCUMENT(); loadMacros( "PGstandard.pl", ); TEXT(beginproblem()); $a=random(2,9); $exp=random(3,5); $reponse=$a**$exp; # ci-dessous le n&eacute;cessaire pour exposer le d&eacute;veloppement de la solution selon l'exposant choisi $aa = $a * $a; $aaa = $a * $a * $a; if ($exp==3) {$solution= "$a x $a x $a = ($a x $a) x $a = $aa x $a = ";} elsif ($exp==4) {$solution= "$a x $a x $a x $a = ($a x $a) x ($a x $a) = $aa x $aa = ";} else {$solution="$a x $a x $a x $a x $a = ($a x $a) x ($a x $a) x $a = $aa x ($aa x $a) = $aa x $aaa = ";} BEGIN_TEXT <table cellpadding="10px" width="850px"> <tr><td> <h1>Question : </h1> <br/>$a<sup>$exp</sup> = <br/> \{ans_rule(10)\} </td></tr> </table> END_TEXT BEGIN_HINT <script> function hint(hint){ var text =""; var hintName =hint.name; switch(hintName){ case '1':text=" L'exposant dans l'&eacute;quation de puissance repr&eacute;sente le nombre de fois que le chiffre pr&eacute;sent doit &ecirc;tre multipli&eacute; par lui-m&ecirc;me. "; break; case '2':text=" Lorsqu'un exposant semble trop &eacute;lev&eacute; pour r&eacute;soudre la puissance d'un coup, s&eacute;parer la puissance en deux ou trois regroupements diff&eacute;rents et en multiplier les r&eacute;sultats partiels obtenus jusqu'&agrave; l'obtention du r&eacute;sultat final (ex.: 2<sup>5</sup> = 2 x 2 x 2 x 2 x 2 = (2 x 2) x (2 x 2 x 2) = (4) x (8)= 32. "; break; case '3':text="Consulter la th&eacute;orie sur le sujet au site web suivant: <a target=_blank href=http://math.cchic.ca/entiers/puissances>http://math.cchic.ca</a>."; break; default:text="" }document.getElementById("hintspace").style.display='block'; document.getElementById("hinttext").innerHTML=text; document.getElementById("hintName").innerHTML="Astuce "+hintName; } function resetHint(){document.getElementById("hintspace").style.display='none';document.getElementById("hinttext").innerHTML="";} </script> <button type="button" name="1" onclick="hint(this)">Astuce 1</button>&nbsp; <button type="button" name="2" onclick="hint(this)">Astuce 2</button>&nbsp; <button type="button" name="3" onclick="hint(this)">Astuce 3</button>&nbsp; <div id="hintspace" style="width:800px;display:none;border:1px solid darkblue;"> <table width="100%" border="0" cellspacing="0"> <tr style="background-color:#8888dd;"> <td valign="top" align="left" width="50%"> <text id="hintName" style="color:white;padding-left:15px;"></text> </td> <td valign="top" align="right" width="50%"> <text style="color:white;cursor:pointer; padding-right:5px;" onclick="resetHint()" >Fermer [x]</text> </td> </tr> <tr style="background-color:#b0c4de;"> <td id="hinttext" colspan="2"style="color:black;padding:15px;"></td> </tr> </table> </div> END_HINT ANS(strict_num_cmp($reponse, .0)); SOLUTION(EV3(<<'END_SOLUTION')); <p><u>Solution</u></p> <p>$a<sup>$exp</sup> = $solution $reponse</p> END_SOLUTION ENDDOCUMENT();
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'main.dart'; import 'tabla.dart'; import 'package:ti_app/second.dart'; import 'package:ti_app/recuperacion.dart'; import 'package:http/http.dart' as http; Future<Usuario> getUsuario(String usuario, String contrasena) async { final response = await http.get(Uri.parse( 'https://technologystaruth5.com.mx/api_xd/login.php?us=$usuario&ps=$contrasena')); if (response.statusCode == 200) { return Usuario.fromJson(jsonDecode(response.body)); } else { throw Exception('Ingresa los datos. '); } } class Usuario { final String id; final String username; final String nombre; final String ap; final String am; final String rol; final String correo; const Usuario({ required this.id, required this.username, required this.nombre, required this.ap, required this.am, required this.rol, required this.correo, }); factory Usuario.fromJson(Map<String, dynamic> json) { return Usuario( id: json['id'], username: json['username'], nombre: json['nombre'], ap: json['ap'], am: json['am'], rol: json['rol'], correo: json['correo']); } } void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); static const String _title = ''; @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int? loggedInUserId; void setLoggedInUserId(int userId) { setState(() { loggedInUserId = userId; }); } @override Widget build(BuildContext context) { return MaterialApp( title: MyApp._title, home: LoginPage(setLoggedInUserId: setLoggedInUserId), routes: { '/second': (context) => SecondRoute(loggedInUserId: loggedInUserId), }, ); } } class LoginPage extends StatefulWidget { var setLoggedInUserId; LoginPage({Key? key, required this.setLoggedInUserId}) : super(key: key); @override LoginPageState createState() => LoginPageState(); } class LoginPageState extends State<LoginPage> { final TextEditingController _userController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); static var user; Future<void> _login() async { try { Usuario usuario = await getUsuario(_userController.text, _passwordController.text); widget.setLoggedInUserId(int.parse(usuario.id)); user = usuario; // Aquí se guarda el ID del usuario Navigator.pushNamed(context, '/second'); } catch (e) { print(e); showDialog( context: context, builder: (context) => AlertDialog( title: const Text('Error'), content: const Text('Error al validar usuario'), ), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('FINGERPRINT'), ), body: Padding( padding: const EdgeInsets.all(10), child: ListView( children: <Widget>[ Container( alignment: Alignment.center, padding: const EdgeInsets.all(10), child: const Text( '', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.w500, fontSize: 30), ), ), Image.asset( 'assets/imagenes/logo.png', height: 200, width: 200, ), // Agregar aquí Container( alignment: Alignment.center, padding: const EdgeInsets.all(10), child: const Text( 'Iniciar sesión', style: TextStyle(fontSize: 20), )), Container( padding: const EdgeInsets.all(10), child: TextField( controller: _userController, decoration: const InputDecoration( border: OutlineInputBorder(), hintText: 'Correo Electrónico', ), ), ), Container( padding: const EdgeInsets.all(8.0), child: TextField( controller: _passwordController, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Contraseña', ), obscureText: true, ), ), ElevatedButton( onPressed: _login, child: const Text('Iniciar sesión'), key: const Key('loginButton'), ), TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => Recovery()), ); }, child: const Text('olvide mi contraseña'), ), ], ), ), ); } }
#!/usr/bin/python3 """ Tests for the BaseModel class These unit tests provide a foundation for verifying the functionality of your BaseModel class. """ from models.base_model import BaseModel import unittest from datetime import datetime import time from time import sleep class TestBaseModel(unittest.TestCase): def test_instance_creation(self): instance = BaseModel() self.assertIsInstance(instance, BaseModel) def test_base_model_attrs(self): """ Test id attribute type Test created_at attribute type Test updated_at attribute type """ self.assertEqual(str, type(BaseModel().id)) self.assertEqual(datetime, type(BaseModel().created_at)) self.assertEqual(datetime, type(BaseModel().updated_at)) def test_id_unique(self): """ Test that the id attribute is unique """ instance1 = BaseModel() instance2 = BaseModel() self.assertNotEqual(instance1.id, instance2.id) def test_two_models_different_updated_at(self): bm1 = BaseModel() sleep(0.05) bm2 = BaseModel() self.assertLess(bm1.updated_at, bm2.updated_at) def test_init_with_attributes(self): """ Test initialization with specific attributes """ created_at = "2022-01-01 12:00:00" updated_at = "2022-01-02 12:00:00" model = BaseModel(id="123", created_at=created_at, updated_at=updated_at) self.assertEqual(model.id, "123") self.assertEqual(str(model.created_at), created_at) self.assertEqual(str(model.updated_at), updated_at) def test_init_with_defaults(self): # Test initialization with default values model = BaseModel() self.assertIsNotNone(model.id) self.assertIsInstance(model.created_at, datetime) self.assertIsInstance(model.updated_at, datetime) def test_to_dict_method(self): instance = BaseModel() dictionary = instance.to_dict() self.assertIsInstance(dictionary, dict) self.assertEqual(dictionary['__class__'], 'BaseModel') def test_to_dict_returns_dict(self): # Test that to_dict() returns a dictionary with the expected keys and values model = BaseModel( id="123", created_at="2022-01-01T12:00:00", updated_at="2022-01-02T12:00:00", ) expected_dict = { "id": "123", "created_at": "2022-01-01T12:00:00", "updated_at": "2022-01-02T12:00:00", "__class__": "BaseModel" } self.assertEqual(model.to_dict(), expected_dict) def test_save_method(self): instance = BaseModel() old_update = instance.updated_at instance.save() self.assertEqual(str(instance.updated_at), str(old_update)) if __name__ == '__main__': unittest.main()
import { Kind } from 'nostr-tools' import React, { useContext, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { ActivityIndicator, StyleSheet, View } from 'react-native' import { Button, Card, Text, useTheme } from 'react-native-paper' import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' import { AppContext } from '../../../Contexts/AppContext' import { RelayPoolContext } from '../../../Contexts/RelayPoolContext' import { UserContext } from '../../../Contexts/UserContext' import { getUsers, type User } from '../../../Functions/DatabaseFunctions/Users' interface SecondStepProps { nextStep: () => void skip: () => void } export const SecondStep: React.FC<SecondStepProps> = ({ nextStep, skip }) => { const theme = useTheme() const { t } = useTranslation('common') const { database } = useContext(AppContext) const { relayPool, relayPoolReady, lastEventId, relays } = useContext(RelayPoolContext) const { publicKey } = useContext(UserContext) const [contactsCount, setContactsCount] = useState<number>() React.useEffect(() => { setTimeout(loadData, 1500) }, []) useEffect(() => { if (publicKey && relayPoolReady && database) { loadPets() } }, [publicKey, lastEventId]) const loadData: () => void = () => { if (publicKey && relayPoolReady) { relayPool?.subscribe('profile-load-contacts', [ { kinds: [Kind.Contacts], authors: [publicKey], }, { kinds: [Kind.ChannelCreation, Kind.ChannelMetadata], authors: [publicKey], }, { kinds: [10000], limit: 1, authors: [publicKey], }, { kinds: [10001], limit: 1, authors: [publicKey], }, { kinds: [30001], limit: 1, authors: [publicKey], }, ]) } } const loadPets: () => void = () => { if (database && publicKey && relayPoolReady) { getUsers(database, {}).then((results) => { if (results.length > 0) { setContactsCount(results.filter((user) => user.contact).length) const authors = [...results.map((user: User) => user.id)] relayPool?.subscribe('profile-load-contacts', [ { kinds: [10002], authors, }, ]) } }) } } return ( <View style={styles.container}> <View> <View style={styles.loadingProfile}> <Text style={{ color: theme.colors.onSurfaceVariant }} variant='titleMedium'> {t('profileLoadPage.connectingRandomRelays')} </Text> <MaterialCommunityIcons style={{ color: '#7ADC70' }} name='check-circle-outline' size={20} /> </View> <View style={styles.loadingProfile}> <Text variant='titleMedium'>{t('profileLoadPage.searchContacts')}</Text> </View> <View style={styles.loadingProfile}> <Text style={{ color: theme.colors.onSurfaceVariant }}> {t('profileLoadPage.searchContactsDescription')} </Text> </View> <Card style={styles.card}> <Card.Content> <View style={styles.loadingProfile}> <Text>{t('profileLoadPage.myRelays')}</Text> <Text style={{ color: '#7ADC70' }}> {t('profileLoadPage.connectedRelays', { activeRelays: relays.length })} </Text> </View> <View style={styles.loadingProfile}> <Text>{t('profileLoadPage.contactsCount')}</Text> {contactsCount ? ( <Text>{contactsCount}</Text> ) : ( <ActivityIndicator animating={true} size={20} /> )} </View> </Card.Content> </Card> <View style={styles.loadingProfile}> <Text style={{ color: theme.colors.onSurfaceVariant }} variant='titleMedium'> {t('profileLoadPage.searchContactsRelays')} </Text> </View> </View> <View style={styles.buttons}> <Button style={styles.button} mode='outlined' onPress={skip}> {t('profileLoadPage.skip')} </Button> <Button mode='contained' onPress={nextStep} disabled={contactsCount === undefined}> {t('profileLoadPage.continue')} </Button> </View> </View> ) } const styles = StyleSheet.create({ container: { padding: 16, justifyContent: 'space-between', flex: 1, }, buttons: { justifyContent: 'space-between', }, button: { marginBottom: 16, }, logo: { justifyContent: 'center', alignContent: 'center', flexDirection: 'row', }, center: { alignContent: 'center', textAlign: 'center', }, card: { marginBottom: 16, }, loadingProfile: { flexDirection: 'row', marginBottom: 16, justifyContent: 'space-between', }, }) export default SecondStep
<%@ page language="java"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%> <%@ taglib uri="http://struts.application-servers.com/layout" prefix="layout"%> <layout:html layout="false" key="page.title.my"> <logic:empty name="configInitForm"> <strong><font color="#FF0000">XTracker has already been configured.</font></strong> <p><em><font color="#800000">Please use the administration console to make changes.</font></em></p> </logic:empty> <logic:notEmpty name="configInitForm"> <logic:equal name="configInitForm" property="configured" value="true"> <strong><font color="#FF0000">XTracker has already been configured.</font></strong> <p><em><font color="#800000">Please use the administration console to make changes.</font></em></p> </logic:equal> <logic:equal name="configInitForm" property="configured" value="false"> <html:form action="/init"> <table width="50%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="100%" cellspacing="0" cellpadding="0" border="0" class="boxyello"> <tr> <th colspan="2">Root Directory Configuration</th> </tr> <tr> <td colspan="2">XPlanner needs to know where you want to store your configuration files and attachments.<br> The directory must be read/write by the user running the application container. <p> A default value has been selected for you.<br> You may leave it as is or change it to something that better suits your system.<br> You will only be asked this once and the system will attempt to create it if it doesn't already exist. </p></td> </tr> <tr><td>&nbsp;</td></tr> <tr> <td colspan="2"><html:text name="configInitForm" property="path" size="60"/></td> </tr> <tr><td>&nbsp;</td></tr> </table> </td> </tr> <tr><td>&nbsp;</td></tr> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="boxyello"> <tr> <th colspan="2">Database Configuration</th> </tr> <tr> <td colspan="2">XPlanner uses Hibernate to store its data.<br> Please specify the properties for the database you wish to use. Properties for MySQL have been pre-populated as an example.<p> <strong>Note:</strong> <em>the account should have rights to create tables, indexes etc.<br> If you do not want XTracker to create its database for you, you can manually create it from the source with the</em> hibernate:schema-export <em>Maven goal. You will have to edit the file</em> etc/hibernate/hibernate.properties <em>file first however.</em></p> <p>Some drivers are already installed, and some you will have to install yourself after initialization. If you want to use one of the drivers that are not installed, simply add the proper configuration parameters here and add the drivers manually to the <em>WEB-INF/lib</em> directory. A restart will be required.</p> The Dialect status ratings are: <ul> <li><span class="greenbackgroup">Installed and Tested</span></li> <li><span class="yellobackgroup">Installed, Not Tested</span></li> <li><span class="redbackgroup">Not Installed, Not Tested</span></li> </ul> </td> </tr> <tr><td>&nbsp;</td></tr> <tr> <td><bean:message key="view.label.config.connection.dialect"/></td> <td><html:select name="configInitForm" property="hibernateDialect"> <html:option styleClass="greenbackgroup" value="net.sf.hibernate.dialect.MySQLDialect">MySQL</html:option> <html:option styleClass="greenbackgroup" value="net.sf.hibernate.dialect.HSQLDialect">HypersonicSQL</html:option> <html:option styleClass="greenbackgroup" value="net.sf.hibernate.dialect.Oracle9Dialect">Oracle 9/10g</html:option> <html:option styleClass="yellobackgroup" value="net.sf.hibernate.dialect.PostgreSQLDialect">PostgreSQL</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.DB2Dialect">DB2</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.DB2400Dialect">DB2 AS/400</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.DB2390Dialect">DB2 OS390</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.OracleDialect">Oracle (any version)</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.SybaseDialect">Sybase</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.SybaseAnywhereDialect">Sybase Anywhere</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.SQLServerDialect">Microsoft SQL Server</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.SAPDBDialect">SAP DB</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.InformixDialect">Informix</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.IngresDialect">Ingres</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.ProgressDialect">Progress</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.MckoiDialect">Mckoi SQL</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.InterbaseDialect">Interbase</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.PointbaseDialect">Pointbase</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.FrontbaseDialect">FrontBase</html:option> <html:option styleClass="redbackgroup" value="net.sf.hibernate.dialect.FirebirdDialect">Firebird</html:option> </html:select></td> </tr> <tr> <td><bean:message key="view.label.config.connection.url"/></td> <td><html:text name="configInitForm" property="connectionUrl" size="40"/></td> </tr> <tr> <td><bean:message key="view.label.config.connection.driver"/></td> <td><html:text name="configInitForm" property="connectionDriver" size="40"/></td> </tr> <tr> <td><bean:message key="view.label.config.connection.username"/></td> <td><html:text name="configInitForm" property="connectionUsername" size="40"/></td> </tr> <tr> <td><bean:message key="view.label.config.connection.password"/></td> <td><html:text name="configInitForm" property="connectionPassword" size="40"/></td> </tr> <tr><td>&nbsp;</td></tr> </table> </td> </tr> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="right" nowrap><html:submit> <bean:message key="view.label.save"/> </html:submit></td> </tr> </table> </td> </tr> </table> </html:form> </logic:equal> </logic:notEmpty> </layout:html>
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "@kengachu-pulumi/azure-native-core/utilities"; import * as types from "./types"; /** * Get a Maps Account. */ export function getAccount(args: GetAccountArgs, opts?: pulumi.InvokeOptions): Promise<GetAccountResult> { opts = pulumi.mergeOptions(utilities.resourceOptsDefaults(), opts || {}); return pulumi.runtime.invoke("azure-native:maps/v20180501:getAccount", { "accountName": args.accountName, "resourceGroupName": args.resourceGroupName, }, opts); } export interface GetAccountArgs { /** * The name of the Maps Account. */ accountName: string; /** * The name of the Azure Resource Group. */ resourceGroupName: string; } /** * An Azure resource which represents access to a suite of Maps REST APIs. */ export interface GetAccountResult { /** * The fully qualified Maps Account resource identifier. */ readonly id: string; /** * The location of the resource. */ readonly location: string; /** * The name of the Maps Account, which is unique within a Resource Group. */ readonly name: string; /** * The map account properties. */ readonly properties: types.outputs.MapsAccountPropertiesResponse; /** * The SKU of this account. */ readonly sku: types.outputs.SkuResponse; /** * Gets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. */ readonly tags: {[key: string]: string}; /** * Azure resource type. */ readonly type: string; } /** * Get a Maps Account. */ export function getAccountOutput(args: GetAccountOutputArgs, opts?: pulumi.InvokeOptions): pulumi.Output<GetAccountResult> { return pulumi.output(args).apply((a: any) => getAccount(a, opts)) } export interface GetAccountOutputArgs { /** * The name of the Maps Account. */ accountName: pulumi.Input<string>; /** * The name of the Azure Resource Group. */ resourceGroupName: pulumi.Input<string>; }
import '../styles/globals.css'; import type { AppProps } from 'next/app'; import Navbar from '../components/Navbar'; import Footer from '../components/Footer'; import Head from 'next/head'; function MyApp({ Component, pageProps }: AppProps) { return ( <div className="antialiased"> <Head> <title>Florian Woelki</title> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" /> <meta name="msapplication-TileColor" content="#da532c"></meta> <meta name="theme-color" content="#ffffff"></meta> </Head> <Navbar /> <Component {...pageProps} /> <Footer /> </div> ); } export default MyApp;
import { space } from "@/types/type"; import Link from "next/link"; import React from "react"; import { BsArrowRight } from "react-icons/bs"; import { formatDate, formatTime } from "./utilities/utility"; type Props = { space: space; }; const SpaceCard = ({ space }: Props) => { return ( <div className="rounded-lg bg-accent-base/80 p-4 w-[12rem] flex flex-col justify-between"> <div className="flex text-sm"> <div className="flex flex-col text-skin-inverted w-[80%] gap-1"> <p> {formatDate(space.date)} @{" "} <span className="text-semibold"> {formatTime(space.from)}</span> </p> <p>{space.title}</p> </div> <img className="w-10 h-10 rounded-full" src={space.users.image} alt="" /> </div> <button className="hover:gap-3 transition-all hover:font-semibold flex gap-2 justify-center items-center mt-2 w-full py-1 rounded-full mx-auto bg-accent-base text-skin-inverted"> <Link href={space.link}>Join</Link> <BsArrowRight /> </button> </div> ); }; export default SpaceCard;
import React from "react"; import ReactApexChart from "react-apexcharts"; import styled from "styled-components"; const ColumnCharts = () => { const options = { //! 차트 바 색상 // list 형태 colors: ["#007cf7", "#8d928a"], //! 차트 기본 설정 chart: { // offsetY: 100, // offsetX: 100, height: "100%", type: "bar", // 툴바 보여주기 여부 및 설정 toolbar: { show: false, }, // 애니메이션 여부 및 설정 animations: { enabled: true, easing: "easeinout", speed: 800, animateGradually: { enabled: true, delay: 150, }, dynamicAnimation: { enabled: true, speed: 350, }, }, // 차트 그림자 여부 및 설정 dropShadow: { enabled: false, enabledOnSeries: undefined, top: 0, left: 0, blur: 3, color: "#000", opacity: 0.35, }, // 차트 폰트 및 색상 fontFamily: "Helvetica, Arial, sans-serif", foreColor: "black", // 차트 요소 변경시 리랜더링 여부 redrawOnParentResize: true, }, //! 주석 설정 annotations: { show: true, }, //! 그래프 바 설정 plotOptions: { bar: { horizontal: false, // 그래프 수직 수평 설정 borderRadius: 0, // 그래프 라운드 설정 endingShape: "rounded", columnWidth: "60%", // 그래프 바 두께 설정 barHeight: "100%", distributed: false, }, }, //! dataLabels: { enabled: false, }, //! stroke: { show: true, width: 10, colors: ["transparent"], }, //! x축 설정 xaxis: { categories: ["0~8", "21~24", "25~(듀스)"], // tickPlacement: "on", }, //! y 축 설정 yaxis: { show: true, showAlways: true, // 제목설정 title: { text: "(회)", rotate: -360, offsetY: 0, offsetX: 0, }, // labels: { offsetX: 0, offsetY: -50, }, axisTicks: { show: true, borderType: "solid", color: "#78909C", width: 0, offsetX: 0, offsetY: 0, }, // logBase: 20, tickAmount: 5, // y축 표시할 선 간격 수 min: 20, // y축 시작 설정 max: 120, // y축 끝 설정 }, fill: { opacity: 20, }, //! 툴박스 설정 // 마우스 호버시 뜨는 정보 설정 tooltip: { // 보여줄지 말지 설정 enabled: true, // 마우스 따라 갈건지 말건지 followCursor: true, // 마우스가 바 위에 있을때만 보여주는 intersect: true, // 바 색상과 툴팁 색상 같이 할건지 fillSeriesColor: false, // theme: false, style: { fontSize: "15px", fontFamily: undefined, }, onDatasetHover: { highlightDataSeries: false, }, // 툴팁 제목 설정 x: { show: true, format: "text", formatter: () => // val, // { series, seriesIndex, dataPointIndex, w } { return "으아아아"; }, }, // 툴팁 내용 설정 y: { formatter: ( val // { series, seriesIndex, dataPointIndex, w } ) => { return val + "점"; }, }, // 툴박스 내용 앞 점 표시 여부 marker: { show: true, }, items: { display: "flex", }, // 툴박스 고정 fixed: { enabled: false, position: "topRight", offsetX: 0, offsetY: 0, }, //? 커스텀 영역 // custom: function ({ series, seriesIndex, dataPointIndex, w }) { // return ( // '<div class="arrow_box">' + // "<span>" + // w.globals.labels[dataPointIndex] + // ": " + // series[seriesIndex][dataPointIndex] + // "</span>" + // "</div>" // ); // }, }, // 범례 여부 및 설정 legend: { show: true, // 차트가 하나일때도 보일지 여부 showForSingleSeries: false, // 값이 null 경우 범례 표시 안함 showForNullSeries: true, showForZeroSeries: true, position: "bottom", horizontalAlign: "start", floating: false, fontSize: "20px", fontFamily: "Helvetica, Arial", fontWeight: 700, formatter: undefined, inverseOrder: false, width: undefined, height: undefined, tooltipHoverFormatter: undefined, customLegendItems: [], offsetX: 0, offsetY: 10, labels: { colors: undefined, useSeriesColors: false, }, // 범례 아이콘 설정 markers: { width: 30, height: 12, strokeWidth: 0, strokeColor: "#fff", fillColors: undefined, radius: 0, customHTML: undefined, onClick: undefined, offsetX: -20, offsetY: 0, }, // 범례 사이 설정 itemMargin: { horizontal: 50, vertical: 0, }, onItemClick: { toggleDataSeries: true, }, onItemHover: { highlightDataSeries: true, }, }, // 바 클릭시 커스텀 옵션 states: { normal: { filter: { type: "none", value: 0, }, }, hover: { filter: { type: "lighten", value: 0.05, }, }, active: { allowMultipleDataPointsSelection: false, filter: { type: "darken", value: 0.35, }, }, }, }; const series = [ { name: "배성열", data: [20, 30, 40], }, { name: "강인호", data: [50, 85, 60], }, ]; return ( <> <ReactApexChartStyled type="bar" options={options} series={series} width={"1000px"} height={"300px"} /> </> ); }; const ReactApexChartStyled = styled(ReactApexChart)` .apexcharts-tooltip { display: flex; background: yellow; color: orange; } `; export default ColumnCharts;
<!-- Curso de HTML --> <!-- Markup: TAGS -Abertura de tags -Fechamento de tags -Conteúdo -Elementos --> <h1>Título</h1> Preencha aqui: <!-- Elementos Vazios Não têm conteúdos, somente atributos (não tem fechamento) --> <img scr="" alt=""> <input type="text"> <!-- Atributos HTML -Informações extras -Configurações --> <img scr="imagem.png" alt="Alguma foto qualquer"> <!-- Atributos Booleanos Não precisam de conteúdo (Verdadeiro ou Falso)--> <input type="text" disabled> <!-- Aspas Usar sempre aspas duplas --> <a href="https://google.com" title="google">Acessar</a> <!-- utilizar At-b para abrir o documento no browser--> <!-- Caracteres Especiais --> <p> &nbsp; </p> <p> &lt; </p> <p> &gt; </p> <p> &amp; </p> <p> &quot; </p> <p> &apos; </p>
/** * I18n.js * App for SecureSwap ICO website. * * Includes all of the following: Tools.js * * @version: 1.0.0 * @author: Philippe Aubessard, [email protected] * @url http://secure-swap.com * @license: Copyright (c) 2018, GreyMattersTechs. All rights reserved. * @namespace: ssw */ 'use strict'; (function(window, undefined) { window.ssw = window.ssw || {}; // NameSpace if ( window.ssw.Tools === undefined ) { throw new Error( 'Please load Tools.js' ); } // ---------- class I18n // --- public static // constructeur public static window.ssw.I18n = function() { throw new Error( 'Please use getInstance' ); }; // singleton factory public static window.ssw.I18n.getInstance = function() { if ( instance ) { return instance; } instance = new I18n(); return instance; }; // --- private static // membres private static var instance = null; // Constructeur private static var I18n = function() { // --- private members // https://github.com/wikimedia/jquery.i18n // https://phraseapp.com/blog/posts/jquery-i18n-the-advanced-guide/ // https://github.com/wikimedia/jquery.i18n // http://www.science.co.il/language/Locale-codes.php // http://www.metamodpro.com/browser-language-codes // http://www.science.co.il/language/Locale-codes.php // https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes // http://4umi.com/web/html/languagecodes.php // https://gist.github.com/wpsmith/7604842 // * \xE2\x80\x8E is the left-to-right marker and // * \xE2\x80\x8F is the right-to-left marker. // * They are required for ensuring the correct display of brackets in mixed rtl/ltr environment. var locales = [ {browser: 'aa', mailchimp: '', flag: '', native: 'Afaraf', english: 'Afar', notes: ''}, {browser: 'ab', mailchimp: '', flag: '', native: 'Аҧсуа', english: 'Abkhazian', notes: ''}, {browser: 'ace', mailchimp: '', flag: '', native: 'Acèh', english: 'Aceh', notes: ''}, {browser: 'af', mailchimp: 'af', flag: '', native: 'Afrikaans', english: 'Afrikaans', notes: ''}, {browser: 'ak', mailchimp: '', flag: '', native: 'Akan', english: 'Akan', notes: ''}, {browser: 'aln', mailchimp: '', flag: '', native: 'Gegë', english: 'Gheg Albanian', notes: ''}, {browser: 'als', mailchimp: '', flag: '', native: 'Alemannisch', english: 'Alemannic', notes: 'Not a valid code, for compatibility. See gsw.'}, {browser: 'am', mailchimp: '', flag: '', native: 'አማርኛ', english: 'Amharic', notes: ''}, {browser: 'an', mailchimp: '', flag: '', native: 'aragonés', english: 'Aragonese', notes: ''}, {browser: 'ang', mailchimp: '', flag: '', native: 'Ænglisc', english: 'Old English', notes: ''}, {browser: 'anp', mailchimp: '', flag: '', native: 'अङ्गिका', english: 'Angika', notes: ''}, {browser: 'ar', mailchimp: 'ar', flag: '', native: 'العربية', english: 'Arabic', notes: ''}, {browser: 'ar_dz', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Algeria)', notes: ''}, {browser: 'ar_bh', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Bahrain)', notes: ''}, {browser: 'ar_eg', mailchimp: 'ar', flag: '', native: 'مصرى', english: 'Arabic (Egypt)', notes: ''}, {browser: 'ar_iq', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Iraq)', notes: ''}, {browser: 'ar_jo', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Jordan)', notes: ''}, {browser: 'ar_kw', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Kuwait)', notes: ''}, {browser: 'ar_lb', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Lebanon)', notes: ''}, {browser: 'ar_ly', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Libya)', notes: ''}, {browser: 'ar_ma', mailchimp: 'ar', flag: '', native: 'Maġribi', english: 'Arabic (Morocco)', notes: ''}, {browser: 'ar_om', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Oman)', notes: ''}, {browser: 'ar_qa', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Qatar)', notes: ''}, {browser: 'ar_sa', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Saudi Arabia)', notes: ''}, {browser: 'ar_sy', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Syria)', notes: ''}, {browser: 'ar_tn', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Tunisia)', notes: ''}, {browser: 'ar_ae', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (U.A.E.)', notes: ''}, {browser: 'ar_ye', mailchimp: 'ar', flag: '', native: '', english: 'Arabic (Yemen)', notes: ''}, {browser: 'arc', mailchimp: '', flag: '', native: 'ܐܪܡܝܐ', english: 'Aramaic', notes: ''}, {browser: 'arn', mailchimp: '', flag: '', native: 'mapudungun', english: 'Mapuche, Mapudungu, Araucanian (Araucano)', notes: ''}, {browser: 'as', mailchimp: '', flag: '', native: 'অসমীয়া', english: 'Assamese', notes: ''}, {browser: 'ast', mailchimp: '', flag: '', native: 'asturianu', english: 'Asturian', notes: ''}, {browser: 'av', mailchimp: '', flag: '', native: 'авар мацӀ', english: 'Avaric', notes: ''}, {browser: 'avk', mailchimp: '', flag: '', native: 'Kotava', english: 'Kotava', notes: ''}, {browser: 'ay', mailchimp: '', flag: '', native: 'Aymar aru', english: 'Aymara', notes: ''}, {browser: 'az', mailchimp: '', flag: '', native: 'Azərbaycan dili', english: 'Azerbaijani', notes: ''}, {browser: 'azb', mailchimp: '', flag: '', native: 'تورکجه', english: 'South Azerbaijani', notes: ''}, {browser: 'ba', mailchimp: '', flag: '', native: 'башҡортса', english: 'Bashkir', notes: ''}, {browser: 'bar', mailchimp: '', flag: '', native: 'Boarisch', english: 'Bavarian (Austro_Bavarian and South Tyrolean)', notes: ''}, {browser: 'bat_smg', mailchimp: '', flag: '', native: 'žemaitėška', english: 'Samogitian', notes: '(deprecated code, \'sgs\' in ISO 693-3 since 2010-06-30 )'}, {browser: 'bbc', mailchimp: '', flag: '', native: 'Batak Toba', english: 'Batak Toba', notes: ' (falls back to bbc_latn)'}, {browser: 'bbc_latn', mailchimp: '', flag: '', native: 'Batak Toba', english: 'Batak Toba', notes: ''}, {browser: 'bcc', mailchimp: '', flag: '', native: 'بلوچی مکرانی', english: 'Southern Balochi', notes: ''}, {browser: 'bcl', mailchimp: '', flag: '', native: 'Bikol Central', english: 'Bikol: Central Bicolano language', notes: ''}, {browser: 'be', mailchimp: 'be', flag: 'be', native: 'беларуская', english: ' Belarusian normative', notes: ''}, // {browser: 'be_tarask', mailchimp: '', flag: '', native: '"беларуская (тарашкевіца)\xE2\x80\x8E"', english: 'Belarusian in Taraskievica orthography', notes: ''}, // {browser: 'be_x_old', mailchimp: '', flag: '', native: '"беларуская (тарашкевіца)\xE2\x80\x8E"', english: '(be_tarask compat)', notes: ''}, {browser: 'bg', mailchimp: 'bg', flag: 'bg', native: 'български', english: 'Bulgarian', notes: ''}, {browser: 'bh', mailchimp: '', flag: '', native: 'भोजपुरी', english: 'Bihari', notes: 'macro language. Falls back to Bhojpuri (bho)'}, {browser: 'bho', mailchimp: '', flag: '', native: 'भोजपुरी', english: 'Bhojpuri', notes: ''}, {browser: 'bi', mailchimp: '', flag: '', native: 'Bislama', english: 'Bislama', notes: ''}, {browser: 'bjn', mailchimp: '', flag: '', native: 'Bahasa Banjar', english: 'Banjarese', notes: ''}, {browser: 'bm', mailchimp: '', flag: '', native: 'bamanankan', english: 'Bambara', notes: ''}, {browser: 'bn', mailchimp: '', flag: 'bn', native: 'বাংলা', english: 'Bengali', notes: ''}, {browser: 'bo', mailchimp: '', flag: '', native: 'བོད་ཡིག', english: 'Tibetan', notes: ''}, {browser: 'bpy', mailchimp: '', flag: '', native: 'বিষ্ণুপ্রিয়া মণিপুরী', english: 'Bishnupriya Manipuri', notes: ''}, {browser: 'bqi', mailchimp: '', flag: '', native: 'بختياري', english: 'Bakthiari', notes: ''}, {browser: 'br', mailchimp: '', flag: '', native: 'brezhoneg', english: 'Breton', notes: ''}, {browser: 'brh', mailchimp: '', flag: '', native: 'Bráhuí', english: 'Brahui', notes: ''}, {browser: 'bs', mailchimp: '', flag: '', native: 'bosanski', english: 'Bosnian', notes: ''}, {browser: 'bug', mailchimp: '', flag: '', native: 'ᨅᨔ ᨕᨘᨁᨗ', english: 'Buginese', notes: ''}, {browser: 'bxr', mailchimp: '', flag: '', native: 'буряад', english: 'Buryat (Russia)', notes: ''}, {browser: 'ca', mailchimp: 'ca', flag: '', native: 'català', english: 'Catalan', notes: ''}, {browser: 'cbk_zam', mailchimp: '', flag: '', native: 'Chavacano de Zamboanga', english: 'Zamboanga Chavacano', notes: ''}, {browser: 'cdo', mailchimp: '', flag: '', native: 'Mìng-dĕ̤ng-ngṳ̄', english: 'Min Dong', notes: ''}, {browser: 'ce', mailchimp: '', flag: '', native: 'нохчийн', english: 'Chechen', notes: ''}, {browser: 'ceb', mailchimp: '', flag: '', native: 'Cebuano', english: 'Cebuano', notes: ''}, {browser: 'ch', mailchimp: '', flag: '', native: 'Chamoru', english: 'Chamorro', notes: ''}, {browser: 'cho', mailchimp: '', flag: '', native: 'Choctaw', english: 'Choctaw', notes: ''}, {browser: 'chr', mailchimp: '', flag: '', native: 'ᏣᎳᎩ', english: 'Cherokee', notes: ''}, {browser: 'chy', mailchimp: '', flag: '', native: 'Tsetsêhestâhese', english: 'Cheyenne', notes: ''}, {browser: 'ckb', mailchimp: '', flag: '', native: 'کوردی', english: 'Sorani', notes: 'The name actually says "Kurdi" (Kurdish).'}, {browser: 'co', mailchimp: '', flag: '', native: 'corsu', english: 'Corsican', notes: ''}, {browser: 'cps', mailchimp: '', flag: '', native: 'Capiceño', english: 'Capiznon', notes: ''}, {browser: 'cr', mailchimp: '', flag: '', native: 'Nēhiyawēwin / ᓀᐦᐃᔭᐍᐏᐣ', english: 'Cree', notes: ''}, {browser: 'crh', mailchimp: '', flag: '', native: 'qırımtatarca', english: 'Crimean Tatar', notes: ' (multiple scripts - defaults to Latin)'}, {browser: 'crh_latn', mailchimp: '', flag: '', native: '"qırımtatarca (Latin)\xE2\x80\x8E"', english: 'Crimean Tatar (Latin)', notes: ''}, {browser: 'crh_cyrl', mailchimp: '', flag: '', native: '"къырымтатарджа (Кирилл)\xE2\x80\x8E"',english: 'Crimean Tatar (Cyrillic)', notes: ''}, {browser: 'cs', mailchimp: 'cs', flag: '', native: 'čeština', english: 'Czech', notes: ''}, {browser: 'csb', mailchimp: '', flag: '', native: 'kaszëbsczi', english: 'Cassubian', notes: ''}, {browser: 'cu', mailchimp: '', flag: '', native: 'словѣньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ', english: 'Old Church Slavonic (ancient language)', notes: ''}, {browser: 'cv', mailchimp: '', flag: '', native: 'Чӑвашла', english: 'Chuvash', notes: ''}, {browser: 'cy', mailchimp: '', flag: '', native: 'Cymraeg', english: 'Welsh', notes: ''}, {browser: 'da', mailchimp: 'da', flag: '', native: 'Dansk', english: 'Danish', notes: ''}, {browser: 'de', mailchimp: 'de', flag: 'de', native: 'Deutsch', english: 'German', notes: ''}, {browser: 'de_at', mailchimp: 'de', flag: 'de', native: 'Österreichisches Deutsch', english: 'German (Austria)', notes: ''}, {browser: 'de_ch', mailchimp: 'de', flag: 'ch', native: 'Schweizer Hochdeutsch', english: 'German (Switzerland)', notes: ''}, {browser: 'de_li', mailchimp: 'de', flag: 'li', native: 'Liechtenstein Deutsch', english: 'German (Liechtenstein)', notes: ''}, {browser: 'de_lu', mailchimp: 'de', flag: 'lu', native: 'Luxembourg Deutsch', english: 'German (Luxembourg)', notes: ''}, {browser: 'de_de', mailchimp: 'de', flag: 'de', native: '"Deutsch (Sie-Form)\xE2\x80\x8E"', english: 'German (Germany)', notes: 'formal address ("Sie")'}, {browser: 'diq', mailchimp: '', flag: '', native: 'Zazaki', english: 'Zazaki', notes: ''}, {browser: 'dsb', mailchimp: '', flag: '', native: 'Dolnoserbski', english: 'Lower Sorbian', notes: ''}, {browser: 'dtp', mailchimp: '', flag: '', native: 'Dusun Bundu-liwan', english: 'Central Dusun', notes: ''}, {browser: 'dv', mailchimp: '', flag: '', native: 'ދިވެހިބަސް', english: 'Dhivehi', notes: ''}, {browser: 'dz', mailchimp: '', flag: '', native: 'ཇོང་ཁ', english: 'Dzongkha (Bhutan)', notes: ''}, {browser: 'ee', mailchimp: '', flag: '', native: 'Eʋegbe', english: 'Éwé', notes: ''}, {browser: 'egl', mailchimp: '', flag: '', native: 'Emiliàn', english: 'Emilian', notes: ''}, {browser: 'el', mailchimp: 'el', flag: '', native: 'Ελληνικά', english: 'Greek', notes: ''}, {browser: 'eml', mailchimp: '', flag: '', native: 'Emiliàn e rumagnòl', english: 'Emiliano-Romagnolo / Sammarinese', notes: ''}, {browser: 'en', mailchimp: 'en', flag: 'gb', native: 'English', english: 'English', notes: ''}, {browser: 'en_au', mailchimp: 'en', flag: '', native: 'Australian English', english: 'English (Australia)', notes: ''}, {browser: 'en_bz', mailchimp: 'en', flag: '', native: 'English', english: 'English (Belize)', notes: ''}, {browser: 'en_ca', mailchimp: 'en', flag: '', native: 'Canadian English', english: 'English (Canada)', notes: ''}, {browser: 'en_ie', mailchimp: 'en', flag: '', native: 'English', english: 'English (Ireland)', notes: ''}, {browser: 'en_jm', mailchimp: 'en', flag: '', native: 'English', english: 'English (Jamaica)', notes: ''}, {browser: 'en_nz', mailchimp: 'en', flag: '', native: 'English', english: 'English (New Zealand)', notes: ''}, {browser: 'en_ph', mailchimp: 'en', flag: '', native: 'English', english: 'English (Philippines)', notes: ''}, {browser: 'en_za', mailchimp: 'en', flag: '', native: 'English', english: 'English (South Africa)', notes: ''}, {browser: 'en_tt', mailchimp: 'en', flag: '', native: 'English', english: 'English (Trinidad & Tobago)', notes: ''}, {browser: 'en_gb', mailchimp: 'en', flag: 'gb', native: 'British English', english: 'English (United Kingdom)', notes: ''}, {browser: 'en_us', mailchimp: 'en', flag: 'us', native: 'American English', english: 'English (United States)', notes: ''}, {browser: 'en_zw', mailchimp: 'en', flag: '', native: 'Zimbabwe English', english: 'English (Zimbabwe)', notes: ''}, {browser: 'eo', mailchimp: '', flag: '', native: 'Esperanto', english: 'Esperanto', notes: ''}, {browser: 'es', mailchimp: 'es_ES', flag: 'es', native: 'Español', english: 'Spanish', notes: ''}, {browser: 'es-ar', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Argentina)', notes: ''}, {browser: 'es-bo', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Bolivia)', notes: ''}, {browser: 'es-cl', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Chile)', notes: ''}, {browser: 'es-co', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Colombia)', notes: ''}, {browser: 'es-cr', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Costa Rica)', notes: ''}, {browser: 'es-do', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Dominican Republic)',notes: ''}, {browser: 'es-ec', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Ecuador)', notes: ''}, {browser: 'es-sv', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (El Salvador)', notes: ''}, {browser: 'es-gt', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Guatemala)', notes: ''}, {browser: 'es-hn', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Honduras)', notes: ''}, {browser: 'es-mx', mailchimp: 'es', flag: 'es', native: '', english: 'Spanish (Mexico)', notes: ''}, {browser: 'es-ni', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Nicaragua)', notes: ''}, {browser: 'es-pa', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Panama)', notes: ''}, {browser: 'es-py', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Paraguay)', notes: ''}, {browser: 'es-pe', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Peru)', notes: ''}, {browser: 'es-pr', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Puerto Rico)', notes: ''}, {browser: 'es-es', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Spain)', notes: ''}, {browser: 'es-uy', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Uruguay)', notes: ''}, {browser: 'es-ve', mailchimp: 'es_ES', flag: 'es', native: '', english: 'Spanish (Venezuela)', notes: ''}, {browser: 'et', mailchimp: 'et', flag: '', native: 'Eesti', english: 'Estonian', notes: ''}, {browser: 'eu', mailchimp: '', flag: '', native: 'Euskara', english: 'Basque', notes: ''}, {browser: 'ext', mailchimp: '', flag: '', native: 'Estremeñu', english: 'Extremaduran', notes: ''}, {browser: 'fa', mailchimp: 'fa', flag: '', native: 'فارسی', english: 'Persian/Farsi', notes: ''}, {browser: 'fa_ir', mailchimp: 'fa', flag: '', native: '', english: 'Persian/Iran', notes: ''}, {browser: 'ff', mailchimp: '', flag: '', native: 'Fulfulde', english: 'Fulfulde, Maasina', notes: ''}, {browser: 'fi', mailchimp: 'fi', flag: '', native: 'Suomi', english: 'Finnish', notes: ''}, {browser: 'fit', mailchimp: '', flag: '', native: 'Meänkieli', english: 'Tornedalen Finnish', notes: ''}, {browser: 'fiu_vro', mailchimp: '', flag: '', native: 'Võro', english: 'Võro', notes: ' (deprecated code, \'vro\' in ISO 639-3 since 2009-01-16)'}, {browser: 'fj', mailchimp: '', flag: '', native: 'Na Vosa Vakaviti', english: 'Fijian', notes: ''}, {browser: 'fo', mailchimp: '', flag: '', native: 'Føroyskt', english: 'Faroese', notes: ''}, {browser: 'fr', mailchimp: 'fr', flag: 'fr', native: 'Français', english: 'French', notes: ''}, {browser: 'fr_be', mailchimp: 'fr', flag: 'be', native: 'Français (Belgique)', english: 'French (Belgium)', notes: ''}, {browser: 'fr_ca', mailchimp: 'fr_CA', flag: 'ca', native: 'Français (Canada)', english: 'French (Canada)', notes: ''}, {browser: 'fr_fr', mailchimp: 'fr', flag: 'fr', native: 'Français (France)', english: 'French (France)', notes: ''}, {browser: 'fr_lu', mailchimp: 'fr', flag: 'lu', native: 'Français (Luxembourg)', english: 'French (Luxembourg)', notes: ''}, {browser: 'fr_mc', mailchimp: 'fr', flag: 'mc', native: 'Français (Monaco)', english: 'French (Monaco)', notes: ''}, {browser: 'fr_ch', mailchimp: 'fr', flag: 'ch', native: 'Français (Suisse)', english: 'French (Switzerland)', notes: ''}, {browser: 'frc', mailchimp: '', flag: '', native: 'Français cadien', english: 'Cajun French', notes: ''}, {browser: 'frp', mailchimp: '', flag: '', native: 'Arpetan', english: 'Franco-Provençal/Arpitan', notes: ''}, {browser: 'frr', mailchimp: '', flag: '', native: 'Nordfriisk', english: 'North Frisian', notes: ''}, {browser: 'fur', mailchimp: '', flag: '', native: 'Furlan', english: 'Friulian', notes: ''}, {browser: 'fy', mailchimp: '', flag: '', native: 'Frysk', english: 'Frisian', notes: ''}, {browser: 'ga', mailchimp: 'ga', flag: '', native: 'Gaeilge', english: 'Irish', notes: ''}, {browser: 'gag', mailchimp: '', flag: '', native: 'Gagauz', english: 'Gagauz', notes: ''}, {browser: 'gan', mailchimp: '', flag: '', native: '贛語', english: 'Gan', notes: ' (multiple scripts - defaults to Traditional)'}, {browser: 'gan_hans', mailchimp: '', flag: '', native: '"赣语(简体)\xE2\x80\x8E"', english: 'Gan (Simplified Han)', notes: ''}, {browser: 'gan_hant', mailchimp: '', flag: '', native: '"贛語(繁體)\xE2\x80\x8E"', english: 'Gan (Traditional Han)', notes: ''}, {browser: 'gd', mailchimp: 'ga', flag: '', native: 'Gàidhlig', english: 'Gaelic (Scots)', notes: ''}, {browser: 'gd_ie', mailchimp: 'ga', flag: '', native: '', english: 'Gaelic (Irish)', notes: ''}, {browser: 'gl', mailchimp: '', flag: '', native: 'Galego', english: 'Galician', notes: ''}, {browser: 'glk', mailchimp: '', flag: '', native: 'گیلکی', english: 'Gilaki', notes: ''}, {browser: 'gn', mailchimp: '', flag: '', native: 'Avañe\'ẽ', english: 'Guaraní, Paraguayan', notes: ''}, {browser: 'gom_latn', mailchimp: '', flag: '', native: 'Konknni', english: 'Goan Konkani', notes: '(Latin script)'}, {browser: 'got', mailchimp: '', flag: '', native: '𐌲𐌿𐍄𐌹𐍃𐌺', english: 'Gothic', notes: ''}, {browser: 'grc', mailchimp: '', flag: '', native: 'Ἀρχαία ἑλληνικὴ', english: 'Ancient Greek', notes: ''}, {browser: 'gsw', mailchimp: '', flag: '', native: 'Alemannisch', english: 'Alemannic', notes: ''}, {browser: 'gu', mailchimp: '', flag: '', native: 'ગુજરાતી', english: 'Gujarati', notes: ''}, {browser: 'gv', mailchimp: '', flag: '', native: 'Gaelg', english: 'Manx', notes: ''}, {browser: 'ha', mailchimp: '', flag: '', native: 'Hausa', english: 'Hausa', notes: ''}, {browser: 'hak', mailchimp: '', flag: '', native: '客家語/Hak-kâ-ngî', english: 'Hakka', notes: ''}, {browser: 'haw', mailchimp: '', flag: '', native: 'Hawai`i', english: 'Hawaiian', notes: ''}, {browser: 'he', mailchimp: 'he', flag: '', native: 'עברית', english: 'Hebrew', notes: ''}, {browser: 'hi', mailchimp: 'hi', flag: '', native: 'हिन्दी', english: 'Hindi', notes: ''}, {browser: 'hif', mailchimp: '', flag: '', native: 'Fiji Hindi', english: 'Fijian Hindi', notes: ' (multiple scripts - defaults to Latin)'}, {browser: 'hif_latn', mailchimp: '', flag: '', native: 'Fiji Hindi', english: 'Fiji Hindi', notes: ' (latin)'}, {browser: 'hil', mailchimp: '', flag: '', native: 'Ilonggo', english: 'Hiligaynon', notes: ''}, {browser: 'ho', mailchimp: '', flag: '', native: 'Hiri Motu', english: 'Hiri Motu', notes: ''}, {browser: 'hr', mailchimp: 'hr', flag: '', native: 'hrvatski', english: 'Croatian', notes: ''}, {browser: 'hsb', mailchimp: '', flag: '', native: 'hornjoserbsce', english: 'Upper Sorbian', notes: ''}, {browser: 'ht', mailchimp: '', flag: '', native: 'Kreyòl ayisyen', english: 'Haitian Creole French', notes: ''}, {browser: 'hu', mailchimp: 'hu', flag: '', native: 'magyar', english: 'Hungarian', notes: ''}, {browser: 'hy', mailchimp: '', flag: '', native: 'Հայերեն', english: 'Armenian', notes: ''}, {browser: 'hz', mailchimp: '', flag: '', native: 'Otsiherero', english: 'Herero', notes: ''}, {browser: 'ia', mailchimp: '', flag: '', native: 'interlingua', english: 'Interlingua (IALA)', notes: ''}, {browser: 'id', mailchimp: 'id', flag: '', native: 'Bahasa Indonesia', english: 'Indonesian', notes: ''}, {browser: 'ie', mailchimp: '', flag: '', native: 'Interlingue', english: 'Interlingue (Occidental)', notes: ''}, {browser: 'ig', mailchimp: '', flag: '', native: 'Igbo', english: 'Igbo', notes: ''}, {browser: 'ii', mailchimp: '', flag: '', native: 'ꆇꉙ', english: 'Sichuan Yi', notes: ''}, {browser: 'ik', mailchimp: '', flag: '', native: 'Iñupiak', english: 'Inupiak', notes: '(Inupiatun, Northwest Alaska / Inupiatun, North Alaskan)'}, {browser: 'ike_cans', mailchimp: '', flag: '', native: 'ᐃᓄᒃᑎᑐᑦ', english: 'Inuktitut, Eastern Canadian', notes: '(Unified Canadian Aboriginal Syllabics)'}, {browser: 'ike_latn', mailchimp: '', flag: '', native: 'inuktitut', english: 'Inuktitut, Eastern Canadian', notes: '(Latin script)'}, {browser: 'ilo', mailchimp: '', flag: '', native: 'Ilokano', english: 'Ilokano', notes: ''}, {browser: 'inh', mailchimp: '', flag: '', native: 'ГӀалгӀай', english: 'Ingush', notes: ''}, {browser: 'io', mailchimp: '', flag: '', native: 'Ido', english: 'Ido', notes: ''}, {browser: 'is', mailchimp: 'is', flag: '', native: 'íslenska', english: 'Icelandic', notes: ''}, {browser: 'it', mailchimp: 'it', flag: 'it', native: 'italiano', english: 'Italian', notes: ''}, {browser: 'it-ch', mailchimp: 'it', flag: '', native: '', english: 'Italian (Switzerland)', notes: ''}, {browser: 'iu', mailchimp: '', flag: '', native: 'ᐃᓄᒃᑎᑐᑦ/inuktitut', english: 'Inuktitut', notes: '(macro language, see ike/ikt, falls back to ike-cans)'}, {browser: 'ja', mailchimp: 'ja', flag: 'jp', native: '日本語', english: 'Japanese', notes: ''}, {browser: "ja-jp", mailchimp: "ja", flag: 'jp', native: "日本語(関西)", english: 'Japanese (Kansai)', notes: ''}, {browser: 'jam', mailchimp: '', flag: '', native: 'Patois', english: 'Jamaican Creole English', notes: ''}, {browser: 'jbo', mailchimp: '', flag: '', native: 'Lojban', english: 'Lojban', notes: ''}, {browser: 'jut', mailchimp: '', flag: '', native: 'jysk', english: 'Jutish / Jutlandic', notes: ''}, {browser: 'jv', mailchimp: '', flag: '', native: 'Basa Jawa', english: 'Javanese', notes: ''}, {browser: 'ji', mailchimp: '', flag: '', native: '', english: 'Yiddish', notes: ''}, {browser: 'ka', mailchimp: '', flag: '', native: 'ქართული', english: 'Georgian', notes: ''}, {browser: 'kaa', mailchimp: '', flag: '', native: 'Qaraqalpaqsha', english: 'Karakalpak', notes: ''}, {browser: 'kab', mailchimp: '', flag: '', native: 'Taqbaylit', english: 'Kabyle', notes: ''}, {browser: 'kbd', mailchimp: '', flag: '', native: 'Адыгэбзэ', english: 'Kabardian', notes: ''}, {browser: 'kbd_cyrl', mailchimp: '', flag: '', native: 'Адыгэбзэ', english: 'Kabardian (Cyrillic)', notes: ''}, {browser: 'kg', mailchimp: '', flag: '', native: 'Kongo', english: 'Kongo', notes: '(FIXME!) should probaly be KiKongo or KiKoongo'}, {browser: 'khw', mailchimp: '', flag: '', native: 'کھوار', english: 'Khowar', notes: ''}, {browser: 'ki', mailchimp: '', flag: '', native: 'Gĩkũyũ', english: 'Gikuyu', notes: ''}, {browser: 'kiu', mailchimp: '', flag: '', native: 'Kırmancki', english: 'Kirmanjki', notes: ''}, {browser: 'kj', mailchimp: '', flag: '', native: 'Kwanyama', english: 'Kwanyama', notes: ''}, {browser: 'kk', mailchimp: '', flag: '', native: 'қазақша', english: 'Kazakh', notes: '(multiple scripts - defaults to Cyrillic)'}, {browser: 'kk_arab', mailchimp: '', flag: '', native: '"قازاقشا (تٴوتە)\xE2\x80\x8F"', english: 'Kazakh Arabic', notes: ''}, {browser: 'kk_cyrl', mailchimp: '', flag: '', native: '"қазақша (кирил)\xE2\x80\x8E"', english: 'Kazakh Cyrillic', notes: ''}, {browser: 'kk_latn', mailchimp: '', flag: '', native: '"qazaqşa (latın)\xE2\x80\x8E"', english: 'Kazakh Latin', notes: ''}, {browser: 'kk_cn', mailchimp: '', flag: '', native: '"قازاقشا (جۇنگو)\xE2\x80\x8F"', english: 'Kazakh (China)', notes: ''}, {browser: 'kk_kz', mailchimp: '', flag: '', native: '"қазақша (Қазақстан)\xE2\x80\x8E"',english: 'Kazakh (Kazakhstan)', notes: ''}, {browser: 'kk_tr', mailchimp: '', flag: '', native: '"qazaqşa (Türkïya)\xE2\x80\x8E"', english: 'Kazakh (Turkey)', notes: ''}, {browser: 'kl', mailchimp: '', flag: '', native: 'kalaallisut', english: 'Inuktitut, Greenlandic/Greenlandic/Kalaallisut (kal)', notes: ''}, {browser: 'km', mailchimp: 'km', flag: '', native: 'ភាសាខ្មែរ', english: 'Khmer, Central', notes: ''}, {browser: 'kn', mailchimp: '', flag: '', native: 'ಕನ್ನಡ', english: 'Kannada', notes: ''}, {browser: 'ko', mailchimp: 'ko', flag: '', native: '한국어', english: 'Korean', notes: ''}, {browser: 'ko_kp', mailchimp: 'ko', flag: '', native: '한국어 (조선)', english: 'Korean (North Korea)', notes: ''}, {browser: 'ko_kr', mailchimp: 'ko', flag: '', native: '', english: 'Korean (South Korea)', notes: ''}, {browser: 'koi', mailchimp: '', flag: '', native: 'Перем Коми', english: 'Komi-Permyak', notes: ''}, {browser: 'kr', mailchimp: '', flag: '', native: 'Kanuri', english: 'Kanuri, Central', notes: ''}, {browser: 'krc', mailchimp: '', flag: '', native: 'къарачай-малкъар', english: 'Karachay-Balkar', notes: ''}, {browser: 'kri', mailchimp: '', flag: '', native: 'Krio', english: 'Krio', notes: ''}, {browser: 'krj', mailchimp: '', flag: '', native: 'Kinaray-a', english: 'Kinaray-a', notes: ''}, {browser: 'ks', mailchimp: '', flag: '', native: 'कॉशुर / کٲشُر', english: 'Kashmiri', notes: '(multiple scripts - defaults to Perso-Arabic)'}, {browser: 'ks_arab', mailchimp: '', flag: '', native: 'کٲشُر', english: 'Kashmiri', notes: '(Perso-Arabic script)'}, {browser: 'ks_deva', mailchimp: '', flag: '', native: 'कॉशुर', english: 'Kashmiri', notes: '(Devanagari script)'}, {browser: 'ksh', mailchimp: '', flag: '', native: 'Ripoarisch', english: 'Ripuarian', notes: ''}, {browser: 'ku', mailchimp: '', flag: '', native: 'Kurdî', english: 'Kurdish', notes: '(multiple scripts - defaults to Latin)'}, {browser: 'ku_latn', mailchimp: '', flag: '', native: '"Kurdî (latînî)\xE2\x80\x8E"', english: 'Northern Kurdish', notes: '(Latin script)'}, {browser: 'ku_arab', mailchimp: '', flag: '', native: '"كوردي (عەرەبی)\xE2\x80\x8F"', english: 'Northern Kurdish', notes: '(Arabic script) (falls back to ckb)'}, {browser: 'kv', mailchimp: '', flag: '', native: 'коми', english: 'Komi-Zyrian', notes: '(Cyrillic is common script but also written in Latin script)'}, {browser: 'kw', mailchimp: '', flag: '', native: 'kernowek', english: 'Cornish', notes: ''}, {browser: 'ky', mailchimp: '', flag: '', native: 'Кыргызча', english: 'Kirghiz', notes: ''}, {browser: 'la', mailchimp: '', flag: '', native: 'Latina', english: 'Latin', notes: ''}, {browser: 'lad', mailchimp: '', flag: '', native: 'Ladino', english: 'Ladino', notes: ''}, {browser: 'lb', mailchimp: '', flag: '', native: 'Lëtzebuergesch', english: 'Luxemburguish', notes: ''}, {browser: 'lbe', mailchimp: '', flag: '', native: 'лакку', english: 'Lak', notes: ''}, {browser: 'lez', mailchimp: '', flag: '', native: 'лезги', english: 'Lezgi', notes: ''}, {browser: 'lfn', mailchimp: '', flag: '', native: 'Lingua Franca Nova', english: 'Lingua Franca Nova', notes: ''}, {browser: 'lg', mailchimp: '', flag: '', native: 'Luganda', english: 'Ganda', notes: ''}, {browser: 'li', mailchimp: '', flag: '', native: 'Limburgs', english: 'Limburgian', notes: ''}, {browser: 'lij', mailchimp: '', flag: '', native: 'Ligure', english: 'Ligurian', notes: ''}, {browser: 'liv', mailchimp: '', flag: '', native: 'Līvõ kēļ', english: 'Livonian', notes: ''}, {browser: 'lmo', mailchimp: '', flag: '', native: 'lumbaart', english: 'Lombard', notes: ''}, {browser: 'ln', mailchimp: '', flag: '', native: 'lingála', english: 'Lingala', notes: ''}, {browser: 'lo', mailchimp: '', flag: '', native: 'ລາວ', english: 'Laotian', notes: ''}, {browser: 'lrc', mailchimp: '', flag: '', native: 'لوری', english: 'Northern Luri', notes: ''}, {browser: 'loz', mailchimp: '', flag: '', native: 'Silozi', english: 'Lozi', notes: ''}, {browser: 'lt', mailchimp: 'lt', flag: '', native: 'lietuvių', english: 'Lithuanian', notes: ''}, {browser: 'ltg', mailchimp: '', flag: '', native: 'latgaļu', english: 'Latgalian', notes: ''}, {browser: 'lus', mailchimp: '', flag: '', native: 'Mizo ţawng', english: 'Mizo/Lushai', notes: ''}, {browser: 'lv', mailchimp: 'lv', flag: '', native: 'latviešu', english: 'Latvian', notes: ''}, {browser: 'lzh', mailchimp: '', flag: '', native: '文言', english: 'Literary Chinese', notes: ''}, {browser: 'lzz', mailchimp: '', flag: '', native: 'Lazuri', english: 'Laz', notes: ''}, {browser: 'mai', mailchimp: '', flag: '', native: 'मैथिली', english: 'Maithili', notes: ''}, {browser: 'map_bms', mailchimp: '', flag: '', native: 'Basa Banyumasan', english: 'Banyumasan', notes: ''}, {browser: 'mdf', mailchimp: '', flag: '', native: 'мокшень', english: 'Moksha', notes: ''}, {browser: 'mg', mailchimp: '', flag: '', native: 'Malagasy', english: 'Malagasy', notes: ''}, {browser: 'mh', mailchimp: '', flag: '', native: 'Ebon', english: 'Marshallese', notes: ''}, {browser: 'mhr', mailchimp: '', flag: '', native: 'олык марий', english: 'Eastern Mari', notes: ''}, {browser: 'mi', mailchimp: '', flag: '', native: 'Māori', english: 'Maori', notes: ''}, {browser: 'min', mailchimp: '', flag: '', native: 'Baso Minangkabau', english: 'Minangkabau', notes: ''}, {browser: 'mk', mailchimp: 'mk', flag: '', native: 'македонски', english: 'Macedonian', notes: ''}, {browser: 'ml', mailchimp: '', flag: '', native: 'മലയാളം', english: 'Malayalam', notes: ''}, {browser: 'mn', mailchimp: '', flag: '', native: 'монгол', english: 'Halh Mongolian (Cyrillic)', notes: '(ISO 639-3: khk)'}, {browser: 'mo', mailchimp: '', flag: '', native: 'молдовеняскэ', english: 'Moldovan', notes: 'deprecated'}, {browser: 'mr', mailchimp: '', flag: '', native: 'मराठी', english: 'Marathi', notes: ''}, {browser: 'mrj', mailchimp: '', flag: '', native: 'кырык мары', english: 'Hill Mari', notes: ''}, {browser: 'ms', mailchimp: 'ms', flag: '', native: 'Bahasa Melayu', english: 'Malay', notes: ''}, {browser: 'mt', mailchimp: 'mt', flag: '', native: 'Malti', english: 'Maltese', notes: ''}, {browser: 'mus', mailchimp: '', flag: '', native: 'Mvskoke', english: 'Muskogee/Creek', notes: ''}, {browser: 'mwl', mailchimp: '', flag: '', native: 'Mirandés', english: 'Mirandese', notes: ''}, {browser: 'my', mailchimp: '', flag: '', native: 'မြန်မာဘာသာ', english: 'Burmese', notes: ''}, {browser: 'myv', mailchimp: '', flag: '', native: 'эрзянь', english: 'Erzya', notes: ''}, {browser: 'mzn', mailchimp: '', flag: '', native: 'مازِرونی', english: 'Mazanderani', notes: ''}, {browser: 'na', mailchimp: '', flag: '', native: 'Dorerin Naoero', english: 'Nauruan', notes: ''}, {browser: 'nah', mailchimp: '', flag: '', native: 'Nāhuatl', english: 'Nahuatl', notes: '(not in ISO 639-3)'}, {browser: 'nan', mailchimp: '', flag: '', native: 'Bân-lâm-gú', english: 'Min-nan', notes: ''}, {browser: 'nap', mailchimp: '', flag: '', native: 'Napulitano', english: 'Neapolitan', notes: ''}, {browser: 'nb', mailchimp: '', flag: '', native: '"norsk bokmål', english: 'Norwegian (Bokmal)', notes: ''}, {browser: 'nds', mailchimp: '', flag: '', native: 'Plattdüütsch', english: 'Low German', notes: 'or Low Saxon'}, {browser: 'nds_nl', mailchimp: '', flag: '', native: 'Nedersaksies', english: 'Nedersaksisch', notes: 'Dutch Low Saxon'}, {browser: 'ne', mailchimp: '', flag: '', native: 'नेपाली', english: 'Nepali', notes: ''}, {browser: 'new', mailchimp: '', flag: '', native: 'नेपाल भाषा', english: 'Newar / Nepal Bhasha', notes: ''}, {browser: 'ng', mailchimp: '', flag: '', native: 'Oshiwambo', english: 'Ndonga', notes: ''}, {browser: 'niu', mailchimp: '', flag: '', native: 'Niuē', english: 'Niuean', notes: ''}, {browser: 'nl', mailchimp: 'nl', flag: '', native: 'Nederlands', english: 'Dutch', notes: ''}, // {browser: 'nl_informal',mailchimp: 'nl', flag: '', native: '"Nederlands (informeel)\xE2\x80\x8E"', english: 'Dutch', notes: 'informal address ("je")'}, {browser: 'nl_be', mailchimp: 'nl', flag: '', native: '', english: 'Dutch (Belgian)', notes: ''}, {browser: 'no', mailchimp: 'no', flag: '', native: '"Norsk"', english: 'Norwegian', notes: ''}, {browser: 'nb', mailchimp: 'no', flag: '', native: '"Norsk Bokmål"', english: 'Norwegian (Bokmal)', notes: ''}, {browser: 'nn', mailchimp: 'ny', flag: '', native: '"Norsk Nynorsk"', english: 'Norwegian (Nynorsk)', notes: ''}, {browser: 'nov', mailchimp: '', flag: '', native: 'Novial', english: 'Novial', notes: ''}, {browser: 'nrm', mailchimp: '', flag: '', native: 'Nouormand', english: 'Norman', notes: ''}, {browser: 'nso', mailchimp: '', flag: '', native: 'Sesotho sa Leboa', english: 'Northern Sotho', notes: ''}, {browser: 'nv', mailchimp: '', flag: '', native: 'Diné bizaad', english: 'Navajo', notes: ''}, {browser: 'ny', mailchimp: '', flag: '', native: 'Chi-Chewa', english: 'Chichewa', notes: ''}, {browser: 'oc', mailchimp: '', flag: '', native: 'occitan', english: 'Occitan', notes: ''}, {browser: 'om', mailchimp: '', flag: '', native: 'Oromoo', english: 'Oromo', notes: ''}, {browser: 'or', mailchimp: '', flag: '', native: 'ଓଡ଼ିଆ', english: 'Oriya', notes: ''}, {browser: 'os', mailchimp: '', flag: '', native: 'Ирон', english: 'Ossetic, bug 29091', notes: ''}, {browser: 'pa', mailchimp: '', flag: '', native: 'ਪੰਜਾਬੀ', english: 'Punjabi', notes: ' (Gurmukhi script) (pan)'}, {browser: 'pa_in', mailchimp: '', flag: '', native: '', english: 'Punjabi (India)', notes: ' (Gurmukhi script) (pan)'}, {browser: 'pa_pk', mailchimp: '', flag: '', native: '', english: 'Punjabi (Pakistan)', notes: ' (Gurmukhi script) (pan)'}, {browser: 'pag', mailchimp: '', flag: '', native: 'Pangasinan', english: 'Pangasinan', notes: ''}, {browser: 'pam', mailchimp: '', flag: '', native: 'Kapampangan', english: 'Pampanga', notes: ''}, {browser: 'pap', mailchimp: '', flag: '', native: 'Papiamentu', english: 'Papiamentu', notes: ''}, {browser: 'pcd', mailchimp: '', flag: '', native: 'Picard', english: 'Picard', notes: ''}, {browser: 'pdc', mailchimp: '', flag: '', native: 'Deitsch', english: 'Pennsylvania German', notes: ''}, {browser: 'pdt', mailchimp: '', flag: '', native: 'Plautdietsch', english: 'Plautdietsch/Mennonite Low German', notes: ''}, {browser: 'pfl', mailchimp: '', flag: '', native: 'Pälzisch', english: 'Palatinate German', notes: ''}, {browser: 'pi', mailchimp: '', flag: '', native: 'पालि', english: 'Pali', notes: ''}, {browser: 'pih', mailchimp: '', flag: '', native: 'Norfuk / Pitkern', english: 'Norfuk/Pitcairn/Norfolk', notes: ''}, {browser: 'pl', mailchimp: 'pl', flag: '', native: 'polski', english: 'Polish', notes: ''}, {browser: 'pms', mailchimp: '', flag: '', native: 'Piemontèis', english: 'Piedmontese', notes: ''}, {browser: 'pnb', mailchimp: '', flag: '', native: 'پنجابی', english: 'Western Punjabi', notes: ''}, {browser: 'pnt', mailchimp: '', flag: '', native: 'Ποντιακά', english: 'Pontic/Pontic Greek', notes: ''}, {browser: 'prg', mailchimp: '', flag: '', native: 'Prūsiskan', english: 'Prussian', notes: ''}, {browser: 'ps', mailchimp: '', flag: '', native: 'پښتو', english: 'Pashto, Northern/Paktu/Pakhtu/Pakhtoo/Afghan/Pakhto/Pashtu/Pushto/Yusufzai Pashto', notes: ''}, {browser: 'pt', mailchimp: 'pt_PT', flag: '', native: 'português', english: 'Portuguese', notes: ''}, {browser: 'pt_br', mailchimp: 'pt', flag: '', native: 'português do Brasil', english: 'Brazilian Portuguese', notes: ''}, {browser: 'qu', mailchimp: '', flag: '', native: 'Runa Simi', english: 'Southern Quechua', notes: ''}, {browser: 'qug', mailchimp: '', flag: '', native: 'Runa shimi', english: 'Kichwa/Northern Quechua', notes: '(temporarily used until Kichwa has its own)'}, {browser: 'rgn', mailchimp: '', flag: '', native: 'Rumagnôl', english: 'Romagnol', notes: ''}, {browser: 'rif', mailchimp: '', flag: '', native: 'Tarifit', english: 'Tarifit', notes: ''}, {browser: 'rm', mailchimp: '', flag: '', native: 'rumantsch', english: 'Rhaeto-Romanic', notes: ''}, {browser: 'rmy', mailchimp: '', flag: '', native: 'Romani', english: 'Vlax Romany', notes: ''}, {browser: 'rn', mailchimp: '', flag: '', native: 'Kirundi', english: 'Rundi/Kirundi/Urundi', notes: ''}, {browser: 'ro', mailchimp: 'ro', flag: 'ro', native: 'Română', english: 'Romanian', notes: ''}, {browser: 'ro_mo', mailchimp: 'ro', flag: '', native: '', english: 'Romanian (Moldavia)', notes: ''}, {browser: 'roa_rup', mailchimp: '', flag: '', native: 'Armãneashce', english: 'Aromanian', notes: 'deprecated code, \'rup\' exists in ISO 693-3)'}, {browser: 'roa_tara', mailchimp: '', flag: '', native: 'tarandíne', english: 'Tarantino', notes: ''}, {browser: 'ru', mailchimp: 'ru', flag: 'ru', native: 'русский', english: 'Russian', notes: ''}, {browser: 'ru_mo', mailchimp: 'ru', flag: '', native: '', english: 'Russian (Moldavia)', notes: ''}, {browser: 'rue', mailchimp: '', flag: '', native: 'русиньскый', english: 'Rusyn', notes: ''}, {browser: 'rup', mailchimp: '', flag: '', native: 'Armãneashce', english: 'Aromanian', notes: ''}, {browser: 'ruq', mailchimp: '', flag: '', native: 'Vlăheşte', english: 'Megleno-Romanian', notes: '(multiple scripts - defaults to Latin)'}, {browser: 'ruq_cyrl', mailchimp: '', flag: '', native: 'Влахесте', english: 'Megleno-Romanian', notes: '(Cyrillic script)'}, {browser: 'ruq_grek', mailchimp: '', flag: '', native: 'Βλαεστε', english: 'Megleno-Romanian', notes: '(Greek script)'}, {browser: 'ruq_latn', mailchimp: '', flag: '', native: 'Vlăheşte', english: 'Megleno-Romanian', notes: '(Latin script)'}, {browser: 'rw', mailchimp: '', flag: '', native: 'Kinyarwanda', english: 'Kinyarwanda', notes: 'should possibly be Kinyarwandi'}, {browser: 'sa', mailchimp: '', flag: '', native: 'संस्कृतम्', english: 'Sanskrit', notes: ''}, {browser: 'sah', mailchimp: '', flag: '', native: 'саха тыла', english: 'Sakha', notes: ''}, {browser: 'sat', mailchimp: '', flag: '', native: 'Santali', english: 'Santali', notes: ''}, {browser: 'sb', mailchimp: '', flag: '', native: '', english: 'Sorbian', notes: ''}, {browser: 'sc', mailchimp: '', flag: '', native: 'sardu', english: 'Sardinian', notes: ''}, {browser: 'scn', mailchimp: '', flag: '', native: 'sicilianu', english: 'Sicilian', notes: ''}, {browser: 'sco', mailchimp: '', flag: '', native: 'Scots', english: 'Scots', notes: ''}, {browser: 'sd', mailchimp: '', flag: '', native: 'سنڌي', english: 'Sindhi', notes: ''}, {browser: 'sdc', mailchimp: '', flag: '', native: 'Sassaresu', english: 'Sassarese', notes: ''}, {browser: 'se', mailchimp: '', flag: '', native: 'Davvisámegiella', english: 'Northern Sami', notes: ''}, {browser: 'sei', mailchimp: '', flag: '', native: 'Cmique Itom', english: 'Seri', notes: ''}, {browser: 'sg', mailchimp: '', flag: '', native: 'Sängö', english: 'Sango/Sangho', notes: ''}, {browser: 'sgs', mailchimp: '', flag: '', native: 'žemaitėška', english: 'Samogitian', notes: ''}, {browser: 'sh', mailchimp: '', flag: '', native: 'srpskohrvatski / српскохрватски', english: 'Serbocroatian', notes: ''}, {browser: 'shi', mailchimp: '', flag: '', native: 'Tašlḥiyt/ⵜⴰⵛⵍⵃⵉⵜ', english: 'Tachelhit', notes: '(multiple scripts - defaults to Latin)'}, {browser: 'shi_tfng', mailchimp: '', flag: '', native: 'ⵜⴰⵛⵍⵃⵉⵜ', english: 'Tachelhit', notes: '(Tifinagh script)'}, {browser: 'shi_latn', mailchimp: '', flag: '', native: 'Tašlḥiyt', english: 'Tachelhit', notes: '(Latin script)'}, {browser: 'si', mailchimp: '', flag: '', native: 'සිංහල', english: 'Sinhalese', notes: ''}, {browser: 'simple', mailchimp: '', flag: '', native: 'Simple English', english: 'Simple English', notes: ''}, {browser: 'sk', mailchimp: 'sk', flag: '', native: 'slovenčina', english: 'Slovak', notes: ''}, {browser: 'sl', mailchimp: 'sl', flag: '', native: 'slovenščina', english: 'Slovenian', notes: ''}, {browser: 'sli', mailchimp: '', flag: '', native: 'Schläsch', english: 'Lower Selisian', notes: ''}, {browser: 'sm', mailchimp: '', flag: '', native: 'Gagana Samoa', english: 'Samoan', notes: ''}, {browser: 'sz', mailchimp: '', flag: '', native: 'Åarjelsaemien', english: 'Sami (Lappish)', notes: ''}, {browser: 'sn', mailchimp: '', flag: '', native: 'chiShona', english: 'Shona', notes: ''}, {browser: 'so', mailchimp: '', flag: '', native: 'Soomaaliga', english: 'Somani', notes: ''}, {browser: 'sq', mailchimp: '', flag: '', native: 'shqip', english: 'Albanian', notes: ''}, {browser: 'sr', mailchimp: 'sr', flag: '', native: 'српски / srpski', english: 'Serbian', notes: '(multiple scripts - defaults to Cyrillic)'}, {browser: 'sr_ec', mailchimp: '', flag: '', native: '"српски (ћирилица)\xE2\x80\x8E"', english: 'Serbian Cyrillic ekavian', notes: ''}, {browser: 'sr_el', mailchimp: '', flag: '', native: '"srpski (latinica)\xE2\x80\x8E"', english: 'Serbian Latin ekavian', notes: ''}, {browser: 'srn', mailchimp: '', flag: '', native: 'Sranantongo', english: 'Sranan Tongo', notes: ''}, {browser: 'ss', mailchimp: '', flag: '', native: 'SiSwati', english: 'Swati', notes: ''}, {browser: 'st', mailchimp: '', flag: '', native: 'Sesotho', english: 'Southern Sotho', notes: ''}, {browser: 'stq', mailchimp: '', flag: '', native: 'Seeltersk', english: 'Saterland Frisian', notes: ''}, {browser: 'su', mailchimp: '', flag: '', native: 'Basa Sunda', english: 'Sundanese', notes: ''}, {browser: 'sv', mailchimp: 'sv', flag: '', native: 'svenska', english: 'Swedish', notes: ''}, {browser: 'sv_fi', mailchimp: 'sv', flag: '', native: '', english: 'Swedish (Finland)', notes: ''}, {browser: 'sv_sv', mailchimp: 'sv', flag: '', native: '', english: 'Swedish (Sweden)', notes: ''}, {browser: 'sw', mailchimp: 'sw', flag: '', native: 'Kiswahili', english: 'Swahili', notes: ''}, {browser: 'sx', mailchimp: '', flag: '', native: '', english: 'Sutu', notes: ''}, {browser: 'szl', mailchimp: '', flag: '', native: 'ślůnski', english: 'Silesian', notes: ''}, {browser: 'ta', mailchimp: 'ta', flag: '', native: 'தமிழ்', english: 'Tamil', notes: ''}, {browser: 'tcy', mailchimp: '', flag: '', native: 'ತುಳು', english: 'Tulu', notes: ''}, {browser: 'te', mailchimp: '', flag: '', native: 'తెలుగు', english: 'Teluga', notes: ''}, {browser: 'tet', mailchimp: '', flag: '', native: 'tetun', english: 'Tetun', notes: ''}, {browser: 'tg', mailchimp: '', flag: '', native: 'тоҷикӣ', english: 'Tajiki', notes: '(falls back to tg_cyrl)'}, {browser: 'tg_cyrl', mailchimp: '', flag: '', native: 'тоҷикӣ', english: 'Tajiki', notes: '(Cyrllic script) (default)'}, {browser: 'tg_latn', mailchimp: '', flag: '', native: 'tojikī', english: 'Tajiki', notes: '(Latin script)'}, {browser: 'th', mailchimp: 'th', flag: '', native: 'ไทย', english: 'Thai', notes: ''}, {browser: 'ti', mailchimp: '', flag: '', native: 'ትግርኛ', english: 'Tigrinya', notes: ''}, {browser: 'tig', mailchimp: '', flag: '', native: '', english: 'Tigre', notes: ''}, {browser: 'tk', mailchimp: '', flag: '', native: 'Türkmençe', english: 'Turkmen', notes: ''}, {browser: 'tl', mailchimp: '', flag: '', native: 'Tagalog', english: 'Tagalog', notes: ''}, {browser: 'tlh', mailchimp: '', flag: '', native: '', english: 'Klingon', notes: ''}, {browser: 'tly', mailchimp: '', flag: '', native: 'толышә зывон', english: 'Talysh', notes: ''}, {browser: 'tn', mailchimp: '', flag: '', native: 'Setswana', english: 'Tswana', notes: ''}, {browser: 'to', mailchimp: '', flag: '', native: 'lea faka-Tonga', english: 'Tonga (Tonga Islands)', notes: ''}, {browser: 'tokipona', mailchimp: '', flag: '', native: 'Toki Pona', english: 'Toki Pona', notes: ''}, {browser: 'tpi', mailchimp: '', flag: '', native: 'Tok Pisin', english: 'Tok Pisin', notes: ''}, {browser: 'tr', mailchimp: 'tr', flag: '', native: 'Türkçe', english: 'Turkish', notes: ''}, {browser: 'tru', mailchimp: '', flag: '', native: 'Ṫuroyo', english: 'Turoyo', notes: ''}, {browser: 'ts', mailchimp: '', flag: '', native: 'Xitsonga', english: 'Tsonga', notes: ''}, {browser: 'tt', mailchimp: '', flag: '', native: 'татарча/tatarça', english: 'Tatar', notes: '(multiple scripts - defaults to Cyrillic)'}, {browser: 'tt_cyrl', mailchimp: '', flag: '', native: 'татарча', english: 'Tatar', notes: '(Cyrillic script) (default)'}, {browser: 'tt_latn', mailchimp: '', flag: '', native: 'tatarça', english: 'Tatar', notes: '(Latin script)'}, {browser: 'tum', mailchimp: '', flag: '', native: 'chiTumbuka', english: 'Tumbuka', notes: ''}, {browser: 'tw', mailchimp: '', flag: '', native: 'Twi', english: 'Twi', notes: '(FIXME!)'}, {browser: 'ty', mailchimp: '', flag: '', native: 'Reo Mā`ohi', english: 'Tahitian', notes: ''}, {browser: 'tyv', mailchimp: '', flag: '', native: 'тыва дыл', english: 'Tyvan', notes: ''}, {browser: 'udm', mailchimp: '', flag: '', native: 'удмурт', english: 'Udmurt', notes: ''}, {browser: 'ug', mailchimp: '', flag: '', native: 'ئۇيغۇرچە / Uyghurche', english: 'Uyghur', notes: '(multiple scripts - defaults to Arabic)'}, {browser: 'ug_arab', mailchimp: '', flag: '', native: 'ئۇيغۇرچە', english: 'Uyghur', notes: '(Arabic script) (default)'}, {browser: 'ug_latn', mailchimp: '', flag: '', native: 'Uyghurche', english: 'Uyghur', notes: '(Latin script)'}, {browser: 'uk', mailchimp: 'uk', flag: '', native: 'українська', english: 'Ukrainian', notes: ''}, {browser: 'ur', mailchimp: '', flag: '', native: 'اردو', english: 'Urdu', notes: ''}, {browser: 'uz', mailchimp: '', flag: '', native: 'oʻzbekcha', english: 'Uzbek', notes: ''}, {browser: 've', mailchimp: '', flag: '', native: 'Tshivenda', english: 'Venda', notes: ''}, {browser: 'vec', mailchimp: '', flag: '', native: 'vèneto', english: 'Venetian', notes: ''}, {browser: 'vep', mailchimp: '', flag: '', native: 'vepsän kel’', english: 'Veps', notes: ''}, {browser: 'vi', mailchimp: 'vi', flag: '', native: 'Tiếng Việt', english: 'Vietnamese', notes: ''}, {browser: 'vls', mailchimp: '', flag: '', native: 'West-Vlams', english: 'West Flemish', notes: ''}, {browser: 'vmf', mailchimp: '', flag: '', native: 'Mainfränkisch', english: 'Upper Franconian, Main-Franconian', notes: ''}, {browser: 'vo', mailchimp: '', flag: '', native: 'Volapük', english: 'Volapük', notes: ''}, {browser: 'vot', mailchimp: '', flag: '', native: 'Vaďďa', english: 'Vod/Votian', notes: ''}, {browser: 'vro', mailchimp: '', flag: '', native: 'Võro', english: 'Võro', notes: ''}, {browser: 'wa', mailchimp: '', flag: '', native: 'walon', english: 'Walloon', notes: ''}, {browser: 'war', mailchimp: '', flag: '', native: 'Winaray', english: 'Waray-Waray', notes: ''}, {browser: 'wo', mailchimp: '', flag: '', native: 'Wolof', english: 'Wolof', notes: ''}, {browser: 'wuu', mailchimp: '', flag: '', native: '吴语', english: 'Wu Chinese', notes: ''}, {browser: 'xal', mailchimp: '', flag: '', native: 'хальмг', english: 'Kalmyk-Oirat', notes: ''}, {browser: 'xh', mailchimp: '', flag: '', native: 'isiXhosa', english: 'Xhosan', notes: ''}, {browser: 'xmf', mailchimp: '', flag: '', native: 'მარგალური', english: 'Mingrelian', notes: ''}, {browser: 'yi', mailchimp: '', flag: '', native: 'ייִדיש', english: 'Yiddish', notes: ''}, {browser: 'yo', mailchimp: '', flag: '', native: 'Yorùbá', english: 'Yoruba', notes: ''}, {browser: 'yue', mailchimp: '', flag: '', native: '粵語', english: 'Cantonese', notes: ''}, {browser: 'za', mailchimp: '', flag: '', native: 'Vahcuengh', english: 'Zhuang', notes: ''}, {browser: 'zea', mailchimp: '', flag: '', native: 'Zeêuws', english: 'Zeeuws/Zeaws', notes: ''}, {browser: 'zh', mailchimp: 'zh', flag: 'cn', native: '中文', english: '(Zhōng Wén) - Chinese', notes: ''}, // {browser: 'zh_classical',mailchimp: 'zh', flag: 'cn', native: '文言', english: 'Classical Chinese/Literary Chinese', notes: '(see bug 8217)'}, {browser: 'zh_cn', mailchimp: 'zh', flag: 'cn', native: '"中文(中国大陆)\xE2\x80\x8E"', english: 'Chinese (PRC)', notes: ''}, {browser: 'zh_hans', mailchimp: 'zh', flag: 'cn', native: '"中文(简体)\xE2\x80\x8E"', english: 'Mandarin Chinese', notes: '(Simplified Chinese script) (cmn_hans)'}, {browser: 'zh_hant', mailchimp: 'zh', flag: 'cn', native: '"中文(繁體)\xE2\x80\x8E"', english: 'Mandarin Chinese', notes: '(Traditional Chinese script) (cmn_hant)'}, {browser: 'zh_hk', mailchimp: 'zh', flag: 'hk', native: '"中文(香港)\xE2\x80\x8E"', english: 'Chinese (Hong Kong)', notes: ''}, {browser: 'zh_min_nan', mailchimp: 'zh', flag: '', native: 'Bân-lâm-gú', english: 'Min-nan', notes: '(see bug 8217)'}, {browser: 'zh_mo', mailchimp: 'zh', flag: '', native: '"中文(澳門)\xE2\x80\x8E"', english: 'Chinese (Macau)', notes: ''}, {browser: 'zh_my', mailchimp: 'zh', flag: '', native: '"中文(马来西亚)\xE2\x80\x8E"', english: 'Chinese (Malaysia)', notes: ''}, {browser: 'zh_sg', mailchimp: 'zh', flag: '', native: '"中文(新加坡)\xE2\x80\x8E"', english: 'Chinese (Singapore)', notes: ''}, {browser: 'zh_tw', mailchimp: 'zh', flag: 'tw', native: '"中文(台灣)\xE2\x80\x8E"', english: 'Chinese (Taiwan)', notes: ''}, {browser: 'zh_yue', mailchimp: 'zh', flag: '', native: '粵語', english: 'Cantonese', notes: '(see bug 8217)'}, {browser: 'zu', mailchimp: '', flag: '', native: 'isiZulu', english: 'Zulu', notes: ''} ]; // $$$ TODO stocker le choix de langue courant dans le browser storage var tools = null; var $i18n = null; // In case locale option is not given, // $.i18n.debug = true; // jquery.i18n plugin will use the language attribute given for the html tag. // If that lang attribute is also missing, // it will try to use the locale specified by the browser. var browserLang = navigator.languages && navigator.languages[0] || // Chrome / Firefox navigator.language || // All browsers navigator.userLanguage; // IE <= 10 var browserLangLc = browserLang.replace(/-/g , '_').toLowerCase(); var mailchimpLanguage = ""; // --- private methods var setLocale = function(locale, callback) { $i18n.locale = locale; // locale should be valid IS0 639 language codes(eg: en, ml, hi, fr, ta, etc...) $i18n.load( 'assets/i18n', locale ) .done(function() { $('[data-i18n]').html(function(index) { var args = $(this).data('i18n').split(','); return $.i18n.apply(null, args); }); if (typeof callback === 'function') { callback(locale, mailchimpLanguage); } }); }; var selectLanguage = function(code, callback) { for (var l = 0; l < locales.length; l++) { if ( locales[l].browser === code ) { $('#i18n-select').html('<span class="flag-icon flag-icon-' + locales[l].flag + '"></span> ' + code.toUpperCase()); $('html').attr('lang', code); // $$$ TODO: $('html').attr('data-textdirection', 'ltr'); mailchimpLanguage = locales[l].mailchimp; setLocale(code, callback); break; } } }; // --- public methods return { init: function() { tools = window.ssw.Tools.getInstance(); $i18n = $.i18n(); $.i18n.fallbacks.en_GB = ['en']; $.i18n.fallbacks.en_UK = ['en']; $.i18n.fallbacks.de_DE = ['de']; $.i18n.fallbacks.fr_FR = ['fr']; $.i18n.fallbacks.fr_CA = ['fr']; $.i18n.fallbacks.fr_BE = ['fr']; $.i18n.fallbacks.fr_LU = ['fr']; $.i18n.fallbacks.fr_MC = ['fr']; $.i18n.fallbacks.fr_CH = ['fr']; }, // end of init:function buildGUI: function(initCallback, updateCallback, roles) { // get supported languages var url = '/api/I18ns/getSupportedLanguages'; if (roles) url = url + '&roles=' + roles; $.ajax({ type: 'POST', url: 'api/I18ns/getSupportedLanguages', data: {roles: roles}, success: function(data) { // Build language menu for (var c = 0; c < data.languages.length; c++) { var code = data.languages[c]; for (var l = 0; l < locales.length; l++) { if (locales[l].browser === code) { var flag = locales[l].flag; var native = locales[l].native; $('#i18n-menu').append('<a class="dropdown-item" href="#" data-i18n-locale="' + code + '"><span class="flag-icon flag-icon-' + flag + '"></span> ' + native + '</a>'); break; } } } // init default (browser) language for (var c = 0; c < data.languages.length; c++) { var code = data.languages[c]; if (browserLangLc === code) { selectLanguage(browserLangLc, initCallback); break; } } if (c === data.languages.length) { // default browser language is not supported // look for fallback for (var c = 0; c < data.languages.length; c++) { var code = data.languages[c]; if (code === browserLangLc.substring(0, 2)) { selectLanguage(code, initCallback); break; } } if (c === data.languages.length) { // fallback not found selectLanguage('en', initCallback); } } }, error: function(err) { selectLanguage('en', initCallback); $('#i18n').html(''); } }); // user select new language $('#i18n-menu').off('click.lang').on('click.lang', 'a', function(e) { e.preventDefault(); selectLanguage($(this).attr('data-i18n-locale'), updateCallback); return false; }); }, getMailChimpLanguage: function() { return mailchimpLanguage; }, // end of getMailChimpLanguage dispose: function() { } // end of dispose }; // end of return }; // end of ssw.I18n = function() { // ---------- End class I18n }(window)); // window.ssw.Tools.getInstance().addEventHandler( document, "DOMContentLoaded", window.ssw.I18n.getInstance().init(), false ); // EOF
import UIKit protocol MenuViewControllerDelegate: AnyObject { func didSelect(menuItem: MenuViewController.MenuOptions) } class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { weak var delegate: MenuViewControllerDelegate? enum MenuOptions: String, CaseIterable { case home = "Home" case locations = "Your Locations" case info = "Info" var imageName: String { switch self { case .home: return "house" case .locations: return "map" case .info: return "note" } } } private let tableView: UITableView = { let table = UITableView() table.backgroundColor = nil table.register(UITableViewCell.self, forCellReuseIdentifier: "cell") return table }() let greyColor = UIColor(red: 33/225.0, green: 33/225.0, blue: 33/225.0, alpha: 1) override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self // Do any additional setup after loading the view. view.backgroundColor = greyColor } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = CGRect(x: 0,y: view.safeAreaInsets.top+50, width: view.bounds.size.width, height: view.bounds.size.height) } // Table func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return MenuOptions.allCases.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //runs once in beginning let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = MenuOptions.allCases[indexPath.row].rawValue// Get string value from the enum cell.textLabel?.textColor = .white cell.imageView?.image = UIImage(systemName: MenuOptions.allCases[indexPath.row].imageName) cell.imageView?.tintColor = .white cell.backgroundColor = greyColor cell.contentView.backgroundColor = greyColor return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true)// unhighlight bij deselect let item = MenuOptions.allCases[indexPath.row] delegate?.didSelect(menuItem: item) } }
一、导出数据库 Linux用mysqldump命令(导出目录为使用该命令的目录): mysqldump -u用户名 -p密码 数据库名 > 数据库名.sql Windows环境: 使用navicat for mysql软件 二、导入数据库 1、首先建空数据库 mysql>create database 数据库名; 2.1、本地导入数据库1 (1)选择数据库 mysql>use 数据库名; (2)设置数据库编码 mysql>set names utf8; (3)导入数据(注意sql文件的路径) mysql>source sql文件路径; 2.2、Linux本地导入数据库 mysqldump -u用户名 -p密码 数据库名 < 数据库名.sql mysqldump详解: mysqldump -u[用户名] -h[ip] -p[密码] -P[端口号] 数据库名 表名 > 导出的文件名.sql mysqldump -uroot -h127.0.0.1 -proot -P3306 education users > d:/user.sql mysqldump -u[用户名] -h[ip] -p[密码] -P[端口号] 数据库名 表名 < 导出的文件名.sql mysqldump -uroot -h127.0.0.1 -proot -P3306 education users < d:/user.sql 如果导出/入整个数据库,则不需要加表名。 2.3、Windows导入数据库可使用navicat for mysql软件。
--- title: 枚举 category: 编程语言 tag: [Rust] article: false --- `enum`关键字允许创建一个从多个不同取值中选其一的枚举类型 ```rust enum Role { Foo, Bar, Qux, } ``` 可以指定类型,甚至另一个枚举类型 ```rust enum Role { Foo(i32), Bar(f32), Qux(String), Baz{x:i32, y:i32}, } ``` 也可以像结构体那样使用`impl`定义方法 ```rust enum Role { Foo(i32), Bar(f32), Qux(String), Baz{x:i32, y:i32}, } impl Role { fn call(&self) {} } ``` ## Option 在 Rust 中,通常使用`Option<T>`泛型枚举类型来表示可能存在或不存在的值,它有两种变体:`Some(T)`和`None`,使用这种枚举类型用来明确的处理可能为空的值 ```rust fn divide(a: i32, b: i32) -> Option<i32> { if b != 0 { Some(a / b) } else { None } } fn main() { let result = divide(2, 0); match result { Some(value) => println!("{}", value), None => println!("Cannot divide by zero!"), } } ```
from flask import Flask, render_template, url_for, request, redirect, flash, session from datetime import datetime from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func app = Flask(__name__) app.secret_key = 'cochabamba' app.config['SQLALCHEMY_DATABASE_URI'] = \ '{SGBD}://{usuario}:{clave}@{servidor}/{database}'.format( SGBD = 'mysql+mysqlconnector', usuario = 'MauriApaza845', clave = 'Mauricio67532900.', servidor = 'MauriApaza845.mysql.pythonanywhere-services.com', database = 'MauriApaza845$sistemaEleccionesDB' ) db = SQLAlchemy(app) class Elector(db.Model): ci_elector = db.Column(db.String(8), primary_key=True) nombre = db.Column(db.String(80), nullable=False) apellido_paterno = db.Column(db.String(80), nullable=False) apellido_materno = db.Column(db.String(80), nullable=False) fecha_nacimiento = db.Column(db.Date, nullable=False) estado = db.Column(db.String(80), nullable=False) def __repr__(self): return '<Name %r>' % self.name class Candidato(db.Model): id_candidato = db.Column(db.String(8), primary_key=True) nombre_candidato = db.Column(db.String(50), nullable=False) nombre_partido = db.Column(db.String(20), nullable=False) foto_candidato = db.Column(db.String(100), nullable=False) def __repr__(self): return '<Name %r>' % self.name def contar_votos(self): return db.session.query(func.count(Voto.id_voto)).filter_by(id_candidato=self.id_candidato).scalar() class Voto(db.Model): id_voto = db.Column(db.Integer, autoincrement=True, primary_key=True) ci_elector = db.Column(db.String(8), db.ForeignKey('elector.ci_elector'), nullable=False) id_candidato = db.Column(db.String(8), db.ForeignKey('candidato.id_candidato'), nullable=False) def __repr__(self): return '<Name %r>' % self.name class Comite(db.Model): __tablename__ = 'comite_electoral' id_comite = db.Column(db.Integer,primary_key = True,nullable=False) ci_comite = db.Column(db.String(10),nullable=False) contrasena = db.Column(db.String(25),nullable=False) def __repr__(self): return '<Name %r>' % self.name @app.route('/') def index(): return render_template('loginUsuario.html') @app.route('/verificar', methods=['POST']) def verificar(): ci_carnet = request.form.get('input-carnet') fecha_nacimiento = request.form.get('input-fn') if not ci_carnet or not fecha_nacimiento: flash('Por favor, completa ambos campos.', 'error') return render_template('loginUsuario.html') elector = Elector.query.filter_by(ci_elector=ci_carnet).first() if elector: pass_elec = elector.fecha_nacimiento.strftime('%Y-%m-%d') if fecha_nacimiento == pass_elec: fecha_nacimiento_dt = datetime.strptime(fecha_nacimiento, '%Y-%m-%d') edad = (datetime.now() - fecha_nacimiento_dt).days // 365 if edad < 18: flash('Solo pueden votar personas mayores a 18 años.', 'error') return render_template('loginUsuario.html') session['elector_logueado'] = elector.ci_elector return render_template('perfil.html', elector = elector) else: flash('CI y/o fecha de nacimiento incorrecta, por favor vuelve a ingresar los datos.', 'error') return render_template('loginUsuario.html') else: flash('CI y/o fecha de nacimiento incorrecta, por favor vuelve a ingresar los datos.', 'error') return render_template('loginUsuario.html') @app.route('/comite') def index2(): return render_template('loginComite.html') @app.route('/verificar_comite', methods=['POST']) def verificar_comite(): ci_comite = request.form.get('input-ci') contrasena = request.form.get('input-contra') if not ci_comite or not contrasena: flash('Por favor, completa ambos campos.', 'error') return render_template('loginComite.html') comite = Comite.query.filter_by(ci_comite=ci_comite).first() if comite: if contrasena == comite.contrasena: session['comite_logueado'] = comite.ci_comite flash('Bienvenido') candidatos = Candidato.query.all() cantidadtotal = Voto.query.count() cantidadelectores = Elector.query.count() return render_template('verResultados.html', candidatos=candidatos, cantidadtotal = cantidadtotal, cantidadelectores = cantidadelectores) else: flash('CI y/o contraseña incorrecta, por favor vuelve a ingresar los datos.', 'error') return render_template('loginComite.html') else: flash('CI y/o contraseña incorrecta, por favor vuelve a ingresar los datos.', 'error') return render_template('loginComite.html') @app.route('/irVotar', methods=['POST']) def irVotar(): candidatos = Candidato.query.all() return render_template('votar.html', candidatos=candidatos) @app.route('/realizar_votacion', methods=['POST']) def realizar_votacion(): ci_elector = session.get('elector_logueado') elector_logeado = Elector.query.get(ci_elector) candidatos = Candidato.query.all() if elector_logeado: id_candidato = request.form.get('candidato_ci') if id_candidato: voto = Voto(ci_elector=ci_elector, id_candidato=id_candidato) db.session.add(voto) elector_logeado.estado = 'desahibilitado' db.session.commit() flash('Votación realizada con éxito.') return render_template('loginUsuario.html') else: flash('Por favor, selecciona un candidato antes de votar.', 'error') return render_template('votar.html', candidatos=candidatos) return render_template('votar.html', candidatos=candidatos)
<?php /** * {{organization}} */ namespace {{ namespace }}; use Illuminate\Support\Carbon; /** * \{{ namespace }}\PaginationDatesTrait */ trait PaginationDatesTrait { protected array $paginationDates = [ 'created_at' => ['label' => 'Created'], 'updated_at' => ['label' => 'Updated'], // 'deleted_at' => ['label' => 'Deleted'], // 'start_at' => ['label' => 'Start'], // 'end_at' => ['label' => 'End'], ]; abstract public function getPaginationOperators(): array; abstract public function get(string $key, mixed $default = null); abstract public function merge(array $input); public function getPaginationDates(): array { return $this->paginationDates; } public function rules_filters_dates(array &$rules): void { foreach ($this->getPaginationDates() as $column => $meta) { if (empty($column) || ! is_string($column)) { continue; } $rule_key = sprintf('filter.%1$s', $column); $rules[$rule_key] = 'nullable'; } } public function prepareForValidationForDates(): ?array { // $params = [ // 'filter' => [ // 'updated_at' => [ // 'operator' => '>=', // 'value' => '-3 days midnight' // ], // 'created_at' => '2023-03%', // ], // ]; $dates = $this->getPaginationDates(); $filter = $this->get('filter'); if (empty($filter) || !is_array($filter)) { return null; } // dump([ // '__METHOD__' => __METHOD__, // '__LINE__' => __LINE__, // '$filter' => $filter, // 'http_build_query' => http_build_query($params), // ]); $merge = false; foreach ($dates as $column => $meta) { $filter_expects_array = false; $unset = true; $options = [ 'operator' => '=', 'parse' => true, 'value' => null, ]; if (array_key_exists($column, $filter)) { if (is_array($filter[$column])) { $merge = true; $unset = false; if (array_key_exists('parse', $filter[$column])) { $options['parse'] = !empty($filter[$column]['parse']); } $filter_operators = $this->getPaginationOperators(); if (array_key_exists('operator', $filter[$column]) && is_string($filter[$column]['operator']) && array_key_exists(strtoupper($filter[$column]['operator']), $filter_operators) ) { $options['operator'] = strtoupper($filter[$column]['operator']); } if (in_array($options['operator'], [ 'BETWEEN', 'NOTBETWEEN', ])) { $filter_expects_array = true; } if (array_key_exists('value', $filter[$column])) { if ($filter_expects_array && !is_array($filter[$column]['value'])) { $unset = true; } elseif (is_string($filter[$column]['value'])) { if ($options['parse']) { $options['value'] = Carbon::parse($filter[$column]['value'])->format('{{ format_sql }}'); } else { $options['value'] = $filter[$column]['value']; } } } if (!$unset) { $filter[$column] = $options; } // dump([ // '__METHOD__' => __METHOD__, // '__LINE__' => __LINE__, // '$column' => $column, // '$filter[$column]' => $filter[$column], // ]); } elseif(is_string($filter[$column])) { // dump([ // '__METHOD__' => __METHOD__, // '__LINE__' => __LINE__, // '$column' => $column, // '$filter[$column]' => $filter[$column], // ]); $merge = true; $unset = false; } else { $unset = true; } if ($unset) { $merge = true; unset($filter[$column]); } } } // dump([ // '__METHOD__' => __METHOD__, // '__LINE__' => __LINE__, // '$filter' => $filter, // '$merge' => $merge, // ]); if ($merge) { $this->merge([ 'filter' => $filter, ]); } return $filter; } }
// SPDX-License-Identifier: Apache-2.0 // Derived from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/mocks/ERC20Mock.sol // // The MIT License (MIT) // // Copyright (c) 2016-2022 zOS Global Limited and contributors // // 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. pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract ERC20Mock is ERC20 { constructor( string memory name, string memory symbol, address initialAccount, uint256 initialBalance ) payable ERC20(name, symbol) { _mint(initialAccount, initialBalance); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
import 'package:ar_furniture_app/core/widgets/spacer.dart'; import 'package:ar_furniture_app/features/cart/model/cart.dart'; import 'package:ar_furniture_app/features/cart/widgets/add_subtract_cart_item.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class CartListItem extends StatelessWidget { const CartListItem({ super.key, required this.cart, required this.onAddPressed, required this.onMinusPressed, required this.onDeletePressed, required this.isLastItem, }); final VoidCallback onAddPressed; final VoidCallback onMinusPressed; final VoidCallback onDeletePressed; final bool isLastItem; final Cart cart; @override Widget build(BuildContext context) { return Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: const BorderRadius.all( Radius.circular(8), ), child: CachedNetworkImage( width: 150, height: 100, fit: BoxFit.fill, imageUrl: cart.imageUrl, ), ), HorizontalSpacer.xl, Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( cart.name, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleMedium, ), VerticalSpacer.s, Text( cart.formattedPrice, style: Theme.of(context).textTheme.titleSmall, ), VerticalSpacer.s, Row( children: [ AddSubtractCartItem( onAddPressed: () => onAddPressed(), onSubtractPressed: () => onMinusPressed(), ), const Spacer(), IconButton( onPressed: () => onDeletePressed(), icon: const Icon( MdiIcons.trashCanOutline, color: Colors.black54, size: 20, ), ) ], ), Divider( color: Colors.grey.shade400, ), ], ), ), ], ), if (isLastItem) VerticalSpacer.exl, ], ); } }
import "@testing-library/jest-dom"; import { fireEvent, screen } from "@testing-library/react"; import customRender from "@/test-utils"; import CustomSelect from "./customSelect"; // TODO re-try to use userEvent.click later - now it doesn't work on React 18 (works fine on < 18); // switched to fireEvent test("Custom select", () => { const options = ["one", "two", "three"]; customRender(<CustomSelect options={options} label="test-select" />); const customSelect = screen.queryByLabelText(/custom-select$/i); const nativeSelect = screen.queryByLabelText(/test-select/i); const nativeSelectOptions = screen.getAllByRole("option"); // default state expect(customSelect).toHaveClass("select__custom"); expect(nativeSelect).toHaveClass("select__native"); expect(nativeSelect).toHaveValue(options[0]); expect(nativeSelectOptions.length).toBe(options.length); if (customSelect) { // open custom select fireEvent.click(customSelect); expect(customSelect).toHaveClass("is-active"); // does custom select have passed options const customSelectOptions = customSelect.getElementsByClassName("select__custom-option"); expect(customSelectOptions.length).toBe(options.length); // click on option fireEvent.click(customSelectOptions[1]); expect(nativeSelect).toHaveValue(options[1]); expect(customSelect).not.toHaveClass("is-active"); } });
import React, { useState } from "react"; import MessageHeader from "./MessageHeader"; import { Stack } from "@mui/material"; import MessageCard from "./MessageCard"; import Button from "@mui/material/Button"; import { LiaFacebookMessenger } from "react-icons/lia"; import MessageModal from "./MessageModal"; import MessageData from "./MessageData"; const MessagePage = (state) => { console.log("looging stae from Message component", state); const [openModel, setOpenModel] = useState(false); return ( <div className="absolute left-60 h-full w-[81%] flex max-sm:left-0 max-sm:w-auto md:left-20 md:w-full md:h-full lg:w-[92%] 3xl:left-60 3xl:w-[81%] 4xl:left-[210px] " > <div className=" text-white w-96 h-full max-sm:w-auto max-sm:h-auto md:w-auto lg:w-auto 3xl:w-auto 4xl:w-96 border-r-solid border-r-2 border-r-zinc-800 "> <MessageHeader userName="bajirao1292" /> <Stack spacing={1} marginTop={"10px"} width={"auto"}> {MessageData.map((sender, index) => { return ( <MessageCard key={index} senderProfile={sender.profile} senderUserName={sender.name} /> ); })} </Stack> </div> <div className=" w-full text-white flex justify-center items-center "> <Stack spacing={2} display={"flex"} justifyContent={"center"} alignItems={"center"} > <div className="w-auto h-auto border-2 border-solid border-white rounded-full p-4"> <LiaFacebookMessenger style={{ fontSize: "80px" }} /> </div> <h1 className="text-2xl">Your Messages</h1> <p className="text-zinc-400 "> Send private photos and messages to a friend or group </p> <Button variant="contained" onClick={() => { setOpenModel((prev) => { return !prev; }); console.log("openModel", openModel); }} > Send Message </Button> </Stack> </div> {openModel && <MessageModal status={openModel} />} </div> ); }; export default MessagePage;
<div class="col-md-8 col-md-offset-2"> <h2>Registered Users</h2> <div ng-controller="RegisteredUsersController as RegisteredUsersCtrl"> <form name="form" role="form"> <div class="form-group" ng-class="{ 'has-error': form.name.$dirty && form.name.$error.required }"> <label for="name">User Name</label> <input type="text" name="name" id="name" class="form-control" ng-model="RegisteredUsersCtrl.find.name" required /> <span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">User Name is required</span> </div> Search with the help of email: <input type="checkbox" ng-model="emailValue" ng-init="emailValue = true"> <div ng-if="emailValue"> <div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }"> <label for="email">E-mail: </label> <input type="email" name="email" id="email" class="form-control" ng-model="RegisteredUsersCtrl.find.email" required /> <span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">E-mail is required</span> </div> </div> <div class="form-actions"> <button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary" ng-click="RegisteredUsersCtrl.findRegisteredUser()">Find</button> <img ng-if="vm.dataLoading" src="img/loader.gif"/> <a data-ui-sref="home.dashboard" class="btn btn-link">Back</a> </div> </form> <p>&nbsp;</p> <div ng-class="{ 'alert': flash, 'alert-success': flash.type === 'success', 'alert-danger': flash.type === 'error' }" ng-if="flash" ng-bind="flash.message"></div> <div ng-view></div> <div ng-model="RegisteredUsersCtrl.status" ng-init="RegisteredUsersCtrl.status = false"> <table class="table table-hover" ng-if="RegisteredUsersCtrl.status"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Active</th> </tr> </thead> <tbody> <tr ng-repeat="item in RegisteredUsersCtrl.result" class="rowId" data-toggle="modal" data-target="#myModal" data-id={{item.userId}} data-name={{item.firstName}}{{item.lastName}}> <td>{{item.firstName}}</td> <td>{{item.lastName}}</td> <td>{{item.email}}</td> <td>{{item.active}}</td> </tr> </tbody> </table> </div> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Request</h4> </div> <div class="modal-body"> <h1 class="modal-body-h1"></h1> <p>Send Friend Request.</p> <button type="button" class="btn btn-info" ng-click="RegisteredUsersCtrl.sendRequest()">Invite</button> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div>
import { StyleSheet, Text, View } from 'react-native' import React, { useState } from 'react' import {Picker} from '@react-native-picker/picker'; import { responsiveHeight } from '../../../utils'; const Pilihan = ({label, datas, width, height, fontSize, selectedValue, onValueChange}) => { return ( <View style={styles.container}> <Text style={styles.label(fontSize)}>{label} :</Text> <View style={styles.wrapperPicker}> <Picker selectedValue={selectedValue} itemStyle={styles.picker(width, height, fontSize)} onValueChange={onValueChange} > <Picker.Item label="-- Pilih --" value=""/> {datas.map((item, index)=>{ if(label == "Provinsi"){ return <Picker.Item label={item.province} value={item.province_id} key={item.province_id} /> }else if(label== "Kota/Kab"){ return <Picker.Item label={item.type+" "+item.city_name} value={item.city_id} key={index.city_id} /> }else if(label == "Diantar atau tidak?"){ return <Picker.Item label={item} value={item} key={index} /> }else{ return <Picker.Item label={item} value={item} key={index} /> } })} </Picker> </View> </View> ) } export default Pilihan const styles = StyleSheet.create({ container:{ marginTop:10, }, label: (fontSize) => ({ fontSize: fontSize ? fontSize : 18, fontFamily: "regular" }), picker: (width, height, fontSize) => ({ fontSize: fontSize ? fontSize : 18, fontFamily: "regular", width: width, height: height ? height : responsiveHeight(46), color: 'black' }), wrapperPicker:{ borderWidth: 1, borderRadius: 5, } })
package interview32I; import bean.TreeNode; import java.util.*; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int[] levelOrder(TreeNode root) { if (root == null) { return new int[]{}; } List<Integer> list = new ArrayList<>(); Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } list.add(node.val); } int[] result = new int[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; } }
<template> <div> <div class="navBar"> <div> <logo-img /> </div> <div> <nav> <ul class="navigationMenu"> <li><router-link to="/">INICIO</router-link> </li> <li><router-link to="/profiles">PERFILES</router-link></li> <!-- <li><router-link to="/us">NOSOTROS</router-link></li> --> <li><router-link to="/us">NOSOTROS</router-link></li> </ul> </nav> </div> <div class="searchAndRegisterContainer"> <form action="#" class="formSearch"> <span><img class="iconSearch" src="../../assets/img/SearchLupe.png" alt="Icono de búsqueda"/></span> <label for="jobSearch" > <input type="search" name="jobSearch" class="textSearch" placeholder="Profesión u oficio" required> </label> </form> </div> <div> <ul class="sectionlogin"> <li> <router-link to="/login">Login</router-link> | <router-link to="/register"> Registrarse </router-link> <img class="loginIcon" src="../../assets/img/login.png" alt=""> </li> </ul> </div> </div> </div> </template> <script lang="ts"> import LogoImg from '@/components/layout/LogoImg.vue' export default ({ name: "NavBar", components: { LogoImg } }) </script> <style scoped> a:hover{ color:#e66f0f; } .logo{ /* border: 1px solid red; */ padding: 0 50px; margin-left: 30px; } /* Menu de navegacion */ .navBar{ display: Flex; justify-content: center; align-items: center; flex-wrap: wrap; background-color: #2d4f5c; height: 100px; /* box-shadow: 1px 1px 10px #888888; */ } .navigationMenu{ display: flex; list-style: none; height: 40px; } .navigationMenu li{ display: flex; align-items: center; justify-content: center; padding: 0 25px; font-weight: bold; font-size: 0.9rem; /* border: 1px solid red */ } /* Caja de busqueda */ .textSearch{ height: 40px; width: 300px; padding-left:36px; padding-right: 15px; border:none; /* border-top-left-radius: 5px; border-bottom-left-radius: 5px; */ border-radius: 5px; font-size: 0.9rem; background-color: #f5f5f5; } .textSearch::placeholder{ text-align: center; font-size: 0.9rem; } /* .btnSearch{ height: 40px; width: 50px; border:none; border-top-right-radius: 5px; border-bottom-right-radius: 5px; background-color: #e66f0f; } */ .iconSearch{ width: 25px; position: absolute; margin-left: 5px; margin-top: 9px; border-right: 1px solid #2d4f5c1f; } /* Secction de logueo */ .sectionlogin{ padding: 0 15px; margin-right: 20px; display: flex; list-style: none; font-weight: bold; font-size: 0.8rem; justify-content: center; align-items: center; } .sectionlogin .loginIcon{ position: absolute; width: 24px; margin: -4px; margin-left: 15px; } .sectionlogin li{ margin: 0 5px; padding: 10px; border-radius: 7px; border: 1px solid white; box-shadow: 1px 1px 3px #252525; } .sectionlogin li a{ color:white; text-decoration: none; } .sectionlogin li a:hover{ color: #e66f0f; } .searchAndRegisterContainer{ display:flex; justify-content: center; } @media screen and (max-width: 1440px) { .navBar{ display: Flex; justify-content: space-around; } } @media screen and (max-width: 768px) { .navBar .navigationMenu li{ padding: 0 10px; } .navBar .textSearch{ width: 150px; } /* .searchAndRegisterContainer{ display: none; } */ .loginIcon{ display: none; } } @media screen and (max-width: 425px) { .navBar{ height: 200px; } .navBar .textSearch{ width: 250px; } } @media screen and (max-width: 320px) { .navBar{ display: flex; flex-wrap: wrap; justify-content: center; align-items: center; height: 280px; } .navBar .textSearch{ width: 250px; } } </style>
import { Component, Input, OnInit, ViewChild } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { SignaturePad } from 'angular2-signaturepad'; import { ToastrService } from 'ngx-toastr'; import { Subscription, throwError } from 'rxjs'; import { catchError, first } from 'rxjs/operators'; import { FirmaAnexoModel } from 'src/app/models/firmaAnexo.model'; import { FirmaService } from 'src/app/services/firma-anexo.service'; @Component({ selector: 'app-modal-firma', templateUrl: './modal-firma.component.html', styleUrls: ['./modal-firma.component.scss'], }) export class ModalFirmaComponent implements OnInit { /***********************************************************************/ //#region Inicialización de variables signatureImg!: string; @ViewChild(SignaturePad) signaturePad!: SignaturePad; @Input() codigo_anexo: any; signaturePadOptions: Object = { minWidth: 2, canvasWidth: 450, canvasHeight: 300, }; private unsubscribe: Subscription[] = []; constructor( private modalActive: NgbActiveModal, private firmaService: FirmaService, private toastr: ToastrService ) {} ngOnInit(): void {} ngAfterViewInit() { this.signaturePad.set('minWidth', 2); this.signaturePad.clear(); } //#endregion /***********************************************************************/ /***********************************************************************/ //#region Gestión del dibujo en el signature-pad drawComplete() { // console.log(this.signaturePad.toDataURL()); } drawStart() { } /** * Borra lo dibujado en el signature-pad * @author Pablo */ clearSignature() { this.signaturePad.clear(); } /** * Guarda lo dibujado en el signature-pad y lo envía al servidor en base64 * @author Pablo */ savePad() { const base64Data = this.signaturePad.toDataURL(); this.signatureImg = base64Data; const firma = new FirmaAnexoModel(); firma.codigo_anexo = this.codigo_anexo; firma.contenido = this.signatureImg; const storageSub = this.firmaService .add(firma) .pipe( first(), catchError((e) => { this.toastr.error('El anexo no ha podido ser firmado', 'Fallo'); return throwError(new Error(e)); }) ) .subscribe((storage: FirmaAnexoModel) => { if (storage) { var o: any = storage; this.toastr.success('Firma añadida', 'Añadida'); let mensaje: String = o.mensaje .replaceAll('\\r', '\r') .replaceAll('\\n', '\n'); this.closeModal(); } else { // TODO: error } }); this.unsubscribe.push(storageSub); } //#endregion /***********************************************************************/ /***********************************************************************/ //#region Funciones auxiliares y otros /** * Cierra el modal de firma de anexos * @author Pablo */ closeModal() { this.modalActive.close(); } //#endregion /***********************************************************************/ }
import { useMemo } from 'react' import { css } from 'glamor' import { fontStyles, mediaQueries, Center, Button, useColorContext, } from '@project-r/styleguide' import { HEADER_HEIGHT, HEADER_HEIGHT_MOBILE } from '../../constants' import { useTranslation } from '../../../lib/withT' import { useInNativeApp } from '../../../lib/withInNativeApp' import SignIn from '../../Auth/SignIn' import SignOut from '../../Auth/SignOut' import Footer from '../../Footer' import NavLink, { NavA } from './NavLink' import NotificationFeedMini from '../../Notifications/NotificationFeedMini' import BookmarkMiniFeed from '../../Bookmarks/BookmarkMiniFeed' import { registerQueryVariables } from '../../Bookmarks/queries' import DarkmodeSwitch from '../DarkmodeSwitch' import Link from 'next/link' import { useRouter } from 'next/router' const SignoutLink = ({ children, ...props }) => ( <div {...styles.signout}> <NavA {...props}>{children}</NavA> </div> ) const UserNav = ({ me }) => { const { t } = useTranslation() const { inNativeApp, inNativeIOSApp } = useInNativeApp() const router = useRouter() const [colorScheme] = useColorContext() const currentPath = router.asPath const hasProgress = !!me?.progressConsent const variables = useMemo(() => { if (hasProgress) { return { collections: ['progress', 'bookmarks'], progress: 'UNFINISHED', lastDays: 30, } } return { collections: ['bookmarks'], } }, [hasProgress]) registerQueryVariables(variables) return ( <> <Center {...styles.container} {...colorScheme.set('color', 'text')}> <div> <> <div style={{ marginBottom: 20 }}> <DarkmodeSwitch t={t} /> </div> {!me && ( <> <div {...styles.signInBlock}> <SignIn style={{ padding: 0 }} /> </div> </> )} {!me?.activeMembership && !inNativeIOSApp && ( <Link href='/angebote' passHref legacyBehavior> <Button style={{ marginTop: 24, marginBottom: 24 }} block> {t('nav/becomemember')} </Button> </Link> )} {me && ( <> <NavLink href='/benachrichtigungen' large> {t('pages/notifications/title')} </NavLink> <NotificationFeedMini /> <div style={{ marginTop: 24 }}> <NavLink href='/lesezeichen' large> {`${t('nav/bookmarks')}`} </NavLink> </div> <BookmarkMiniFeed style={{ marginTop: 10, }} variables={variables} /> <div {...styles.navSection}> <div {...styles.navLinks}> <NavLink href='/konto' currentPath={currentPath} large> {t('Frame/Popover/myaccount')} </NavLink> <NavLink href={`/~${me.username || me.id}`} currentPath={currentPath} large > {t('Frame/Popover/myprofile')} </NavLink> </div> </div> <hr {...styles.hr} {...colorScheme.set('color', 'divider')} {...colorScheme.set('backgroundColor', 'divider')} /> <div {...styles.navSection}> <div {...styles.navLinks}> {me?.accessCampaigns?.length > 0 && ( <NavLink href='/teilen' currentPath={currentPath} large> {t('nav/share')} </NavLink> )} {!inNativeIOSApp && ( <> <NavLink href={{ pathname: '/angebote', query: { group: 'GIVE' }, }} currentPath={currentPath} large > {t('nav/give')} </NavLink> <NavLink {...fontStyles.sansSerifLight16} href={{ pathname: '/angebote', query: { package: 'DONATE' }, }} currentPath={currentPath} large > {t('nav/donate')} </NavLink> </> )} </div> </div> <div {...styles.navSection}> <div {...styles.navLinks} {...styles.smallLinks}> <SignOut Link={SignoutLink} /> </div> </div> </> )} </> </div> </Center> {inNativeApp && <Footer />} </> ) } const styles = { container: css({ [mediaQueries.mUp]: { marginTop: '40px', }, }), hr: css({ margin: 0, display: 'block', border: 0, height: 1, width: '100%', }), hrFixed: css({ position: 'fixed', top: HEADER_HEIGHT_MOBILE - 1, [mediaQueries.mUp]: { top: HEADER_HEIGHT - 1, }, }), signInBlock: css({ display: 'block', }), navSection: css({ display: 'flex', flexDirection: 'column', margin: '24px 0px', }), navLinks: css({ display: 'flex', flexDirection: 'column', width: '100%', [mediaQueries.mUp]: { flexDirection: 'row', }, }), smallLinks: css({ '& a': { ...fontStyles.sansSerifRegular18, }, }), } export default UserNav
import { render, screen } from "@testing-library/react"; import EditFeedback from "../EditFeedback"; import { GlobalContext } from "../../../../App/App"; import { MemoryRouter, Route, Routes } from "react-router-dom"; import userEvent from "@testing-library/user-event"; import { act } from "react-dom/test-utils"; const MockEditFeedback = () => { const setRefreshCount = vitest.fn(); const id = "64c870dbedb470fd5dce61f2"; return ( <GlobalContext.Provider value={{ setRefreshCount }}> <MemoryRouter initialEntries={[`/edit/${id}`]}> <Routes> <Route path="/edit/:id" element={<EditFeedback />} /> </Routes> </MemoryRouter> </GlobalContext.Provider> ); }; globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ _id: "64c870dbedb470fd5dce61f2", id: 3, title: "Q&A within the challenge hubs", category: "feature", upvotes: 65, status: "suggestion", description: "Challenge-specific Q&A would make for easy reference.", comments: [ { id: 5, content: "Much easier to get answers from devs who can relate, since they've either finished the challenge themselves or are in the middle of it.", user: { image: "./assets/user-images/image-george.jpg", name: "George Partridge", username: "soccerviewer8", }, }, ], upvoted: false, updatedAt: { $date: "2023-09-06T18:27:14.339Z", }, }), }) ); vi.mock("react-router-dom", () => ({ ...vi.importActual("react-router-dom"), useParams: () => ({ id: "64c870dbedb470fd5dce61f2", }), })); vi.mock("react-router-dom", async () => { const actual = await vi.importActual("react-router-dom"); return { ...actual, NavLink: "a", }; }); describe("Edit Feedback page", () => { it("should fetch data", async () => { await act(async () => { render(<MockEditFeedback />); }); expect(fetch).toHaveBeenCalledWith( "http://3.135.141.179:27017/api/feedback/64c870dbedb470fd5dce61f2" ); }); it("Should navigate to root path", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const backButton = screen.getByRole("button", { name: "Go Back" }); await user.click(backButton); expect(window.location.pathname).toBe("/"); }); it("should change content of title textarea", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const textArea = screen.getByTestId("title-textarea"); await user.type(textArea, " Test"); expect(textArea.value).toBe("Q&A within the challenge hubs Test"); }); it("should change content of desc textarea", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const textArea = screen.getByTestId("desc-textarea"); await user.clear(textArea); await user.type(textArea, "Test"); expect(textArea.value).toBe("Test"); }); it("should open category dropdown", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); expect(screen.getByTestId("category-1")).toBeInTheDocument(); expect(screen.getByTestId("category-2")).toBeInTheDocument(); expect(screen.getByTestId("category-3")).toBeInTheDocument(); expect(screen.getByTestId("category-4")).toBeInTheDocument(); expect(screen.getByTestId("category-5")).toBeInTheDocument(); }); it("should change category to Feature", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("category-1"); expect(screen.getByAltText("check icon")).toBeInTheDocument(); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("feature"); await user.click(dropDown); expect(dropDown.textContent).toBe("Feature"); }); it("should change category to UI", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("category-2"); expect(screen.getByAltText("check icon")).toBeInTheDocument(); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("ui"); await user.click(dropDown); expect(dropDown.textContent).toBe("UI"); }); it("should change category to UX", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("category-3"); expect(screen.getByAltText("check icon")).toBeInTheDocument(); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("ux"); await user.click(dropDown); expect(dropDown.textContent).toBe("UX"); }); it("should change category to Enhancement", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("category-4"); expect(screen.getByAltText("check icon")).toBeInTheDocument(); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("enhancement"); await user.click(dropDown); expect(dropDown.textContent).toBe("Enhancement"); }); it("should change category to Bug", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("category-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("category-5"); expect(screen.getByAltText("check icon")).toBeInTheDocument(); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("bug"); await user.click(dropDown); expect(dropDown.textContent).toBe("Bug"); }); it("should open status dropdown", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("status-dropdown"); await user.click(dropDown); expect(screen.getByTestId("status-1")).toBeInTheDocument(); expect(screen.getByTestId("status-2")).toBeInTheDocument(); expect(screen.getByTestId("status-3")).toBeInTheDocument(); expect(screen.getByTestId("status-4")).toBeInTheDocument(); }); it("should change status to Suggestion", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("status-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("status-1"); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("suggestion"); await user.click(dropDown); expect(dropDown.textContent).toBe("Suggestion"); }); it("should change status to Planned", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("status-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("status-2"); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("planned"); await user.click(dropDown); expect(dropDown.textContent).toBe("Planned"); }); it("should change status to In-Progress", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("status-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("status-3"); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("progress"); await user.click(dropDown); expect(dropDown.textContent).toBe("In-Progress"); }); it("should change status to Live", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const dropDown = screen.getByTestId("status-dropdown"); await user.click(dropDown); const itemElement = screen.getByTestId("status-4"); await user.click(itemElement); await user.click(dropDown); expect(screen.getByAltText("check icon").id).toBe("live"); await user.click(dropDown); expect(dropDown.textContent).toBe("Live"); }); it("should send successful delete request", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); fetch = vi.fn(() => { Promise.resolve({ ok: true, method: "DELETE", }); }); const deleteButton = screen.getByRole("button", { name: /delete/i }); await user.click(deleteButton); expect(fetch).toHaveBeenCalledWith( "http://3.135.141.179:27017/api/feedback/64c870dbedb470fd5dce61f2", { method: "DELETE", } ); }); it("should send unsuccessful delete request", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); fetch = vi.fn(() => { return Promise.reject(new Error("HTTP error")); }); const deleteButton = screen.getByRole("button", { name: /delete/i }); await user.click(deleteButton); expect(fetch).toHaveBeenCalledWith( "http://3.135.141.179:27017/api/feedback/undefined", { method: "DELETE", } ); }); it("should send successful patch request to save changes", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const updateButton = screen.getByRole("button", { name: /save changes/i }); fetch = vi.fn(() => { Promise.resolve({ ok: true, method: "PATCH", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ _id: "64c870dbedb470fd5dce61f2", id: 3, title: "Testing patch request", category: "feature", upvotes: 65, status: "suggestion", description: "New test description", comments: [ { id: 5, content: "Much easier to get answers from devs who can relate, since they've either finished the challenge themselves or are in the middle of it.", user: { image: "./assets/user-images/image-george.jpg", name: "George Partridge", username: "soccerviewer8", }, }, ], upvoted: false, updatedAt: { $date: "2023-09-06T18:27:14.339Z", }, }), }); }); await user.click(updateButton); expect(fetch).toHaveBeenCalledWith( "http://3.135.141.179:27017/api/feedback/64c870dbedb470fd5dce61f2", { method: "PATCH", body: JSON.stringify({}), headers: { Accept: "application/json", "Content-Type": "application/json", }, } ); }); it("should send unsuccessful patch request when saving changes", async () => { const user = userEvent.setup(); await act(async () => { render(<MockEditFeedback />); }); const updateButton = screen.getByRole("button", { name: /save changes/i }); fetch = vi.fn(() => { return Promise.reject(new Error("HTTP error")); }); await user.click(updateButton); expect(fetch).toHaveBeenCalledWith( "http://3.135.141.179:27017/api/feedback/64c870dbedb470fd5dce61f2", { method: "PATCH", body: JSON.stringify({}), headers: { Accept: "application/json", "Content-Type": "application/json", }, } ); }); });
#!/usr/bin/python3 """Creating a student module""" class Student: """A student class""" def __init__(self, first_name, last_name, age): """Initializing an instance""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Retrieving the dictionary representation""" if type(attrs) is list and all(type(x) is str for x in attrs): dictionary = {} for i in attrs: if i in self.__dict__: dictionary[i] = self.__dict__[i] return dictionary else: return self.__dict__
library(tidyverse) require(maps) library(colorBlindness) wiid <- read_csv("wiid.csv") glimpse(wiid) wiid_select <- wiid %>% select(country, c3, c2, year, gini_reported, region_un, region_un_sub, region_wb, eu, oecd, incomegroup, mean_usd, median_usd, gdp_ppp_pc_usd2011, population) glimpse(wiid_select) wiid_select$incomegroup <- factor(wiid$incomegroup , levels = c("High income", "Upper middle income", "Lower middle income", "Low income"), ordered = TRUE) colorBlindness::cvdPlot(plot) ## 1st plot: World Map with Most recent Gini Scores by Country world_map <- map_data("world") world_map <- world_map %>% filter(region != "Antarctica") %>% mutate(region = case_when( region == "Greenland" ~ "Denmark", TRUE ~ region)) wiid_most_recent <- wiid_select %>% group_by(country) %>% drop_na(gini_reported) %>% mutate(most_recent = max(year)) %>% filter(year == most_recent) %>% mutate(mean_gini = mean(gini_reported)) %>% rename(region = country) %>% mutate(region = case_when( region == "Bahamas, The" ~ "Bahamas", region == "Congo, Democratic Republic of the" ~ "Democratic Republic of the Congo", region == "Congo, Republic of the" ~ "Republic of Congo", region == "Cote d'Ivoire" ~ "Ivory Coast", region == "Czechia" ~ "Czech Republic", region == "Eswatini" ~ "Swaziland", region == "Gambia, The" ~ "Gambia", region == "Korea, Republic of" ~ "South Korea", region == "Macedonia, former Yugoslav Republic of" ~ "North Macedonia", region == "Micronesia, Federated States of" ~ "Micronesia", region == "Serbia and Montenegro" ~ "Serbia", region == "Taiwan (China)" ~ "Taiwan", region == "Trinidad and Tobago" ~ "Trinidad", region == "United Kingdom" ~ "UK", region == "West Bank and Gaza" ~ "Palestine", region == "United States" ~ "USA", TRUE ~ region) ) non_match <- anti_join(wiid_most_recent, world_map, by = "region") wiid_world_map <- left_join(world_map, wiid_most_recent, by = "region") wiid_world_map %>% ggplot(aes(x = long, y = lat, group = group))+ geom_polygon(aes(fill = mean_gini, color = ""), color = "white") + labs(title = "Most Recent Gini Coefficients by Country", fill = "Gini Coefficient") + scale_fill_gradientn(colors = c("#32CF16", "#F9F214", "#E20000")) + theme_void() + guides(fill = guide_colorbar(title.vjust = 0.7)) + theme(legend.position = "bottom") + theme(text = element_text(size = 8)) + theme(plot.title = element_text(hjust = 0.5)) ## 2nd Plot: Mean Gini Indices over time by UN regions wiid_select %>% filter(year > 1959, year < 2011) %>% group_by(year, region_un) %>% summarize(mean_gini = mean(gini_reported, na.rm = TRUE)) %>% ggplot(aes(x = year, y = mean_gini, color = region_un)) + geom_point(alpha = 0.3, size = 1) + geom_smooth(size = 0, span = 0.7, alpha = 0.1) + stat_smooth(geom = "line", size = 0.8) + labs(title = "Gini Coefficient of UN Regions between 1960 - 2010", y = "Gini Coefficient", color = "UN Regions") + scale_color_viridis_d() + theme_minimal() + theme(text = element_text(size = 8), plot.title = element_text(hjust = 0.5), axis.title.x = element_blank()) ## 3rd Plot: Mean Income against Gini Coefficient wiid_select %>% filter(year > 1999, !is.na(mean_usd), !is.na(gini_reported)) %>% ggplot(aes(x = mean_usd, y = gini_reported, color = region_un)) + geom_point(size = 1.3, alpha = 0.8) + geom_smooth(aes(x = mean_usd, y = gini_reported), inherit.aes = FALSE, color = "#CF0E0E", size = 0.8) + labs(title = "Mean Income against Gini Coefficient", subtitle = "Only Gini Coefficients from after 1999 considered", x = "Mean Income (in $)", y = "Gini Coefficient", size = "Population", color = "UN Region") + scale_color_viridis_d() + theme_minimal() + theme(text = element_text(size = 8), plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5), legend.position = "bottom") ## 4th Plot: Most recent Gini coeffienct of G20 members and countries with the highest and lowest gini coefficient top_5_names <- wiid_most_recent %>% filter(year > 2010) %>% group_by(region) %>% summarize(first(region), mean_gini = mean(gini_reported, na.rm = TRUE)) %>% ungroup() %>% arrange(desc(mean_gini)) %>% select(region) %>% slice(1:5) bottom_5_names <- wiid_most_recent %>% filter(year > 2010) %>% group_by(region) %>% summarize(first(region), mean_gini = mean(gini_reported, na.rm = TRUE)) %>% ungroup() %>% arrange(mean_gini) %>% select(region) %>% slice(1:5) top_5_names <- pull(top_5_names, region) bottom_5_names <- pull(bottom_5_names, region) g20 <- c("Argentina", "Australia", "Brazil", "Canada", "China", "France", "Germany", "India", "Indonesia", "Italy", "Japan", "South Korea", "Mexico", "Russia", "Saudi Arabia", "South Africa", "Turkey", "UK", "USA", "EU") top_bottom_5_oecd <- wiid_most_recent %>% filter(year > 2010, region %in% top_5_names | region %in% bottom_5_names | region %in% g20) %>% mutate(status = case_when( region %in% top_5_names & region %in% g20 ~ "G20 Member and Highest 5", region %in% bottom_5_names & region %in% g20 ~ "G20 Member and Lowest 5", region %in% top_5_names ~ "Highest 5", region %in% bottom_5_names ~ "Lowest 5", region %in% g20 ~ "G20 Member" )) %>% group_by(region) %>% summarize(status, mean_gini = mean(gini_reported, na.rm = TRUE)) %>% distinct() top_bottom_5_oecd %>% ggplot(aes(x = reorder(region, mean_gini), y = mean_gini, fill = status)) + geom_bar(stat = "identity") + coord_flip() + labs(title = "Gini Coefficient of G20 Countries\n and the 5 Countries with the Highest and Lowest Gini Coefficient", subtitle = "Only Gini Coefficients from after 2009 considered", y = "Gini Coefficient", fill = "Status") + scale_fill_viridis_d() + theme_minimal() + theme(text = element_text(size = 8), plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5), axis.title.y = element_blank(), legend.position = "bottom")
//Leetcode Problem Link: https://leetcode.com/problems/product-of-array-except-self use std::collections::VecDeque; impl Solution { pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> { let mut prefix = vec![0; nums.len()]; let mut suffix = vec![0; nums.len()]; let mut result = vec![0; nums.len()]; suffix[nums.len() - 1] = 1; for i in (1..nums.len()).rev() { suffix[i - 1] = suffix[i] * nums[i]; } prefix[0] = 1; for i in 1..nums.len() { prefix[i] = prefix[i - 1] * nums[i - 1]; } for i in 0..nums.len() { result[i] = prefix[i] * suffix[i]; } return result; } }
<template> <div> <h1>{{msg}}</h1> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <h2>学生年龄:{{myAge+1}}</h2> <button @click="updateAge">尝试修改收到的年龄</button> </div> </template> <script> export default { name:'StudentList', data() { console.log(this) return { msg:'我是一个尚硅谷的学生', myAge:this.age } }, methods:{ updateAge() { this.myAge++ } }, //简单声明接收 // props:['name','age','sex'] //接收的同时对数据进行类型限制 // props:{ // name:String, // age:Number, // sex:String // } //接收的同时对数据:进行类型限制+默认值的指定+必要性的限制 props:{ name:{ type:String, //name的类型是字符串 required:true, //name是必要的 }, age:{ type:Number, default:99 //默认值 }, sex:{ type:String, required:true } } } </script>
package com.example.avicultura_silsan.screen import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.LifecycleCoroutineScope import androidx.navigation.NavController import com.example.avicultura_silsan.components.retrieve_account.HeaderRetrieveAccount import com.example.avicultura_silsan.components.retrieve_account.insert_email.FooterInsertEmail import com.example.avicultura_silsan.components.retrieve_account.insert_email.FormInsertEmail import com.example.avicultura_silsan.view_model.RetrieveAccountViewModel @Composable fun InsertEmailScreen( navController: NavController, lifecycleScope: LifecycleCoroutineScope, viewModel: RetrieveAccountViewModel ) { var emailState by remember { mutableStateOf("") } Column( modifier = Modifier .fillMaxSize() .padding(25.dp, 15.dp) .background(Color.White) ) { HeaderRetrieveAccount() Spacer(modifier = Modifier.height(25.dp)) FormInsertEmail(emailState, onEmailChange = { emailState = it }) Spacer(modifier = Modifier.height(70.dp)) FooterInsertEmail(navController, lifecycleScope, viewModel,emailState) } }