text
stringlengths
184
4.48M
import Ingredients from "../models/ingredients"; interface Iingredients { name: string, group: string, unit: string, price: number, critical: number } interface IupdateIngredient { name?: string, group?: string, unit?: string, price?: number, critical?: number } interface IfunctionsReturns { status: number, messages: {} } export const createIngredients = async function (data: Iingredients): Promise<IfunctionsReturns> { const { name, group, unit, price, critical } = data const checkIngredient = await Ingredients.findOne({ name }) if (checkIngredient) { return { status: 400, messages: "The name is already exists" } } const newIngredients = new Ingredients() newIngredients.name = name, newIngredients.group = group, newIngredients.unit = unit, newIngredients.price = price, newIngredients.critical = critical, newIngredients.save() return { status: 200, messages: newIngredients } } export const allIngredients = async function (): Promise<IfunctionsReturns> { const ingredients = await Ingredients.find() return { status: 200, messages: ingredients } } export const getIngredientById = async function (id: string): Promise<IfunctionsReturns> { try { const ingredient = await Ingredients.findById({ _id: id }) return { status: 200, messages: ingredient } } catch (error) { return { status: 400, messages: "incorrect id" } } } export const updateIngredient = async function (id: string, data: IupdateIngredient): Promise<IfunctionsReturns> { const updateData: { name?: string, group?: string, unit?: string, price?: number, critical?: number } = {} for (const key in data) { if (data[key]) { updateData[key] = data[key] } } try { await Ingredients.findOneAndUpdate({ _id: id }, { $set: updateData }) const ingredient = await Ingredients.findById({ _id: id }) return { status: 200, messages: ingredient } } catch (error) { return { status: 400, messages: "incorrect id" } } }
# EXSM 3935: JavaScript Fundamentals - JavaScript Introduction Assignment **Deadline:** Sunday Jul 16, 2023 at 11:59 PM **GitHub Classroom Link:** [https://classroom.github.com/a/hd_uFeog](https://classroom.github.com/a/hd_uFeog) ## Introduction This assignment is meant to be a graded assignment to assess your ability in writing a basic JavaScript program. Follow the instructions below to complete the task, and be sure to read the hints if you are lost! If the hints do not help, be sure to reach out to us during office hours. ## Instructions: Your program should run in the following order: 1. Collect the first name of a user (remember to provide a prompt!) 2. Collect the last name of a user (remember to provide a prompt!) 3. Assign both the first and last name to a new variable named “fullname” (include a space between the first and last name in the new variable) 4. Replace any ‘o’ characters in “fullname” to be ‘a’ characters and output the result to the console application (lowercase ‘o’ only!) 5. Ask the user to enter a number larger than 10 (remember to provide a prompt!) 6. Ask the user to enter a number smaller than 10 (remember to provide a prompt!) 7. Output the remainder of the larger number divided by the smaller number to the console application ## Criteria **Total:** /5
import React, { useState } from 'react' import { Link, useNavigate, useParams } from "react-router-dom"; import SignNav from "../Components/SignNav/index"; import SignUp from "../Components/SignUp/index"; import { connect } from 'react-redux' import { signUpAction, } from '../redux' import { supabase } from '../configurations'; const SignUpPage = ({ appState, signupUser }) => { const new_supabase = supabase() const navigate = useNavigate(); const state = appState const [loading, setloading] = useState(false) const submit = (e) => { // console.log(e) setloading(true) new_supabase.auth.signUp( { email: e.email, password: e.password, }, { data: e } ) .then(success => { if (success.user == null) { setloading(false) alert("User with the details already exists.") } else { new_supabase.auth.signIn({ email: e.email, password: e.password }) .then(success2 => { if (success2.error == null) { new_supabase .from("user") .insert({ email: success2.email, data: success2, }) .then(response => { navigate("/userAdmin") }) } else { alert("An error occured") } setloading(false) }) .catch(error => { }) } console.log(success) }) .catch(error => { setloading(false) console.log(error) }) } window.scrollTo(0, 0); return ( <main> {console.log(state)} {loading == true && <> <div style={{ position: "fixed", width: "100%", height: "100%", left: "0px", top: "0px", background: "rgb(0,0,0,0.6)", zIndex: "2000" }}></div> </>} {/* */} <SignNav /> <SignUp submit={submit} /> </main> ); }; const mapStateToProps = state => { return { appState: state.user } } const mapDispatchToProps = (dispatch, encoded) => { return { signupUser: (payload) => dispatch(signUpAction(payload)), } } export default connect( mapStateToProps, mapDispatchToProps )(SignUpPage)
package userview import ( "errors" "github.com/DanPlayer/randomname" "log" "rt-chat/internal/global" "rt-chat/internal/object/user" "rt-chat/internal/result" "rt-chat/pkg/tools/tcaptcha" "rt-chat/pkg/tools/temail" "rt-chat/pkg/tools/tencrypt" "rt-chat/pkg/tools/tjwt" "rt-chat/pkg/tools/tredis" "rt-chat/pkg/tools/ttrans" "rt-chat/pkg/tools/tuuid" "strconv" "time" ) // JudgeExistFunc 根据类型、账号来判断用户是否存在 func JudgeExistFunc(vo user.Auth) (bool, user.Auth) { ua := user.Auth{} if vo.BasicId != 0 { ua.BasicId = vo.BasicId } if vo.IdentityType != "" { ua.IdentityType = vo.IdentityType } if vo.Identifier != "" { ua.Identifier = vo.Identifier } if vo.Credential != "" { ua.Credential = vo.Credential } return judgeExist(ua) } // IdentifierCodeFunc 向该账号发送验证码,账号的类型有手机号、邮箱...... func IdentifierCodeFunc(ic IdentifierCode) bool { return identifierCode(ic.IdentityType, ic.Identifier) } // RegisterFunc 注册用户函数,成功返回token,失败返回error func RegisterFunc(form RegisterVo) (string, error) { // 解密数据并返回 username, form, err := decryptRegisterData(form) if err != nil { return "", err } // 判断是否存在 b, _ := JudgeExistFunc(user.Auth{IdentityType: form.IdentityType, Identifier: form.Identifier}) if b { return "", errors.New("用户已存在,不能重复注册!") } // 判断验证码是否正确 if !codeIsValid(form) { return "", errors.New("验证码错误,请重新输入!") } // 添加到数据库 uid, err := addUserDB(username, form) if err != nil { return "", err } // 删除redis的code // 将redis中的验证码删除,防止多次使用 _, err = tredis.DelByKey(global.REDIS, form.Identifier+"-register") if err != nil { return "", err } token, err := tjwt.GenerateToken(strconv.Itoa(int(uid))) if err != nil { return "", err } // 返回bool,err return token, nil } // LoginFunc 登录用户函数,成功返回token,失败返回error func LoginFunc(form LoginVo) (string, error) { // 解密数据并返回 rv, err := decryptLoginData(form) if err != nil { return "", err } // 判断是否存在 b, u := JudgeExistFunc(rv) if !b { return "", errors.New("用户不存在,登录失败!") } token, err := tjwt.GenerateToken(strconv.Itoa(int(u.BasicId))) if err != nil { return "", err } // 返回bool,err return token, nil } // GetUserListFunc 获取用户列表函数,成功返回'用户切片',失败返回error func GetUserListFunc(p result.Page) ([]UserList, error) { return getList(p) } // DeleteByUuidFunc 删除用户函数,成功返回nil,失败返回error func DeleteByUuidFunc(uuid string) error { // 查询得到 *user.Basic ub, err := findByUUID(uuid) if err != nil { return err } deleteOne(ub) return nil } // ------------func分界线---------- // judgeExist 根据类型、账号来判断用户是否存在 func judgeExist(ua user.Auth) (bool, user.Auth) { u := user.Auth{} tx := global.DB.Where(&ua).Find(&u) if tx.RowsAffected == 0 { // 不存在 return false, user.Auth{} } else { // 存在 return true, u } } // identifierCode 发送验证码 func identifierCode(identityType, identifier string) bool { switch identityType { case user.EMAIL: co := "" var expire = time.Minute * 30 // 如果redis中有值,那么直接取出就行,不用再次生成验证码了 if s := tredis.GetString(global.REDIS, identifier+"-register"); s != "" && s != "key not exist" && s != "err" { co = s expire, _ = tredis.GetExpiration(global.REDIS, identifier+"-register") } else { co = tcaptcha.GenerateVerificationCode() tredis.SetString(global.REDIS, identifier+"-register", co, time.Minute*30) } go func() { err := temail.SendVerificationCode(identifier, co, expire) if err != nil { log.Println(err, "-验证码发送失败") } }() default: return false } return true } // decryptRegisterData 解密注册数据并返回 username、registerVO、error func decryptRegisterData(form RegisterVo) (string, RegisterVo, error) { /* { type: type identifier: RSA加密(username(aes加密) | phone/email(aes加密)) credential: password code: register_code } */ // rsa解密,得到 username(aes加密后) | identifier(aes加密后) plaintext, err := tencrypt.RsaDecrypt(ttrans.String2Bytes(form.Identifier)) if err != nil { return "", RegisterVo{}, err } res := ttrans.Bytes2String(plaintext) // 分隔符 | sep := "|" // a => [username(aes加密后),identifier(aes加密后)] arr := ttrans.SplitInString(res, sep) if len(arr) != 2 { return "", RegisterVo{}, errors.New("账号填写有误!") } // aes解密,得到 username []byte类型 u1, err := tencrypt.AesDecrypt(ttrans.String2Bytes(arr[0])) if err != nil { return "", RegisterVo{}, errors.New("用户名解密失败!") } username := ttrans.Bytes2String(u1) // aes解密,得到identifier []byte类型 i1, err := tencrypt.AesDecrypt(ttrans.String2Bytes(arr[1])) if err != nil { return "", RegisterVo{}, errors.New("账号解密失败!") } identifier := ttrans.Bytes2String(i1) form.Identifier = identifier return username, form, nil } // codeIsValid 判断验证码是否正确 func codeIsValid(form RegisterVo) bool { if s := tredis.GetString(global.REDIS, form.Identifier+"-register"); form.Code != s { return false } return true } // addUserDB 添加用户到数据库,成功返回uuid func addUserDB(username string, form RegisterVo) (uint, error) { // md5加密 credential := tencrypt.MD5Encrypt(form.Credential) // 登录类型:账密、QQ、WX、钉钉、github、微博等 UUID := tuuid.GenerateUUID() // 昵称取随机的,用了个github的库(github.com/DanPlayer/。。。) nickname := randomname.GenerateName() // 向数据库添加该字段 添加两个授权、一个基础 base := &user.Basic{Uuid: UUID, Nickname: nickname, Status: user.NORMAL} switch form.IdentityType { case user.EMAIL: base.Email = form.Identifier case user.PHONE: base.Phone = form.Identifier default: return 0, errors.New("未知的账号类型!") } // 添加base表 global.DB.Create(base) auth := &user.Auth{BasicId: base.ID, IdentityType: form.IdentityType, Identifier: form.Identifier, Credential: credential} // 添加auth表 global.DB.Create(auth) auth.IdentityType = user.NAME auth.Identifier = username // 添加auth表 global.DB.Create(auth) return base.ID, nil } // decryptLoginData 解密登录数据并返回 user_auth error func decryptLoginData(form LoginVo) (user.Auth, error) { // res 为rsa解密后的[]byte转的string decrypt, err := tencrypt.RsaDecrypt(ttrans.String2Bytes(form.Info)) if err != nil { return user.Auth{}, nil } res := ttrans.Bytes2String(decrypt) // sep 为分隔符, 例如: | sep := "|" // fs 为分割后的res, 例如: identityType|identifier|credential -> 1|1371546845|888miMa123456 fs := ttrans.SplitInString(res, sep) if len(fs) != 3 { return user.Auth{}, errors.New("数据有误,解密失败!") } // type identityType := fs[0] //// aes解密 //temp, _ := tencrypt.AesDecrypt(ttrans.String2Bytes(fs[1])) //// identifier //identifier := ttrans.Bytes2String(temp) identifier := fs[1] // credential credential := tencrypt.MD5Encrypt(fs[2]) return user.Auth{IdentityType: identityType, Identifier: identifier, Credential: credential}, nil } // getList 获取用户列表,返回list,error func getList(page result.Page) ([]UserList, error) { var users []user.Basic // 构建GORM查询 query := global.DB.Model(&user.Basic{}) // 添加模糊搜索条件 if page.Keyword != "" { // 构建LIKE语句 keyword := "%" + page.Keyword + "%" query = query.Where("nickname LIKE ? OR phone LIKE ? OR email LIKE ? OR address LIKE ?", keyword, keyword, keyword, keyword) } // 添加反向搜索条件 if page.Desc { query = query.Order("created_at DESC") } else { query = query.Order("created_at ASC") } // 添加分页条件 offset := (page.PageNum - 1) * page.PageSize query = query.Offset(offset).Limit(page.PageSize) // Unscoped() 方法是包括上已经软删除的用户 // 执行查询并预加载 Auth 信息 , 这个AuthList是basic新添加的,目的是与auth表关联 if err := query.Unscoped().Preload("AuthList").Find(&users).Error; err != nil { return nil, err } // 将查询结果转换为 UserList 结构 userList := make([]UserList, len(users)) for i, user0 := range users { identList := make([]Ident, len(user0.AuthList)) for j, auth := range user0.AuthList { identList[j] = Ident{ IdentityType: auth.IdentityType, Identifier: auth.Identifier, } } userList[i] = UserList{ Uuid: user0.Uuid, Nickname: user0.Nickname, Avatar: user0.Avatar, Status: user0.Status, Phone: user0.Phone, Email: user0.Email, Address: user0.Address, AuthList: identList, IsDeleted: user0.DeletedAt.Valid, } } return userList, nil } // findByUUID 根据uuid查询用户user_basic表,成功返回*user_basic,nil,失败返回nil,error func findByUUID(uuid string) (*user.Basic, error) { ub := new(user.Basic) err := global.DB.First(ub, "uuid = ?", uuid).Error if err != nil { return nil, err } return ub, nil } // deleteOne 软删除用户信息,需要将basic和auth表都删除 func deleteOne(ub *user.Basic) error { // 根据ub的id查询user_auth表 basicId := ub.ID // 软删除user_auth表(根据basic_id批量删除) global.DB.Where("basic_id = ?", basicId).Delete(&user.Auth{}) // 软删除user_basic表 global.DB.Delete(ub) return nil }
# DP On Stocks **Problems discussed** 1. [Buy and sell stocks I](#buy-and-sell-stocks-i) 1. [Buy and sell stocks II](#buy-and-sell-stocks-ii) 1. [Buy and sell stocks III](#buy-and-sell-stocks-iii) 1. [Buy and sell stocks IV](#buy-and-sell-stocks-iv) 1. [Buy and sell stocks with cooldown](#buy-and-sell-stocks-with-cooldown) 1. [Best Time to Buy and Sell Stock with Transaction Fee](#best-time-to-buy-and-sell-stock-with-transaction-fee) ## Buy and sell stocks I Find the problem on [leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) ### Problem Statement You are given an integer array prices where `prices[i]` is the price of a given stock on the $i^{\text{th}}$ day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. ### Approach - Pretty simple approach we can see for this, - We only sell with the minimum buy price to the left. - Now we record the max profit possible. Hence the following code ### Code ```cpp class Solution { public: int maxProfit(vector<int>& prices) { int min_ = INT_MAX; int max_profit = INT_MIN; for (int i = 0; i < prices.size(); i++) { min_ = std::min(min_, prices[i]); max_profit = std::max(max_profit, prices[i] - min_); } return max_profit; } }; ``` ## Buy and sell stocks II Find the problem on [Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) ### Problem Statement Problem statement is same as the last one but here you can buy multiple times (but not before you sell off first). You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). You are given an integer array prices where `prices[i]` is the price of a given stock on the $i^{\text{th}}$ day. Find maximum profit possible. ### Approach - This problem can be solved by greedy strategy, but requires a proof why that works. - However we don't need any argument as to why `DP` based solution is correct, because it explores all possibility of buy and sell choices. - If we look closely, we have 4 choices, if we bought previously then we can sell or not sell (2 choices) - if we have sold earlier on a given day we have 2 choices (buy or sell). - Based on that we write the recurrence and memoize to solve this problem. - In the following implementation `B` is indication for buy order availability and `N` for not availability. ### Code ```cpp class Solution { public: int subroutine(vector<int>& prices, int index, char order, map<int, map<char, int>>& dp) { if (index >= prices.size()) return 0; int profit = 0; if (dp.find(index) != dp.end()) { if ((*dp.find(index)).second.find(order) != (*dp.find(index)).second.end()) { return dp[index][order]; } } if (order == 'B') { // we can buy now dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp), dp[index + 1]['B'] = subroutine(prices, index + 1, 'B', dp); profit = std::max( dp[index + 1]['N'] - prices[index], // buy today dp[index + 1]['B'] // don't buy ); } else { // we have choice to sell dp[index + 1]['B'] = subroutine(prices, index + 1, 'B', dp); dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp); profit = std::max( prices[index] + dp[index + 1]['B'], // sell today dp[index + 1]['N'] ); } return dp[index][order] = profit; } int maxProfit(vector<int>& prices) { // 'B' enter the day with 'B'(buy) order available. 'N' not available map<int, map<char, int>> dp; return std::max(subroutine(prices, 0, 'B', dp), 0); } }; ``` Converting the code into **tabulation**, to reduce recursion space. ```cpp class Solution { public: int maxProfit(vector<int>& prices) { // 'B' enter the day with 'B'(buy) order available. 'N' not available int n = prices.size(); int dp[n + 1][2]; // 1 -> buy order available // 0 -> buy order not available // base cases dp[n][1] = 0; dp[n][0] = 0; for (int index = n - 1; index >= 0; index--) { for (int order = 0; order <= 1; order++) { int profit = 0; if (order == 1) { profit = std::max( dp[index + 1][0] - prices[index], // buy today dp[index + 1][1] // don't buy ); } else { profit = std::max( prices[index] + dp[index + 1][1], // sell today dp[index + 1][0] ); } dp[index][order] = profit; } } return dp[0][1]; } }; ``` **Even more optimization** We are using only one index up from the currently exploring index in the `dp` table. So no need to store `index + 1` once we done exploring `index` for some `index` $\in [1, n-1]$. We can replace current `index + 1` entries with `index` entries before we reach `index - 1`. Hence we first set `dp` as a `pair<int, int>`. Then we say `dp.first` is same as `dp[index + 1][0]` and `dp.second` is same as `dp[index + 1][1]`, then replace `dp.first` and `dp.second` accordingly. ```cpp class Solution { public: pair<int, int> dp; int maxProfit(vector<int>& prices) { int n = prices.size(); // base cases dp.first = 0; // same as dp[idx + 1][1] dp.second = 0; for (int index = n - 1; index >= 0; index--) { for (int order = 0; order <= 1; order++) { int profit = 0; if (order == 1) { profit = std::max( dp.first - prices[index], // buy today dp.second // don't buy ); dp.second = profit; } else { profit = std::max( prices[index] + dp.second, // sell today dp.first ); dp.first = profit; } } } return dp.second; } }; ``` ## Buy and sell stocks III Find the problem on [Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii) ### Problem Statement You are given an integer array prices where `prices[i]` is the price of a given stock on the $i^{\text{th}}$ day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again) ### Approach The approach will be pretty much the same but we'll introduce a `cap` variable in the recursion, whenever a sell happens we can reduce this `cap` to `cap - 1`. Then stop the recursion when we reach `cap`. ### Code ```cpp class Solution { public: int subroutine(vector<int>& prices, int index, int order, vector<vector<vector<int>>>& dp, int cap) { if (cap <= 0) return 0; if (index >= prices.size()) return 0; int profit = 0; if (dp[index][order][cap] != -1) return dp[index][order][cap]; if (order) { // we can buy now dp[index + 1][0][cap] = subroutine(prices, index + 1, 0, dp, cap), dp[index + 1][1][cap] = subroutine(prices, index + 1, 1, dp, cap); profit = std::max( dp[index + 1][0][cap] - prices[index], // buy today dp[index + 1][1][cap] // don't buy ); } else { // we have choice to sell dp[index + 1][1][cap - 1] = subroutine(prices, index + 1, 1, dp, cap - 1); dp[index + 1][0][cap] = subroutine(prices, index + 1, 0, dp, cap); profit = std::max( prices[index] + dp[index + 1][1][cap - 1], // sell today dp[index + 1][0][cap] ); } return dp[index][order][cap] = profit; } int maxProfit(vector<int>& prices) { int n = prices.size(); vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(2, vector<int>(3, -1))); return subroutine(prices, 0, 1, dp, 2); } }; ``` ## Buy and sell stocks IV Find the problem on [Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv) ### Problem statement You are given an integer array prices where `prices[i]` is the price of a given stock on the $i^{\text{th}}$ day. Find the maximum profit you can achieve. You may complete at most $k$ transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again) ### Approach Once simple modification we need to do, that is update the initial call from $2$ to $k$ and update the `cap` size in the `dp` table from $3$ to $k + 1$ to accomodate $0 \dots k$. ### Code ```cpp class Solution { public: int subroutine(vector<int>& prices, int index, int order, vector<vector<vector<int>>>& dp, int cap) { if (cap <= 0) return 0; if (index >= prices.size()) return 0; int profit = 0; if (dp[index][order][cap] != -1) return dp[index][order][cap]; if (order) { // we can buy now dp[index + 1][0][cap] = subroutine(prices, index + 1, 0, dp, cap), dp[index + 1][1][cap] = subroutine(prices, index + 1, 1, dp, cap); profit = std::max( dp[index + 1][0][cap] - prices[index], // buy today dp[index + 1][1][cap] // don't buy ); } else { // we have choice to sell dp[index + 1][1][cap - 1] = subroutine(prices, index + 1, 1, dp, cap - 1); dp[index + 1][0][cap] = subroutine(prices, index + 1, 0, dp, cap); profit = std::max( prices[index] + dp[index + 1][1][cap - 1], // sell today dp[index + 1][0][cap] ); } return dp[index][order][cap] = profit; } int maxProfit(int k, vector<int>& prices) { int n = prices.size(); vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(2, vector<int>(k + 1, -1))); return subroutine(prices, 0, 1, dp, k); } }; ``` ## Buy and sell stocks with cooldown Find the problem on [leetcode $\to$](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/submissions/) ### Problem Statement Same as above, find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times, same as [Buy and sell stocks II](#buy-and-sell-stocks-ii)) with the following restrictions: - After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). ### Approach We write the same exact code as [Buy and sell stocks II](#buy-and-sell-stocks-ii) and we change the sell to continue from `index + 2` because after a sell we go have one day cooldown. ### Code ```cpp class Solution { public: int subroutine(vector<int>& prices, int index, char order, map<int, map<char, int>>& dp) { if (index >= prices.size()) return 0; int profit = 0; if (dp.find(index) != dp.end()) { if ((*dp.find(index)).second.find(order) != (*dp.find(index)).second.end()) { return dp[index][order]; } } if (order == 'B') { // we can buy now dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp), dp[index + 1]['B'] = subroutine(prices, index + 1, 'B', dp); profit = std::max( dp[index + 1]['N'] - prices[index], // buy today dp[index + 1]['B'] // don't buy ); } else { // we have choice to sell dp[index + 2]['B'] = subroutine(prices, index + 2, 'B', dp); dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp); profit = std::max( prices[index] + dp[index + 2]['B'], // sell today dp[index + 1]['N'] ); } return dp[index][order] = profit; } int maxProfit(vector<int>& prices) { // 'B' enter the day with 'B'(buy) order available. 'N' not available map<int, map<char, int>> dp; return subroutine(prices, 0, 'B', dp); } }; ``` ## Best Time to Buy and Sell Stock with Transaction Fee ### Problem Statement You are given an integer array prices where `prices[i]` is the price of a given stock on the $i^{\text{th}}$ day. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again) ### Approach Same as the [Buy and sell stocks II](#buy-and-sell-stocks-ii) but here we'll pass a new variable called `fee`, and once a buy is done we subtract `fee` from profit. ### Code ```cpp class Solution { public: int subroutine(vector<int>& prices, int index, char order, map<int, map<char, int>>& dp, int fee) { if (index >= prices.size()) return 0; int profit = 0; if (dp.find(index) != dp.end()) { if ((*dp.find(index)).second.find(order) != (*dp.find(index)).second.end()) { return dp[index][order]; } } if (order == 'B') { // we can buy now dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp, fee), dp[index + 1]['B'] = subroutine(prices, index + 1, 'B', dp, fee); profit = std::max( dp[index + 1]['N'] - prices[index] - fee, // buy today, charge fee once the buy is done dp[index + 1]['B'] // don't buy ); } else { // we have choice to sell dp[index + 1]['B'] = subroutine(prices, index + 1, 'B', dp, fee); dp[index + 1]['N'] = subroutine(prices, index + 1, 'N', dp, fee); profit = std::max( prices[index] + dp[index + 1]['B'], // sell today dp[index + 1]['N'] ); } return dp[index][order] = profit; } int maxProfit(vector<int>& prices, int fee) { map<int, map<char, int>> dp; return subroutine(prices, 0, 'B', dp, fee); } }; ```
/*********************************************** Gameka: A game development tool for non-programmers Copyright (C) 2011 Igor Augusto de Faria Costa This software is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ************************************************/ #ifndef GAMEOBJECTANIMATION_H #define GAMEOBJECTANIMATION_H #include <string> #include <vector> #include <stdio.h> #include "sprite.h" #include "animationdata.h" #include "point.h" class Sprite; class AnimationData; class Point; /** * @brief Entidade para guardar animações de um objeto. * */ class GameObjectAnimation { public: /** * @brief Construtor. * */ GameObjectAnimation(); int id; /**< Identificador. */ int type; /**< Tipo: \n 1: Estático; 2: Animado. */ std::string name; /**< Nome. */ std::vector<Sprite*> *sprites; /**< Array de 32 direções para sprites. */ std::vector<AnimationData*> *animations; /**< Array de 32 direções para animações. */ std::vector<int> *types; /**< Array de 32 posições pra dizer se deve acessar o array de sprites ou de animação de acordo com o tipo */ std::vector<bool> horizontalInvert; /**< Inverte horizontalmente a animação (32 posições, para cada direção). */ std::vector<bool> verticalInvert; /**< Inverte verticalmente a animação (32 posições, para cada direção). */ std::vector<Point> adjustments; /**< Ajustes no ponto de desenho (32 posições, para cada direção). */ int numDirectionFactor; /**< Não mais utilizado. */ static const int STATIC = 1; /**< */ static const int ANIMATED = 2; /**< */ }; #endif // GAMEOBJECTANIMATION_H
// MenuService.java package com.example.usercontent.service; import com.example.usercontent.model.Menu; import com.example.usercontent.model.Restaurant; import com.example.usercontent.repository.MenuRepository; import com.example.usercontent.repository.RestaurantRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class MenuService { @Autowired private MenuRepository menuRepository; @Autowired private RestaurantRepository restaurantRepository; public Menu createMenu(Menu menu) { Optional<Restaurant> restaurant = restaurantRepository.findById(menu.getRestaurant().getId()); if (restaurant.isPresent()) { menu.setRestaurant(restaurant.get()); return menuRepository.save(menu); } else { throw new RuntimeException("Restaurant not found with id " + menu.getRestaurant().getId()); } } public List<Menu> getAllMenus() { return menuRepository.findAll(); } public Optional<Menu> getMenuById(Long id) { return menuRepository.findById(id); } public Menu updateMenu(Long id, Menu menuDetails) { return menuRepository.findById(id) .map(menu -> { menu.setName(menuDetails.getName()); Optional<Restaurant> restaurant = restaurantRepository.findById(menuDetails.getRestaurant().getId()); if (restaurant.isPresent()) { menu.setRestaurant(restaurant.get()); } else { throw new RuntimeException("Restaurant not found with id " + menuDetails.getRestaurant().getId()); } return menuRepository.save(menu); }).orElseThrow(() -> new RuntimeException("Menu not found with id " + id)); } public void deleteMenu(Long id) { menuRepository.deleteById(id); } }
import java.util.Scanner; public class PAC1Ex1 { private static long motzkin(int n, long motzkinNMinus1, long motzkinNMinus2) { //metodo que define numeros de motzkin // Base cases if (n == 0 || n == 1) return 1; return ((((2 * n + 1) * motzkinNMinus1 + (3 * n - 3) * motzkinNMinus2)) / (n + 2)); } public static long printMotzkin(int n) { // metodo que muestra por pantalla los n+1 primeros numeros de Motzkin long motzkin, motzkinNMinus1 = 1, motzkinNMinus2 = 1; for (int i = 0; i <= n; i++) { motzkin = motzkin(i, motzkinNMinus1, motzkinNMinus2); System.out.print(motzkin + ", "); motzkinNMinus2 = motzkinNMinus1; motzkinNMinus1 = motzkin; } return motzkinNMinus1; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; do { System.out.print("Enter the value of N (only whole numbers): "); n = in.nextInt(); if (n == 0) { System.out.println("The value of N must be a whole number. Try again."); } } while (n == 0); printMotzkin(n); // ejecuta el metodo } }
import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; import User from '../models/user.js'; import ExpressError from '../utilities/express-error.js'; export const registerUser = async (req, res) => { const { password, mobile_no, first_name, last_name } = req.body; const saltRounds = 10; const hash_password = await bcrypt.hash(password, saltRounds); const newUser = new User({ mobile_no, first_name, last_name, hash_password }); const json_secret_key = process.env.JWT_SECRET_KEY; const token = jwt.sign(newUser._id.toString(), json_secret_key); await newUser.save(); res.status(200).send({ success: true, token, user: { ...newUser.toJSON(), hash_password: undefined } }); }; export const loginUser = async (req, res) => { const { mobile_no, password } = req.body; const user = await User.findOne({ mobile_no }); if (!user) { throw new ExpressError("User doesn't exist. Please register!", 400); } const match = await bcrypt.compare(password, user.hash_password); if (match) { const json_secret_key = process.env.JWT_SECRET_KEY; const token = jwt.sign(user._id.toString(), json_secret_key); res.status(200).send({ success: true, user: { ...user.toJSON(), hash_password: undefined }, token }); } else { throw new ExpressError("Mobile Number and password doesn't match", 400); } }; export const fetchSelf = async (req, res) => { const { user } = req; if (!user) { throw new ExpressError('User not found', 401); } res.status(200).send({ success: true, user: { ...user.toJSON(), hash_password: undefined } }); };
import React, { useState } from "react"; import { Container, Radio, Rating } from "./RatingStyles"; import { FaStar } from "react-icons/fa"; function Rate() { const [rate, setRate] = useState(0); return ( <Container> {[...Array(5)].map((item, index) => { const givenRating = index + 1; return ( <label key={index}> <Radio type="radio" value={givenRating} onClick={() => { setRate(givenRating); }} /> <Rating> <FaStar color={ givenRating < rate || givenRating === rate ? "#DF9511" : "rgb(192,192,192)" } /> </Rating> </label> ); })} <span className="ml-4 font-bold">{rate}</span> </Container> ); } export default Rate;
import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import './AdminHome.css'; import no_image_img from '../../../assets/no-image.jpg'; // import products from '../../../assets/products'; import Product from "../../../components/product/Product"; import axios from "axios"; const AdminHome = () => { const token = "Token " + localStorage.getItem("token"); const [products, setProducts] = useState([]); const fetchProducts = () => { axios({ method: "get", url: "http://localhost:8000/api/stores/products/", headers: { Accept: 'application/json', Authorization: token } }) .then((response) => { console.log(response.data); setProducts(response.data); }, (error) => { console.log(error); }) }; useEffect(() => { fetchProducts(); }, []); return ( <div className="products-container"> <div className="products"> <h1>All Products</h1> <hr /> <div> <Link to="/admin/product/add"><p>Add a new product</p></Link> </div> <div className="product"> {products.map((item, i) => { return ( <div> <Link to={`/admin/product/${item.id}`}> <Product key={i} id={item.id} productName={item.name} productDescription={item.description} productImage={item.img} productPrice={item.price} /> </Link> </div> ) })} </div> </div> </div> ) } export default AdminHome;
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Base.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jbarbay <jbarbay@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/03 14:41:37 by jbarbay #+# #+# */ /* Updated: 2024/06/03 16:29:40 by jbarbay ### ########.fr */ /* */ /* ************************************************************************** */ #include "Base.hpp" #include "A.hpp" #include "B.hpp" #include "C.hpp" #include <exception> Base::~Base() { std::cout << "Base destructor called" << std::endl; } Base * generate(void) { std::srand(std::time(0)); int random_num = rand(); Base *instance; if (random_num % 3 == 0) instance = new A(); if (random_num % 3 == 1) instance = new B(); if (random_num % 3 == 2) instance = new C(); return (instance); } void identify(Base* p) { // std::cout << "function called with pointer: "; A *a = dynamic_cast<A*>(p); if (a) { std::cout << "A" << std::endl; return ; } B *b = dynamic_cast<B*>(p); if (b) { std::cout << "B" << std::endl; return ; } C *c = dynamic_cast<C*>(p); if (c) { std::cout << "C" << std::endl; return ; } std::cout << "Unknown type\n"; } void identify(Base& p) { // std::cout << "function called with reference: "; try { A &a = dynamic_cast<A&>(p); (void)a; std::cout << "A" << std::endl; } catch(const std::exception& e) { try { B &b = dynamic_cast<B&>(p); (void)b; std::cout << "B" << std::endl; } catch(const std::exception& e) { std::cout << "C" << std::endl; } } }
class Public::PostsController < ApplicationController def new @post = Post.new end def create @post = Post.new(post_params) @post.customer_id = current_customer.id @post = current_customer.posts.build(post_params) @post.genre_id = params[:post][:genre_id] if @post.save! #↓まずtimeline.post_idとtimeline.rt_idをsaveらいらいする #次にタイムラインモデルを作り、タイムラインアブルに"post"を入れ、saveで保存する #うまくタイムラインアブルに値を入れることができたらtimelinesのindex.html.erbに #投稿などが表示されるはず timeline = Timeline.new timeline.timelineable = @post timeline.customer_id = current_customer.id params[:timelineable_type] = "post" timeline.save! #ポリモーフィック関連付けで"timelineable"に自分がフォローしている人の"id"もpostのcreate時に一緒に入れるため、ここに記述 #follower_customersにしている理由は:follower_customers# 被フォロー関係を通じて参照→自分をフォローしている人にすることで #自分がフォローしている人=相手から見ると自分をフォローしている人(follower_customers)となるため #表示するものはcurrent_customer.follower_customers(自分をフォローしている人の投稿(相互関係的に)になる) current_customer.follower_customers.each do | customer | timeline = Timeline.new timeline.timelineable = @post timeline.customer_id = customer.id timeline.save! end flash[:notice] = "投稿に成功しました" redirect_to post_path(@post.id) else flash[:notice] = "入力内容に不備があります。未入力での投稿はできません。" redirect_to new_post_path end end def index @posts = Post.all @post = Post.new @customer = current_customer end def show @post = Post.find(params[:id]) @post_comment = PostComment.new end def update @post = Post.find(params[:id]) @post.update(post_params) flash[:notice] = "You have updated book successfully." if @post.save redirect_to post_path(@post.id) else render :edit end end def edit @post = Post.find(params[:id]) end def destroy post = Post.find(params[:id]) post.destroy redirect_to posts_path end private def post_params params.require(:post).permit(:content, :place, :image, :genre_id, :timelineable_type, :timeline) end end
package adt.queue; import adt.linkedList.DoubleLinkedList; import adt.linkedList.DoubleLinkedListImpl; public class QueueDoubleLinkedListImpl<T> implements Queue<T> { protected DoubleLinkedList<T> list; protected int size; public QueueDoubleLinkedListImpl(int size) { this.size = size; this.list = new DoubleLinkedListImpl<T>(); } @Override public void enqueue(T element) throws QueueOverflowException { if(element != null) { if(isFull()) { throw new QueueOverflowException(); } list.insert(element); } } @Override public T dequeue() throws QueueUnderflowException { if(isEmpty()) { throw new QueueUnderflowException(); } T head = head(); list.removeFirst(); return head; } @Override public T head() { if(isEmpty()) return null; return (T) ((DoubleLinkedListImpl<T>) list).getHead().getData(); } @Override public boolean isEmpty() { return this.list.isEmpty(); } @Override public boolean isFull() { return list.size() == size; } }
import React, { useState, useEffect } from 'react'; import { useFirebase } from './UserRoleContext'; import { ToastContainer, toast } from "react-toastify"; const BtcTaskList = () => { // Rename the function to start with an uppercase letter const { userImg, userEmail, userFullName, userID, userPhoneNo ,userRole, userBalance, slots, setUserBalance, accountLimit, setAccountLimit, referralsBalance, setReferralsBalance, dailyDropBalance, setDailyDropBalance, isUserActive, setIsUserActive, referralsCount, setReferralsCount, totalReferrals, setTotalReferrals, referralCode, setReferralCode, hasPaid, referredUsers, setReferredUsers, adRevenue, setAdRevenue, deposit, setDeposit, currencySymbol, country } = useFirebase(); const [tasks, setTasks] = useState([]); const [btcTx, setBtcTx] = useState([]); useEffect(() => { fetchPendingBtcDeposits(); }, []); const fetchPendingBtcDeposits = async () => { try { const response = await fetch('https://broker-base.onrender.com/api/getBtcDeposits'); const transactions = await response.json(); setBtcTx(transactions); } catch (error) { console.error('Error fetching tasks:', error.message); } }; // change state of btc tasks (transactions and temp data); const changePaymentStatus = async (transactionId, newStatus, userId) => { try { const response = await fetch(`https://broker-base.onrender.com/api/updatePaymentStatusAndDelete/${transactionId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ newStatus, userId }), }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // If the request is successful, call another function toast.success(`Documents Updated!`, { toastId: 'toast-change-success', }); } catch (error) { console.error('Error updating payment status:', error); toast.error(`Failed to update documents!`, { toastId: 'toast-change-failed', }); } }; return ( <div> <ToastContainer /> <h1>Task Manager</h1> <div className="custom-task-list d-block"> <> {btcTx.map((tx) => ( <div key={tx.id} className="custom-task-card"> {/* Display transaction details */} <p>Transaction ID: {tx.payment_id}</p> <p>Amount: {tx.price_amount}</p> <p>Status: {tx.payment_status}</p> <p>User ID: {tx.userID}</p> <p>Payment Description: {tx.order_description}</p> {/* Buttons to change payment status */} <div className='d-flex justify-content-between align-items-center'> <button className='btn btn-success' onClick={() => changePaymentStatus(tx.payment_id, 'success', tx.userID)}>Mark as Approved</button> <button className='btn btn-danger' onClick={() => changePaymentStatus(tx.payment_id, 'failed', tx.userID)}>Mark as Declined</button> </div> </div> ))} </> </div> </div> ); }; export default BtcTaskList;
import React, { useContext, useEffect } from 'react' import "./style.scss" import { Link } from 'react-router-dom' import CircularSelector from '../../frames/circular_selector/CircularSelector' import { frame_selector, models, style_selector } from '../../../constants/frame' import CustomisationContext from '../../../contexts/CustomisationContext' import Render from '../../frames/render/Render' import full_picture from "../../../assets/home/porsche-model-1.png" import { smooth_scroll } from '../../../functions/links' import arrow_down from "../../../assets/home/arrow-down.svg" import { HashLink } from 'react-router-hash-link' const Hero = () => { const {frame, set_frame} = useContext(CustomisationContext); useEffect(() => { const links = document.getElementsByClassName("link-smooth") for (let index = 0; index < links.length; index++) { const link = links[index]; link.addEventListener("click", smooth_scroll); } return () => { for (let index = 0; index < links.length; index++) { const link = links[index]; link.removeEventListener("click", smooth_scroll); } } }, []) return ( <section id="home-hero"> <div className='title-container'> <h1>L'art automobile encadré</h1> <span className='absolute-frame'>cadres</span> <p className='light-p'>Morem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate libero et velit interdum, ac aliquet odio mattis. </p> <Link to="frames" className='main-button'> Créer son cadre </Link> <div className='hide-mobile'> <CircularSelector title={"Style"} subtitle={"Fond du cadre"} list={style_selector} select={(id) => set_frame({style: id})} selected_id={frame.style} /> <CircularSelector title={"Matière"} subtitle={"Cadre"} list={frame_selector} select={(id) => set_frame({frame: id})} selected_id={frame.frame} /> <a href="/#home-text-image-section" className='link-smooth brand-link'> <img src={arrow_down} /> <span>La marque<br/>et ses valeurs</span> </a> </div> </div> <div className='hero-frame-container'> <div className='renders'> <Render is_home={true}/> </div> <div className='car-container'> <div className='name-pointer'> <span className='title'>{models[frame.model].brand}</span> <span className='choice'>{models[frame.model].model}</span> </div> <img src={models[frame.model].image} className="car-full-pic" /> <div className='product-headlines'> <div className='top-data'> <div className='data'> <span className='value'>320 km/h</span> <span className='description'>Vitesse max</span> </div> <div className='data'> <span className='value'>2,8 s</span> <span className='description'>0-100 km/h</span> </div> <div className='data'> <span className='value'>650 cv</span> <span className='description'>Puissance</span> </div> </div> <p className='description main-car-desc light-p'>La Porsche 911 Turbo 2022 est la définition même de la beauté brute, avec son design intemporel et sa technologie de pointe.</p> </div> </div> </div> </section> ) } export default Hero
import stl from "./TopBar.module.css"; import { faArrowLeft, faTrashCan } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "react-router-dom"; import { useContext, useEffect } from "react"; import { PaginationContext } from "../../../../../utils/paginationstate/PaginationProvider"; import FetchUsername from "../fetchUsername/FetchUsername"; import { osrsXpTable } from "../../../../../utils/playerStats"; const TopBar = (props) => { const { setSubState } = useContext(PaginationContext); const navigate = useNavigate(); const handleMenuSwitch = () => { setSubState(null); navigate("/skillcalculators"); }; const handleUserReset = () => { props.setSkills(null); props.setPlayerName(null); props.setSkillsExp(null); }; const arePropsDefined = props.skills; useEffect(() => { setSubState(props.title); }, [setSubState, props.title, props]); const calculateExpUntilNextLevel = () => { const skill = props.skillname; const currentLvl = +props.currentLvl; const currentExp = +props.currentExp[skill]; const nextLevelStartExp = osrsXpTable[currentLvl + 1]; const remainder = nextLevelStartExp - currentExp; const result = isNaN(+remainder) ? "?" : remainder.toLocaleString(); return result; }; return ( <div className={stl.topBar}> <FontAwesomeIcon icon={faArrowLeft} className={stl.backArrow} onClick={handleMenuSwitch} /> <img src={props.iconSrc} alt={`${props.title} Level`} className={stl.skillImg} /> <span className={stl.skillTitle}>{props.title}</span> {arePropsDefined ? ( <div className={stl.userStatsBox}> <div className={stl.playerInfo}> <div className={stl.userBlock}> <span className={stl.playerName}>{props?.playerName}</span> <span className={stl.playerLvl}> Level {props?.skills && props?.skills[props.skillname]} </span> </div> {props.skills && calculateExpUntilNextLevel() > 0 && ( <div className={stl.remainderBlock}> <div className={stl.toGoBlock}> <span className={stl.expToGo}>XP</span> <span className={stl.expToGoLevel}>Level</span> </div> <span className={stl.remaining}> {props.skills && calculateExpUntilNextLevel()} </span> </div> )} </div> <div className={stl.canWrapper}> <FontAwesomeIcon icon={faTrashCan} className={stl.trashcan} onClick={handleUserReset} /> </div> </div> ) : ( <FetchUsername setSkills={props.setSkills} setSkillsExp={props.setSkillsExp} setPlayerName={props.setPlayerName} /> )} </div> ); }; export default TopBar;
package model; import dao.BillingAddressDao; public class BillingAddress extends Model { public static final String table = "billing_addresses"; public static final String primaryKeyColumnName = "id"; public BillingAddress(BillingAddressDao dao) { super(dao); } public BillingAddress(BillingAddressDao dao, int id) { super(dao, id); } @Override public String getPrimaryKeyColumnName() { return primaryKeyColumnName; } @Override public String getTable() { return table; } @Override protected String[] getAttributeNames() { return new String[] {"street", "province", "country", "postal_code"}; } // Getters & Setters public void setStreet(String street) { setAttribute("street", street); } public String getStreet() { return getAttribute("street"); } public void setProvince(String province) { setAttribute("province", province); } public String getProvince() { return getAttribute("province"); } public void setCountry(String country) { setAttribute("country", country); } public String getCountry() { return getAttribute("country"); } public void setPostalCode(String postalCode) { setAttribute("postal_code", postalCode); } public String getPostalCode() { return getAttribute("postal_code"); } public String toString() { String result = this.getStreet() + ", " + this.getProvince() + " " + this.getPostalCode() + " " + this.getCountry(); return result; } }
import { ButtonLink as UtrechtButtonLink, LinkButton as UtrechtLinkButton, } from '@utrecht/component-library-react'; import React from 'react'; import FAIcon from '../FAIcon'; import OFButton from './OFButton'; export default { title: 'Pure React components / OF Button', component: OFButton, argTypes: { children: {table: {disable: true}}, }, parameters: { controls: {sort: 'requiredFirst'}, }, }; const render = ({label, component, ...args}) => { const ButtonComponent = component; return <ButtonComponent {...args}>{label}</ButtonComponent>; }; export const UtrechtDefault = { render, args: { label: 'Default', component: OFButton, }, }; export const UtrechtPrimary = { render, args: { label: 'Primary', component: OFButton, appearance: 'primary-action-button', }, }; export const UtrechtSecondary = { render, args: { label: 'Secondary', component: OFButton, appearance: 'secondary-action-button', }, }; export const UtrechtDanger = { render, args: { label: 'Danger', component: OFButton, appearance: 'primary-action-button', hint: 'danger', }, }; export const UtrechtLinkLooksLikeDefaultButton = { render, args: { label: 'Default', component: UtrechtButtonLink, href: '#', }, }; export const UtrechtLinkLooksLikePrimaryButton = { render, args: { label: 'Primary', component: UtrechtButtonLink, href: '#', appearance: 'primary-action-button', }, }; export const UtrechtLinkLooksLikeSecondaryButton = { render, args: { label: 'Secondary', component: UtrechtButtonLink, href: '#', appearance: 'secondary-action-button', }, }; export const UtrechtLinkLooksLikeDangerButton = { render, args: { label: 'Danger', component: UtrechtButtonLink, href: '#', appearance: 'primary-action-button', hint: 'danger', }, }; export const UtrechtButtonLooksLikeLink = { render, args: { label: 'Link-like button', component: UtrechtLinkButton, }, }; export const UtrechtIconButton = { render, args: { label: <FAIcon icon={'pen'} />, component: OFButton, appearance: 'subtle-button', }, }; export const UtrechtIconButtonDanger = { render, args: { label: <FAIcon icon={'pen'} />, component: OFButton, appearance: 'subtle-button', hint: 'danger', }, }; export const UtrechtButtonDisabled = { render, args: { label: 'Disabled', component: OFButton, appearance: 'primary-action-button', disabled: true, }, };
<script setup> import { onMounted, ref } from "vue"; import { useRouter, useRoute } from "vue-router"; import UserServices from "../services/UserServices"; import OrderServices from "../services/OrderServices"; import CustomerServices from "../services/CustomerServices"; const route = useRoute(); const router = useRouter(); const newOrder = ref({ pickupTime: "", deliveryTime: "", blocks: "", quotedPrice: "", customerId: "", deliverToCustomerId: "", userId: "", finalBill: "", }); let isAddOrder = ref(true); let isEditClerk = ref(false); const pickupDate = ref(null); const pickupTime = ref(null); const deliveryDate = ref(null); const deliveryTime = ref(null); const customers = ref([]); const selectedCustomer = ref(null); const selectedDeliverToCustomer = ref(null); const snackbar = ref({ value: false, color: "", text: "", }); onMounted(async () => { const user = localStorage.getItem("user"); if(user === null){ router.push({ name: "login" }); } if(JSON.parse(user).role < 1){ router.push({ name: "home" }); } // console.log(newOrder); if (user !== null) { newOrder.value.userId = JSON.parse(user).id; } getCustomers(); // console.log(newOrder.value); }); async function getCustomers() { await CustomerServices.getCustomers() .then((response) => { customers.value = response.data; }) .catch((error) => { console.log(error); snackbar.value.value = true; snackbar.value.color = "error"; snackbar.value.text = error.response.data.message; }); } async function getClerk() { await UserServices.getUser(route.params.id) .then((response) => { newUser.value = response.data[0]; }) .catch((error) => { console.log(error); }); } async function updateClerk() { await UserServices.updateUser(newUser.value.id, newUser.value) .then(() => { snackbar.value.value = true; snackbar.value.color = "green"; snackbar.value.text = `${newUser.value.firstName} updated successfully!`; }) .catch((error) => { console.log(error); snackbar.value.value = true; snackbar.value.color = "error"; snackbar.value.text = error.response.data.message; }); await getClerk(); } async function addOrder() { let pickUp = pickupDate.value +" "+ pickupTime.value; let delivery = deliveryDate.value +" "+ deliveryTime.value; if(new Date(pickUp) > new Date(delivery)){ alert("Pick Up DateTime cannot be after Delivery DateTime"); return; } newOrder.value.pickupTime = pickUp; newOrder.value.deliveryTime = delivery; newOrder.value.customerId = selectedCustomer.value.id; newOrder.value.deliverToCustomerId = selectedDeliverToCustomer.value.id; await OrderServices.addOrder(newOrder.value).then( () => { snackbar.value.value = true; snackbar.value.color = "green"; snackbar.value.text = `Order created successfully!`; setTimeout(()=> {router.push({ name: "home" });}, 5000); } ) .catch((error) => { console.log(error); snackbar.value.value = true; snackbar.value.color = "error"; snackbar.value.text = error.response.data.message; }); } </script> <template> <v-container> <v-row align="center"> <v-col cols="10" ><v-card-title class="pl-0 text-h4 font-weight-bold" >Create Order </v-card-title> </v-col> </v-row> <v-row> <v-col> <v-card class="rounded-lg elevation-5"> <v-form> <v-card-text> <v-text-field v-model="pickupDate" label="Pick Up Date" type="date" required ></v-text-field> <v-text-field v-model="pickupTime" label="Pick Up Time" type="time" required ></v-text-field> <v-text-field v-model="deliveryDate" label="Delivery Date" type="date" required ></v-text-field> <v-text-field v-model="deliveryTime" label="Delivery Time" type="time" required ></v-text-field> <v-autocomplete v-model="selectedCustomer" :items="customers" item-title="name" item-value="id" label="Select Pick Up Customer" placeholder="Search Customers" persistent-hint return-object auto-select-first hide-selected clearable ></v-autocomplete> <v-autocomplete v-model="selectedDeliverToCustomer" :items="customers" item-title="name" item-value="id" label="Select Drop Off Customer" placeholder="Search Customers" persistent-hint return-object auto-select-first hide-selected clearable ></v-autocomplete> <!-- <v-text-field v-model="newOrder.blocks" label="Blocks" required ></v-text-field> <v-text-field v-model="newOrder.quotedPrice" label="Quoted Price" required ></v-text-field> <v-text-field v-model="newOrder.finalBill" label="Final Bill" required ></v-text-field> --> </v-card-text> <v-card-actions class="pt-0"> <v-btn variant="flat" color="primary" @click=" isAddOrder ? addOrder() : isEditClerk ? updateClerk() : false " > {{ isAddOrder ? "Create Order" : isEditClerk ? "Update Clerk" : "" }} </v-btn> <v-spacer></v-spacer> </v-card-actions> </v-form> </v-card> </v-col> </v-row> <v-snackbar v-model="snackbar.value" rounded="pill"> {{ snackbar.text }} <template v-slot:actions> <v-btn :color="snackbar.color" variant="text" @click="closeSnackBar()"> Close </v-btn> </template> </v-snackbar> </v-container> </template>
import { GET_VIDEOGAMES, GET_VIDEOGAME_NAME, GET_VIDEOGAME_ID, GET_PLATFORMS, GET_GENEROS, NAME_ORDER_A, NAME_ORDER_Z, GENERO, CREATED, GAME_RTN_MAX, GAME_RTN_MIN } from '../actions/index.js'; const Title_Order = (a, b) => { if(a.Titulo < b.Titulo) return -1 if(a.Titulo > b.Titulo) return 1 return 0 } const Rtn_Order = (a, b) => { if(a.Rating < b.Rating) return -1 if(a.Rating > b.Rating) return 1 return 0 } const initialState = { Videogames: [], ExactGame: [], GameInfo: [], Generos: [], Consolas: {} } function rootReducer(state = initialState, action) { if(action.type === GET_VIDEOGAMES) { return { ...state, Videogames: action.payload, ExactGame: action.payload }; } if(action.type === GET_VIDEOGAME_NAME) { return { ...state, Videogames: action.payload }; } if(action.type === GET_VIDEOGAME_ID) { return { ...state, GameInfo: action.payload } } if(action.type === GET_PLATFORMS) { return { ...state, Consolas: action.payload }; } if(action.type === GET_GENEROS) { return { ...state, Generos: action.payload }; } if(action.type === NAME_ORDER_A) { return { ...state, Videogames: state.Videogames.slice().sort(Title_Order) } }; if(action.type === NAME_ORDER_Z) { return { ...state, Videogames: state.Videogames.slice().sort(Title_Order).reverse() } }; if(action.type === GENERO) { const allGames = state.ExactGame const typeFilter = action.payload === "allGenre" ? allGames : allGames.filter(({Generos}) => { return Generos.find(({Genero}) => Genero === action.payload)} ) return { ...state, Videogames: typeFilter, } }; if(action.type === CREATED) { const Existe = state.ExactGame let createdFilter; if(action.payload === "Todo") { createdFilter = Existe } if(action.payload === "true") { createdFilter = Existe.filter((e) => e.Creado === true) } if(action.payload === "false") { createdFilter = Existe.filter((e) => e.Creado === false) } return { ...state, Videogames: createdFilter, } }; if(action.type === GAME_RTN_MAX) { return { ...state, Videogames: state.Videogames.slice().sort(Rtn_Order).reverse() } } if(action.type === GAME_RTN_MIN) { return { ...state, Videogames: state.Videogames.slice().sort(Rtn_Order) } } return state; } export default rootReducer;
package com.newandromo.dev18147.app821162.ui.adapter; import android.content.Context; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import androidx.annotation.NonNull; import androidx.paging.AsyncPagedListDiffer; import androidx.paging.PagedList; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; import com.newandromo.dev18147.app821162.R; import com.newandromo.dev18147.app821162.db.entity.YoutubeSearchEntity; import com.newandromo.dev18147.app821162.utils.AppUtils; import com.newandromo.dev18147.app821162.utils.MyDateUtils; public class YoutubeSearchAdapter extends RecyclerView.Adapter<YoutubeSearchAdapter.YoutubeVideoViewHolder> { private static final DiffUtil.ItemCallback<YoutubeSearchEntity> DIFF_CALLBACK = new DiffUtil.ItemCallback<YoutubeSearchEntity>() { @Override public boolean areItemsTheSame(YoutubeSearchEntity oldItem, YoutubeSearchEntity newItem) { return oldItem.getVideoId().equals(newItem.getVideoId()); } @Override public boolean areContentsTheSame(YoutubeSearchEntity oldItem, YoutubeSearchEntity newItem) { return oldItem.getVideoId().equals(newItem.getVideoId()); } }; private final AsyncPagedListDiffer<YoutubeSearchEntity> mDiffer = new AsyncPagedListDiffer<>(this, DIFF_CALLBACK); private Context mContext; private YoutubeSearchListener mListener; private boolean mIsChannel = true; public YoutubeSearchAdapter(Context context, @NonNull YoutubeSearchListener listener) { this.mContext = context; this.mListener = listener; } public void submitList(PagedList<YoutubeSearchEntity> pagedList) { mDiffer.submitList(pagedList); } @Override public int getItemCount() { return mDiffer.getItemCount(); } @NonNull @Override public YoutubeVideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_video, parent, false); return new YoutubeVideoViewHolder(view); } @Override public void onBindViewHolder(@NonNull YoutubeVideoViewHolder holder, int position) { YoutubeSearchEntity video = mDiffer.getItem(position); if (video != null) { holder.bindTo(video); } else { // Null defines a placeholder item - AsyncPagedListDiffer will automatically // invalidate this row when the actual object is loaded from the database holder.clear(); } } public void setIsChannel(boolean isChannel) { mIsChannel = isChannel; } public interface YoutubeSearchListener { void onSelected(YoutubeSearchEntity video); void onContextMenuAction(YoutubeSearchEntity video); } public class YoutubeVideoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener { ImageView mThumbImageView; TextView mDurationTextView; TextView mTitleTextView; TextView mChannelTextView; TextView mDateTextView; RelativeLayout mViewsContainer; ImageView mIconViewImage; TextView mViewsTextView; YoutubeVideoViewHolder(View itemView) { super(itemView); mThumbImageView = itemView.findViewById(R.id.thumbnail); mDurationTextView = itemView.findViewById(R.id.duration); mTitleTextView = itemView.findViewById(R.id.title); mChannelTextView = itemView.findViewById(R.id.channel); mDateTextView = itemView.findViewById(R.id.date); mViewsContainer = itemView.findViewById(R.id.viewContainer); mIconViewImage = itemView.findViewById(R.id.views_icon); mViewsTextView = itemView.findViewById(R.id.views); itemView.setOnClickListener(this); itemView.setOnCreateContextMenuListener(this); } @Override public void onClick(View v) { if (mListener != null) { YoutubeSearchEntity video = mDiffer.getItem(getAdapterPosition()); if (video != null) mListener.onSelected(video); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (mListener != null) { YoutubeSearchEntity video = mDiffer.getItem(getAdapterPosition()); if (video != null) mListener.onContextMenuAction(video); } } void bindTo(YoutubeSearchEntity video) { // itemView.setTag(entry.getId()); mTitleTextView.setText(video.getTitle()); if (!TextUtils.isEmpty(video.getChannel())) { mChannelTextView.setVisibility(mIsChannel ? View.GONE : View.VISIBLE); mChannelTextView.setText(video.getChannel()); } String date = video.getDate(); try { if (video.getDateMillis() != 0) { CharSequence prettyTime = DateUtils.getRelativeTimeSpanString( video.getDateMillis(), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS); if (!TextUtils.isEmpty(prettyTime)) date = prettyTime.toString(); } else { String parsedDate = MyDateUtils.parseTimestampToString(date); if (!TextUtils.isEmpty(parsedDate)) date = parsedDate; } } catch (Exception e) { e.printStackTrace(); } mDateTextView.setText(date); mViewsTextView.setText(video.getViews()); if (TextUtils.isEmpty(video.getViews())) { mViewsContainer.setVisibility(View.GONE); } if (!TextUtils.isEmpty(video.getDuration())) { mDurationTextView.setText(video.getDuration()); mDurationTextView.setVisibility(View.VISIBLE); } try { int placeHolderColor = AppUtils.getPlaceholderColor(mContext); Picasso.get() .load(video.getThumbUrl()) .placeholder(placeHolderColor) .error(placeHolderColor) .fit().centerCrop() .into(mThumbImageView); } catch (Exception e) { e.printStackTrace(); } } void clear() { // itemView.invalidate(); mDurationTextView.invalidate(); mThumbImageView.invalidate(); mTitleTextView.invalidate(); mChannelTextView.invalidate(); mDateTextView.invalidate(); mViewsContainer.invalidate(); mIconViewImage.invalidate(); mViewsTextView.invalidate(); } } }
import { Component, Inject, OnInit } from '@angular/core'; import { animate, style, transition, trigger } from '@angular/animations'; import { MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ host: { selector: 'ngx-helper-preview' }, templateUrl: './ngx-helper-preview.component.html', styleUrls: ['./ngx-helper-preview.component.scss'], animations: [ trigger('image', [ transition(':enter', [ style({ width: 0, opacity: 0 }), animate('250ms ease-in-out', style({ width: '*', opacity: 1 })), ]), ]), trigger('description', [ transition(':enter', [ style({ height: 0, opacity: 0 }), animate('250ms ease-in-out', style({ height: '7rem', opacity: 1 })), ]), ]), ], }) export class NgxHelperPreviewComponent implements OnInit { public loading: boolean = false; public image: string = this.data.image; public description: string | undefined = this.data.description; public html: boolean = !!this.data.html; constructor( @Inject(MAT_DIALOG_DATA) private readonly data: { image: string; description?: string; html?: boolean }, ) {} ngOnInit(): void { this.loading = true; const image: HTMLImageElement = new Image(); image.onload = () => (this.loading = false); image.src = this.data.image; } }
import { Controller, Delete, Param, Req, UnauthorizedException, UseGuards, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { Request } from 'express'; import { DeleteUserUseCase } from 'src/app/use-cases/user-use-cases/delete-user.use-case'; import { AuthGuard } from 'src/infrastructure/auth/auth.guard'; @Controller('/user/delete') export class DeleteUserController { constructor( private deleteUser: DeleteUserUseCase, private jwtService: JwtService, ) {} @UseGuards(AuthGuard) @Delete(':id') async deleteUserExecute(@Param('id') id: string, @Req() request: Request) { const [type, token] = request.headers.authorization?.split(' ') ?? ''; const decodedToken = await this.jwtService.decode(token); if (decodedToken.userId !== id) { throw new UnauthorizedException('unauthorized to update another user'); } await this.deleteUser.execute(id); } }
from datetime import timedelta, datetime from fastapi import APIRouter, Depends, Body, HTTPException from sqlalchemy.orm import Session from starlette import status from jose import jwt from user import repository, schema from database import orm, connection router = APIRouter(prefix="/users") ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 SECRET_KEY = "4ab2fce7a6bd79e1c014396315ed322dd6edb1c5d975c6b74a2904135172c03c" ALGORITHM = "HS256" @router.get("/") def get_users( skip: int = 0, limit: int = 100, db: Session = Depends(connection.get_db), ): users = repository.get_users(db, skip=skip, limit=limit) return users @router.post( "/", status_code=status.HTTP_204_NO_CONTENT ) def post_users( user: schema.UserCreate, db: Session = Depends(connection.get_db), ): db_user = repository.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") new_user = repository.create_users(db=db, user=user) @router.post( "/login", response_model=schema.Token, ) def login_for_access_token( login_user: schema.LoginUser, db: Session = Depends(connection.get_db) ): # check user and password user = repository.get_user_by_email(db, login_user.email) if not user or not repository.pwd_context.verify(login_user.password, user.hashed_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) # make access token data = { "sub": user.email, "exp": datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) } access_token = jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM) return { "access_token": access_token, "token_type": "bearer", "email": user.email }
<template> <el-table :data="results" style="width: 100%"> <el-table-column label="ResultID" prop="resultId" /> <el-table-column label="用户ID" prop="resultUserId" /> <el-table-column label="类型" prop="resultType" /> <el-table-column label="处理时间" prop="resultTime" /> <el-table-column label="状态" prop="resultHave"> <template #default="scope"> <el-tag type="warning" v-if="scope.row.resultHave===0">未处理</el-tag> <el-tag type="success" v-if="scope.row.resultHave===1">已处理</el-tag> </template> </el-table-column> <el-table-column align="right"> <template #header> <el-switch v-model="has" class="ml-2" inline-prompt style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66" active-text="未处理" inactive-text="已处理" /> </template> <template #default="scope"> <el-button size="small" type="warning" v-if="scope.row.resultHave===0" @click="showIt(scope.row)" >详情</el-button> <el-dialog v-model="showVisible" title="处理详情"> <el-form :model="showDetail" label-width="100px"> <el-form-item label="用户" prop="resultUserId"> <el-text>{{showDetail.resultUserId}}</el-text> </el-form-item> <el-form-item label="类型" prop="resultType"> <el-text>{{showDetail.resultType}}</el-text> </el-form-item> <el-form-item label="对象" prop="resultObject"> <el-text>{{showDetail.resultObject}}</el-text> </el-form-item> <el-form-item label="对象ID" prop="resultObject"> <el-text>{{showDetail.resultObjectId}}</el-text> </el-form-item> <el-form-item label="理由" prop="resultReason"> <el-text>{{showDetail.resultReason}}</el-text> </el-form-item> <el-form-item> <el-button type="warning" @click="this.showVisible=false">取消</el-button> <el-button type="primary" @click="doIt">处理</el-button> </el-form-item> </el-form> </el-dialog> </template> </el-table-column> </el-table> <el-pagination @current-change="changePage" v-model:current-page="this.page" :default-current-page="parseInt(this.page)" hide-on-single-page :page-size="10" background layout="prev, pager, next, jumper" :total="parseInt(this.total)" ></el-pagination> </template> <script> import {showResultHasDo, showResultNotDo} from "@/api/admin"; import {doResult, showDetail} from "@/api/result"; export default { name: "ResultList", data() { return{ results: [], page: 1, total: 0, has: false, resultId: '', showVisible: false, showDetail: { resultId: '', resultUserId: '', resultObjectId: '', resultObject: '', resultType: '', resultReason: '' }, } }, watch: { has: { handler(newValue,oldValue){ if(this.has===false){ this.results=[] showResultNotDo(this.$store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } else{ this.results=[] showResultHasDo(this.$store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } }, deep:true } }, created() { if(this.has===false){ showResultNotDo(this.$store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } else{ showResultHasDo(this.$store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } }, methods: { showIt: function (val){ this.showVisible=true this.resultId=val.resultId showDetail(val.resultId).then(res=>{ if(res.data.code===200){ this.showDetail.resultId=res.data.object.resultId this.showDetail.resultUserId=res.data.object.resultUserId this.showDetail.resultType=res.data.object.resultType this.showDetail.resultObjectId=res.data.object.resultObjectId this.showDetail.resultObject=res.data.object.resultObject this.showDetail.resultReason=res.data.object.resultReason } }).catch(e=>{ console.log(e) }) }, doIt: function (){ this.showVisible=false doResult(this.resultId).then(res=>{ if(res.data.code===200){ this.store.dispatch('changeAdmin',{ admin: res.data.object }) this.change() } }) }, changePage: function (){ if(this.has===false){ showResultNotDo(this.store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } else{ showResultHasDo(this.store.getters['admin'].adminId, this.page).then(res=>{ this.total=res.data.object.total if(res.data.code===200){ for(let i=0;i<res.data.object.list.length;i++){ let result=res.data.object.list[i] this.results.push({ resultId: result.resultId, resultUserId: result.resultUserId, resultType: result.resultType, resultTime: result.resultTime, resultHave: result.resultHave }) } } }).catch(e=>{ console.log(e) }) } } } } </script> <style scoped> </style>
import 'package:flutter/material.dart'; import 'package:flutter_codigo5_museumapp/ui/general/general_widget.dart'; import 'package:flutter_codigo5_museumapp/ui/responsive/responsive.dart'; class ItemSlider3Widget extends StatelessWidget { String title; String image; Widget toPage; ItemSlider3Widget({ required this.title, required this.image, required this.toPage, }); @override Widget build(BuildContext context) { return GestureDetector( onTap: (){ Navigator.push(context, MaterialPageRoute(builder: (context)=> toPage)); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 180, margin: const EdgeInsets.only(right: 12.0), width: ResponsiveUI.of(context).wp(45), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(12.0), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(image), ), ), ), divider6, Text( title, style: const TextStyle( color: Colors.white, fontSize: 15.0, ), ), divider6, const Text( "12 999 artistas", style: TextStyle( color: Colors.white70, fontSize: 12.0, ), ), ], ), ); } }
import { createSlice } from "@reduxjs/toolkit"; const initialState = { name: "", email: "", photo: "", role: "", active: false, createdAt: "", status: "idle", error: "", id: "", }; const userSlice = createSlice({ name: "user", initialState, reducers: { setUserData(state, action) { state.name = action.payload.name; state.email = action.payload.email; state.photo = action.payload.photo; state.role = action.payload.role; state.active = action.payload.active; state.createdAt = action.payload.createdAt; state.id = action.payload._id; }, setUserUpdate(state, action) { state.name = action.payload.name; state.email = action.payload.email; state.photo = action.payload.photo; state.createdAt = action.payload.createdAt; state.id = action.payload._id; }, setUserLogout(state) { state = state.initialState; }, }, }); export const { setUserData, setUserLogout, setUserUpdate } = userSlice.actions; export default userSlice.reducer;
mod backend; mod keystore; use serde_json::json; use futures_lite::future; use openmls::prelude::group_info::VerifiableGroupInfo; use openmls::prelude::*; use openmls_basic_credential::SignatureKeyPair; use backend::TestBackend; use clap::{Parser, Subcommand}; use io::Read; use io::Write; use std::fs; use std::io; use std::path::PathBuf; use uuid::Uuid; #[derive(Debug)] struct ClientId { user: String, client: String, domain: String, } impl core::str::FromStr for ClientId { type Err = String; fn from_str(s: &str) -> Result<Self, String> { let dom_index = s.find('@').ok_or("No domain separator")?; let cli_index = s[0..dom_index].find(':').ok_or("No client ID separator")?; Ok(ClientId { user: s[0..cli_index].to_string(), client: s[cli_index + 1..dom_index].to_string(), domain: s[dom_index + 1..].to_string(), }) } } impl ClientId { fn to_vec(&self) -> Vec<u8> { let mut out = Vec::new(); out.extend(self.user.bytes()); out.push(b':'); out.extend(self.client.bytes()); out.push(b'@'); out.extend(self.domain.bytes()); out } fn to_x509(&self, handle: &str) -> String { let uuid = Uuid::parse_str(&self.user).unwrap(); let uid = base64::encode_config(uuid.into_bytes(), base64::URL_SAFE_NO_PAD); format!( "subjectAltName=URI:im:wireapp={}/{}@{}, URI:im:wireapp=%40{}@{}", uid, self.client, self.domain, handle, self.domain ) } } #[derive(Debug)] enum CredentialType { Basic, X509, } impl core::str::FromStr for CredentialType { type Err = String; fn from_str(x: &str) -> Result<Self, String> { match x { "basic" => Ok(Self::Basic), "x509" => Ok(Self::X509), _ => Err(format!("Invalid credential type {}", x)), } } } #[derive(Debug)] struct CredentialBundle { credential: Credential, keys: SignatureKeyPair, } impl CredentialBundle { fn credential_with_key(&self) -> CredentialWithKey { CredentialWithKey { credential: self.credential.clone(), signature_key: self.keys.public().into(), } } fn new( backend: &impl OpenMlsCryptoProvider, credential_type: CredentialType, client_id: ClientId, ciphersuite: Ciphersuite, handle: Option<String>, ) -> Self { let keys = SignatureKeyPair::new( ciphersuite.signature_algorithm(), &mut *backend.rand().borrow_rand().unwrap(), ) .unwrap(); let credential = match credential_type { CredentialType::Basic => Credential::new_basic(client_id.to_vec()), CredentialType::X509 => { // generate a self-signed certificate let handle = handle.unwrap_or(client_id.user.clone()); let subject = format!("/O={}/CN={}", client_id.domain, handle); let san = client_id.to_x509(&handle); let openssl = std::process::Command::new("openssl") .args([ "req", "-new", "-x509", "-nodes", "-days", "3650", "-key", "/dev/stdin", "-keyform", "DER", "-out", "/dev/stdout", "-keyout", "/dev/null", "-outform", "DER", "-subj", &subject, "-addext", &san, ]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let mut stdin = openssl.stdin.as_ref().unwrap(); // add hardcoded pkcs8 envelope stdin.write_all(b"\x30\x2e\x02\x01\x00\x30\x05\x06\x03\x2b\x65\x70\x04\x22\x04\x20") .unwrap(); stdin.write_all(keys.private()).unwrap(); let out = openssl.wait_with_output().unwrap(); if !out.status.success() { panic!( "openssl failed: {}", core::str::from_utf8(&out.stderr).unwrap() ); } let cert = out.stdout; Credential::new_x509(vec![cert.clone(), cert]).unwrap() } }; Self { credential, keys } } fn store(&self, backend: &TestBackend) { backend .key_store() .store_value(b"self", &(&self.keys, &self.credential)) .unwrap(); } fn read(backend: &TestBackend) -> Self { let ks = backend.key_store(); let (keys, credential) = ks .read_value(b"self") .ok() .flatten() .expect("Credential not initialised. Please run `init` first."); Self { credential, keys } } } #[derive(Parser, Debug)] #[clap(name = "mls-test-cli", version = env!("CARGO_PKG_VERSION"))] struct Cli { #[clap(short, long)] store: String, #[clap(subcommand)] command: Command, } #[derive(Subcommand, Debug)] enum Command { Init { client_id: ClientId, #[clap(short = 't', long, default_value = "basic")] credential_type: CredentialType, #[clap(short, long, default_value = "0x0001")] ciphersuite: String, #[clap(long)] handle: Option<String>, }, Show { #[clap(subcommand)] command: ShowCommand, }, KeyPackage { #[clap(subcommand)] command: KeyPackageCommand, }, PublicKey, Group { #[clap(subcommand)] command: GroupCommand, }, Member { #[clap(subcommand)] command: MemberCommand, }, Message { #[clap(short, long)] group: String, text: String, }, Proposal { #[clap(short, long)] group_in: String, #[clap(long)] group_out: Option<String>, #[clap(short, long, conflicts_with = "group-out")] in_place: bool, #[clap(subcommand)] command: ProposalCommand, }, ExternalProposal { #[clap(short, long)] group_id: String, #[clap(short, long)] epoch: u64, #[clap(subcommand)] command: ExternalProposalCommand, #[clap(short, long, default_value = "0x0001")] ciphersuite: String, }, /// Create a commit that references all pending proposals Commit { #[clap(short, long)] group: String, #[clap(long)] group_out: Option<String>, #[clap(long)] group_info_out: Option<String>, #[clap(short, long, conflicts_with = "group-out")] in_place: bool, #[clap(short, long)] welcome_out: Option<String>, }, /// Create an external commit ExternalCommit { #[clap(long)] group_info_in: String, #[clap(long)] group_info_out: Option<String>, #[clap(long)] group_out: Option<String>, #[clap(short, long, default_value = "0x0001")] ciphersuite: String, }, /// Receive and store an incoming message. Consume { #[clap(short, long)] group: String, #[clap(long)] group_out: Option<String>, #[clap(short, long, conflicts_with = "group-out")] in_place: bool, /// The public key used to sign the message. This is only used for external senders. /// Signatures of messages originating from members are not verified at the moment, so this /// option is ignored in those cases. #[clap(short, long)] signer_key: Option<String>, message: String, }, } #[derive(Subcommand, Debug)] enum ShowCommand { Message { file: String }, KeyPackage { file: String }, } #[derive(Subcommand, Debug)] enum KeyPackageCommand { /// Create a new key package and save it in the store. Create { /// How long in seconds will the key package be valid #[clap(short, long)] lifetime: Option<u64>, #[clap(short, long, default_value = "0x0001")] ciphersuite: String, }, /// Compute the hash of a key package. Ref { key_package: String }, } #[derive(Subcommand, Debug)] enum GroupCommand { Create { group_id: String, #[clap(short, long)] removal_key: Option<String>, #[clap(short, long, default_value = "-")] group_out: String, #[clap(short, long, default_value = "0x0001")] ciphersuite: String, }, FromWelcome { welcome: String, #[clap(long)] group_out: String, }, } #[derive(Subcommand, Debug)] enum MemberCommand { Add { #[clap(short, long)] group: String, key_packages: Vec<String>, #[clap(short, long)] welcome_out: Option<String>, #[clap(long)] group_out: Option<String>, #[clap(long)] group_info_out: Option<String>, #[clap(short, long, conflicts_with = "group-out")] in_place: bool, }, Remove { #[clap(short, long)] group: String, indices: Vec<u32>, #[clap(short, long)] welcome_out: Option<String>, #[clap(long)] group_out: Option<String>, #[clap(long)] group_info_out: Option<String>, #[clap(short, long, conflicts_with = "group-out")] in_place: bool, }, } #[derive(Subcommand, Debug)] enum ProposalCommand { /// Create an add proposal Add { key_package: String }, /// Create a remove proposal Remove { index: u32 }, /// Create a re-init proposal ReInit { ciphersuite: Option<String> }, } #[derive(Subcommand, Debug)] enum ExternalProposalCommand { /// Create an add proposal Add {}, } fn path_reader(path: &str) -> io::Result<Box<dyn Read>> { if path == "-" { Ok(Box::new(io::stdin())) } else { Ok(Box::new(fs::File::open(path)?)) } } fn path_writer(path: &str) -> io::Result<Box<dyn Write>> { if path == "-" { Ok(Box::new(io::stdout())) } else { Ok(Box::new(fs::File::create(path)?)) } } fn save_group<W: Write>(group: &MlsGroup, mut writer: W) { let json = serde_json::to_string_pretty(&group).unwrap(); writer.write_all(&json.into_bytes()).unwrap(); } fn load_group<R: Read>(reader: R) -> MlsGroup { #[allow(deprecated)] let group: SerializedMlsGroup = serde_json::from_reader(reader).unwrap(); group.into() } fn group_id_from_str(group_id: &str) -> GroupId { let group_id = base64::decode(group_id).expect("Failed to decode group_id as base64"); GroupId::from_slice(&group_id) } fn build_configuration( external_senders: Vec<ExternalSender>, ciphersuite: Ciphersuite, ) -> MlsGroupConfig { MlsGroupConfig::builder() .wire_format_policy(openmls::group::MIXED_PLAINTEXT_WIRE_FORMAT_POLICY) .max_past_epochs(3) .padding_size(16) .number_of_resumption_psks(1) .sender_ratchet_configuration(SenderRatchetConfiguration::new(2, 5)) .use_ratchet_tree_extension(true) .external_senders(external_senders) .crypto_config(CryptoConfig::with_default_version(ciphersuite)) .build() } fn parse_ciphersuite(s: &str) -> Result<Ciphersuite, String> { let s = s.trim_start_matches("0x"); let n = u16::from_str_radix(s, 16).map_err(|e| e.to_string())?; Ciphersuite::try_from(n).map_err(|e| e.to_string()) } async fn new_key_package( backend: &TestBackend, _lifetime: Option<u64>, ciphersuite: Ciphersuite, ) -> KeyPackage { let cred_bundle = CredentialBundle::read(backend); // TODO: set lifetime KeyPackage::builder() .build( CryptoConfig { ciphersuite, version: ProtocolVersion::default(), }, backend, &cred_bundle.keys, cred_bundle.credential_with_key(), ) .await .unwrap() } async fn run() { let cli = Cli::parse(); let backend = TestBackend::new(PathBuf::from(&cli.store)).unwrap(); match cli.command { Command::Init { client_id, credential_type, ciphersuite, handle, } => { let ciphersuite = parse_ciphersuite(&ciphersuite).unwrap(); let ks = backend.key_store(); match ks.read_value::<serde_json::Value>(b"self").unwrap() { Some(_) => { panic!("Credential already initialised"); } None => { CredentialBundle::new( &backend, credential_type, client_id, ciphersuite, handle, ) .store(&backend); } } } Command::KeyPackage { command: KeyPackageCommand::Create { lifetime, ciphersuite, }, } => { let ciphersuite = parse_ciphersuite(&ciphersuite).unwrap(); let key_package = new_key_package(&backend, lifetime, ciphersuite).await; // output key package to standard output key_package.tls_serialize(&mut io::stdout()).unwrap(); } Command::Show { command: ShowCommand::Message { file }, } => { let message = { let mut data = path_reader(&file).unwrap(); MlsMessageIn::tls_deserialize(&mut data).unwrap() }; match message.extract() { MlsMessageInBody::PublicMessage(pmsg) => { let v = serde_json::to_value(&pmsg).unwrap(); let obj = json!({ "type": "public_message", "message": v }); serde_json::to_writer_pretty(io::stdout(), &obj).unwrap(); } MlsMessageInBody::PrivateMessage(_) => { let obj = json!({ "type": "private_message" }); serde_json::to_writer_pretty(io::stdout(), &obj).unwrap(); } MlsMessageInBody::Welcome(_) => { let obj = json!({ "type": "welcome" }); serde_json::to_writer_pretty(io::stdout(), &obj).unwrap(); } MlsMessageInBody::GroupInfo(_) => { let obj = json!({ "type": "group_info" }); serde_json::to_writer_pretty(io::stdout(), &obj).unwrap(); } MlsMessageInBody::KeyPackage(kp) => { let v = serde_json::to_value(&kp).unwrap(); let obj = json!({ "type": "key_package", "message": v }); serde_json::to_writer_pretty(io::stdout(), &obj).unwrap(); } } } Command::Show { command: ShowCommand::KeyPackage { file }, } => { let kp = { let mut data = path_reader(&file).unwrap(); let key_package = KeyPackageIn::tls_deserialize(&mut data).unwrap(); key_package .validate(backend.crypto(), ProtocolVersion::Mls10) .unwrap() }; serde_json::to_writer_pretty(io::stdout(), &kp).unwrap(); } Command::KeyPackage { command: KeyPackageCommand::Ref { key_package }, } => { let mut data = path_reader(&key_package).unwrap(); let key_package = KeyPackageIn::tls_deserialize(&mut data).unwrap(); let key_package = key_package .validate(backend.crypto(), ProtocolVersion::Mls10) .unwrap(); io::stdout() .write_all( key_package.hash_ref(backend.crypto()).unwrap().as_slice(), ) .unwrap(); } Command::PublicKey => { let cred_bundle = CredentialBundle::read(&backend); let bytes = cred_bundle.keys.public(); io::stdout().write_all(bytes).unwrap(); } Command::Group { command: GroupCommand::Create { group_id, removal_key, group_out, ciphersuite, }, } => { let cred_bundle = CredentialBundle::read(&backend); let group_id = group_id_from_str(&group_id); let backend_credential = Credential::new_basic(b"backend".to_vec()); let external_senders = match removal_key { Some(removal_key) => { let removal_key = { let mut reader = path_reader(&removal_key).unwrap(); let mut data = Vec::new(); reader.read_to_end(&mut data).unwrap(); SignaturePublicKey::from(data) }; let backend_sender = ExternalSender::new(removal_key, backend_credential); vec![backend_sender] } None => vec![], }; let ciphersuite = parse_ciphersuite(&ciphersuite).unwrap(); let group_config = build_configuration(external_senders, ciphersuite); let group = MlsGroup::new_with_group_id( &backend, &cred_bundle.keys, &group_config, group_id, cred_bundle.credential_with_key(), ) .await .unwrap(); save_group(&group, &mut path_writer(&group_out).unwrap()); } Command::Group { command: GroupCommand::FromWelcome { welcome, group_out }, } => { let message = MlsMessageIn::tls_deserialize( &mut path_reader(&welcome).unwrap(), ) .unwrap(); let welcome = match message.extract() { MlsMessageInBody::Welcome(welcome) => welcome, _ => { panic!("expected welcome") } }; let ciphersuite = welcome.ciphersuite(); let group_config = build_configuration(vec![], ciphersuite); let group = MlsGroup::new_from_welcome( &backend, &group_config, welcome, None, ) .await .unwrap(); let mut group_out = fs::File::create(group_out).unwrap(); save_group(&group, &mut group_out); } Command::Member { command: MemberCommand::Add { group: group_in, key_packages, welcome_out, group_out, group_info_out, in_place, }, } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let kps = key_packages .into_iter() .map(|kp| { let mut data = path_reader(&kp).expect(&format!( "Could not open key package file: {}", kp )); let kp = KeyPackageIn::tls_deserialize(&mut data).unwrap(); kp.validate(backend.crypto(), ProtocolVersion::Mls10) .unwrap() }) .collect::<Vec<_>>(); let (handshake, welcome, group_info) = if kps.is_empty() { group .commit_to_pending_proposals(&backend, &cred_bundle.keys) .await .unwrap() } else { let (commit, welcome, group_info) = group .add_members(&backend, &cred_bundle.keys, &kps) .await .unwrap(); (commit, Some(welcome), group_info) }; match (welcome_out, welcome) { (Some(welcome_out), Some(welcome)) => { let mut writer = fs::File::create(welcome_out).unwrap(); welcome.tls_serialize(&mut writer).unwrap(); } _ => {} } let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); group.merge_pending_commit(&backend).await.unwrap(); save_group(&group, &mut writer); } if let (Some(group_info_out), Some(group_info)) = (group_info_out, group_info) { let mut writer = fs::File::create(group_info_out).unwrap(); group_info.tls_serialize(&mut writer).unwrap(); } handshake.tls_serialize(&mut io::stdout()).unwrap(); } Command::Member { command: MemberCommand::Remove { group: group_in, indices, welcome_out, group_out, group_info_out, in_place, }, } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let indices = indices .into_iter() .map(LeafNodeIndex::new) .collect::<Vec<_>>(); let (commit, welcome, group_info) = group .remove_members(&backend, &cred_bundle.keys, &indices[..]) .await .unwrap(); let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); group.merge_pending_commit(&backend).await.unwrap(); save_group(&group, &mut writer); } if let Some(welcome_out) = welcome_out { if let Some(welcome) = welcome { let mut writer = fs::File::create(welcome_out).unwrap(); welcome.tls_serialize(&mut writer).unwrap(); } } if let (Some(group_info_out), Some(group_info)) = (group_info_out, group_info) { let mut writer = fs::File::create(group_info_out).unwrap(); group_info.tls_serialize(&mut writer).unwrap(); } commit.tls_serialize(&mut io::stdout()).unwrap(); } Command::Message { group, text } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group).unwrap(); load_group(data) }; let message = group .create_message(&backend, &cred_bundle.keys, text.as_bytes()) .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); } Command::Proposal { group_in, group_out, in_place, command: ProposalCommand::Add { key_package }, } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let key_package = { let mut data = path_reader(&key_package).unwrap(); let kp = KeyPackageIn::tls_deserialize(&mut data).unwrap(); kp.validate(backend.crypto(), ProtocolVersion::Mls10) .unwrap() }; let (message, _) = group .propose_add_member(&backend, &cred_bundle.keys, &key_package) .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); save_group(&group, &mut writer); } } Command::Proposal { group_in, group_out, in_place, command: ProposalCommand::Remove { index }, } => { let cred_bundle = CredentialBundle::read(&backend); let index = LeafNodeIndex::new(index); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let message = group .propose_remove_member(&backend, &cred_bundle.keys, index) .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); save_group(&group, &mut writer); } } Command::Proposal { group_in, group_out, in_place, command: ProposalCommand::ReInit { ciphersuite }, } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let ciphersuite = match ciphersuite { Some(ciphersuite) => parse_ciphersuite(&ciphersuite).unwrap(), None => group.ciphersuite(), }; let (message, _) = group .propose_reinit( &backend, &cred_bundle.keys, Extensions::empty(), ciphersuite, ProtocolVersion::Mls10, ) .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); save_group(&group, &mut writer); } } Command::ExternalProposal { group_id, epoch, command: ExternalProposalCommand::Add {}, ciphersuite, } => { let cred_bundle = CredentialBundle::read(&backend); let ciphersuite = parse_ciphersuite(&ciphersuite).unwrap(); let key_package = new_key_package(&backend, None, ciphersuite).await; let group_id = group_id_from_str(&group_id); let proposal = JoinProposal::new( key_package, group_id, GroupEpoch::from(epoch), &cred_bundle.keys, ) .unwrap(); proposal.tls_serialize(&mut io::stdout()).unwrap(); } Command::Commit { group: group_in, group_out, group_info_out, in_place, welcome_out, } => { let cred_bundle = CredentialBundle::read(&backend); let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; let (message, welcome, group_info) = group .commit_to_pending_proposals(&backend, &cred_bundle.keys) .await .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); if let Some(welcome_out) = welcome_out { if let Some(welcome) = welcome { let mut writer = fs::File::create(welcome_out).unwrap(); welcome.tls_serialize(&mut writer).unwrap(); } } let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); group.merge_pending_commit(&backend).await.unwrap(); save_group(&group, &mut writer); } if let (Some(group_info_out), Some(group_info)) = (group_info_out, group_info) { let mut writer = fs::File::create(group_info_out).unwrap(); group_info.tls_serialize(&mut writer).unwrap(); } } Command::ExternalCommit { group_info_in, group_info_out, group_out, ciphersuite, } => { let cred_bundle = CredentialBundle::read(&backend); let group_info = { let mut data = path_reader(&group_info_in).unwrap(); VerifiableGroupInfo::tls_deserialize(&mut data).unwrap() }; let ciphersuite = parse_ciphersuite(&ciphersuite).unwrap(); let (mut group, message, group_info) = MlsGroup::join_by_external_commit( &backend, &cred_bundle.keys, None, group_info, &build_configuration(vec![], ciphersuite), &[], cred_bundle.credential_with_key(), ) .await .unwrap(); message.tls_serialize(&mut io::stdout()).unwrap(); if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); group.merge_pending_commit(&backend).await.unwrap(); save_group(&group, &mut writer); } if let (Some(group_info_out), Some(group_info)) = (group_info_out, group_info) { let mut writer = fs::File::create(group_info_out).unwrap(); group_info.tls_serialize(&mut writer).unwrap(); } } Command::Consume { group: group_in, group_out, in_place, message, signer_key: _, } => { let mut group = { let data = path_reader(&group_in).unwrap(); load_group(data) }; // parse and verify message let msg_in = { let mut data = path_reader(&message).unwrap(); MlsMessageIn::tls_deserialize(&mut data).unwrap() }; // TODO: read signer key if necessary let pmsg: ProtocolMessage = match msg_in.extract() { MlsMessageInBody::PrivateMessage(m) => m.into(), MlsMessageInBody::PublicMessage(m) => m.into(), _ => panic!("Unexpected message type"), }; let message = group.process_message(&backend, pmsg).await.unwrap(); // store proposal or apply commit match message.into_content() { ProcessedMessageContent::ApplicationMessage(_) => {} ProcessedMessageContent::ProposalMessage(staged_proposal) => { group.store_pending_proposal(*staged_proposal); } ProcessedMessageContent::StagedCommitMessage(staged_commit) => { group .merge_staged_commit(&backend, *staged_commit) .await .expect("Could not merge commit"); } ProcessedMessageContent::ExternalJoinProposalMessage( staged_proposal, ) => { group.store_pending_proposal(*staged_proposal); } } // save new group state let group_out = if in_place { Some(group_in) } else { group_out }; if let Some(group_out) = group_out { let mut writer = fs::File::create(group_out).unwrap(); save_group(&group, &mut writer); } } } } fn main() { future::block_on(run()); }
<div class="header"> <span>beecrowd | 1040</span> <h1>Média 3</h1> <div><p> Adaptado por Neilor Tonin, URI <img alt src="https://resources.beecrowd.com.br/gallery/images/flags/br.gif" style="width: 16px; height: 11px; " /> Brasil</p> </div> <strong>Timelimit: 1</strong> </div> <div class="problem"> <div class="description"> <p> Leia quatro números (N<sub>1</sub>, N<sub>2</sub>, N<sub>3</sub>, N<sub>4</sub>), cada um deles com uma casa decimal, correspondente às quatro notas de um aluno. Calcule a média com pesos 2, 3, 4 e 1, respectivamente, para cada uma destas notas e mostre esta média acompanhada pela mensagem <em>"Media: "</em>. Se esta média for maior ou igual a 7.0, imprima a mensagem <em>"Aluno aprovado."</em>. Se a média calculada for inferior a 5.0, imprima a mensagem <em>"Aluno reprovado."</em>. Se a média calculada for um valor entre 5.0 e 6.9, inclusive estas, o programa deve imprimir a mensagem <em>"Aluno em exame."</em>.</p> <p> No caso do aluno estar em exame, leia um valor correspondente à nota do exame obtida pelo aluno. Imprima então a mensagem <em>"Nota do exame: "</em> acompanhada pela nota digitada. Recalcule a média (some a pontuação do exame com a média anteriormente calculada e divida por 2). e imprima a mensagem <em>"Aluno aprovado."</em> (caso a média final seja 5.0 ou mais ) ou <em>"Aluno reprovado."</em>, (caso a média tenha ficado 4.9 ou menos). Para estes dois casos (aprovado ou reprovado após ter pego exame) apresente na última linha uma mensagem <em>"Media final: "</em> seguido da média final para esse aluno. </p> </div> <h2>Entrada</h2> <div class="input"> <p> A entrada contém quatro números de ponto flutuante correspendentes as notas dos alunos.</p> </div> <h2>Saída</h2> <div class="output"> <p> Todas as respostas devem ser apresentadas com uma casa decimal. As mensagens devem ser impressas conforme a descrição do problema. Não esqueça de imprimir o <em>enter</em> após o final de cada linha, caso contrário obterá "Presentation Error".</p> </div> <div class="both"></div> <table> <thead> <tr> <td>Exemplo de Entrada</td> <td>Exemplo de Saída</td> </tr> </thead> <tbody> <tr> <td class="division"> <p> 2.0 4.0 7.5 8.0<br/> 6.4</p> </td> <td> <p> Media: 5.4<br/> Aluno em exame.<br/> Nota do exame: 6.4<br/> Aluno aprovado.<br/> Media final: 5.9</p> </td> </tr> </tbody> </table> <table> <tbody> <tr> <td class="division"> <p> 2.0 6.5 4.0 9.0</p> </td> <td> <p>Media: 4.8<br/> Aluno reprovado.</p> </td> </tr> </tbody> </table> <table> <tbody> <tr> <td class="division"> <p> 9.0 4.0 8.5 9.0</p> </td> <td> <p> Media: 7.3<br/> Aluno aprovado.</p> </td> </tr> </tbody> </table> </div>
import torch import torch.nn as nn import torch.nn.functional as F from utils import BahdanauAttention, AttentionWrapper, get_mask_from_lengths from torch.autograd import Variable class Prenet(nn.Module): def __init__(self, in_feature, sizes=[256, 128]): super(Prenet, self).__init__() self.in_features = [in_feature] + sizes[:-1] self.layers = nn.ModuleList( [ nn.Linear(in_feat, out_feat) for (in_feat, out_feat) in zip(self.in_features, sizes) ] ) self.relu = nn.ReLU() def forward(self, x): for layer in self.layers: x = F.dropout(self.relu(layer(x)), p=0.5) return x class BatchNormConv1d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, stride, padding, activation=None ): super(BatchNormConv1d, self).__init__() self.conv1d = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding) self.bnorm = nn.BatchNorm1d(out_channels) self.activation = activation def forward(self, x): x = self.conv1d(x) if self.activation: x = self.activation(x) return self.bnorm(x) class Highway(nn.Module): "paper : https://arxiv.org/pdf/1505.00387" def __init__(self, in_features, out_features): super(Highway, self).__init__() self.H = nn.Linear(in_features, out_features, bias=False) self.T = nn.Linear(in_features, out_features, bias=False) def forward(self, inputs): H = F.relu(self.H(inputs)) T = torch.sigmoid(self.T(inputs)) return H * T + inputs * (1.0 - T) class CBHG(nn.Module): def __init__(self, in_dim, K=16, projections=[128, 128]): super(CBHG, self).__init__() self.in_dim = in_dim self.relu = nn.ReLU() self.conv1d_banks = nn.ModuleList( [ BatchNormConv1d( in_dim, in_dim, kernel_size=k, stride=1, padding=k // 2, activation=self.relu, ) for k in range(1, K + 1) ] ) self.max_pool1d = nn.MaxPool1d(kernel_size=2, stride=1, padding=1) in_sizes = [K * in_dim] + projections[:-1] activations = [self.relu] * (len(projections) - 1) + [None] self.conv1d_projections = nn.ModuleList( [ BatchNormConv1d( in_size, out_size, kernel_size=3, stride=1, padding=1, activation=ac ) for (in_size, out_size, ac) in zip(in_sizes, projections, activations) ] ) self.pre_highway = nn.Linear(projections[-1], in_dim, bias=False) self.highways = nn.ModuleList([Highway(in_dim, in_dim) for _ in range(4)]) self.gru = nn.GRU(in_dim, in_dim, 1, batch_first=True, bidirectional=True) def forward(self, inputs, input_lengths=None): # (B, T_in, in_dim) x = inputs # Needed to perform conv1d on time-axis # (B, in_dim, T_in) if x.size(-1) == self.in_dim: x = x.transpose(1, 2) T = x.size(-1) # (B, in_dim*K, T_in) # Concat conv1d bank outputs x = torch.cat([conv1d(x)[:, :, :T] for conv1d in self.conv1d_banks], dim=1) assert x.size(1) == self.in_dim * len(self.conv1d_banks) x = self.max_pool1d(x)[:, :, :T] for conv1d in self.conv1d_projections: x = conv1d(x) # (B, T_in, in_dim) # Back to the original shape x = x.transpose(1, 2) if x.size(-1) != self.in_dim: x = self.pre_highway(x) # Residual connection x += inputs for highway in self.highways: x = highway(x) if input_lengths is not None: x = nn.utils.rnn.pack_padded_sequence(x, input_lengths, batch_first=True) # (B, T_in, in_dim*2) outputs, _ = self.gru(x) if input_lengths is not None: outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs, batch_first=True) return outputs class Encoder(nn.Module): def __init__(self, in_dim): super(Encoder, self).__init__() self.prenet = Prenet(in_dim, sizes=[256, 128]) self.cbhg = CBHG(128, K=16, projections=[128, 128]) def forward(self, inputs, input_lengths=None): inputs = self.prenet(inputs) print(inputs.shape) return self.cbhg(inputs, input_lengths) class Decoder(nn.Module): def __init__(self, in_dim, r): super(Decoder, self).__init__() self.in_dim = in_dim self.r = r self.prenet = Prenet(in_dim * r, sizes=[256, 128]) # (prenet_out + attention context) -> output self.attention_rnn = AttentionWrapper( nn.GRUCell(256 + 128, 256), BahdanauAttention(256) ) self.memory_layer = nn.Linear(256, 256, bias=False) self.project_to_decoder_in = nn.Linear(512, 256) self.decoder_rnns = nn.ModuleList([nn.GRUCell(256, 256) for _ in range(2)]) self.proj_to_mel = nn.Linear(256, in_dim * r) self.max_decoder_steps = 200 def forward(self, encoder_outputs, inputs=None, memory_lengths=None): """ Decoder forward step. If decoder inputs are not given (e.g., at testing time), as noted in Tacotron paper, greedy decoding is adapted. Args: encoder_outputs: Encoder outputs. (B, T_encoder, dim) inputs: Decoder inputs. i.e., mel-spectrogram. If None (at eval-time), decoder outputs are used as decoder inputs. memory_lengths: Encoder output (memory) lengths. If not None, used for attention masking. """ B = encoder_outputs.size(0) processed_memory = self.memory_layer(encoder_outputs) if memory_lengths is not None: mask = get_mask_from_lengths(processed_memory, memory_lengths) else: mask = None # Run greedy decoding if inputs is None greedy = inputs is None if inputs is not None: # Grouping multiple frames if necessary if inputs.size(-1) == self.in_dim: inputs = inputs.view(B, inputs.size(1) // self.r, -1) assert inputs.size(-1) == self.in_dim * self.r T_decoder = inputs.size(1) # go frames initial_input = Variable( encoder_outputs.data.new(B, self.in_dim * self.r).zero_() ) # Init decoder states attention_rnn_hidden = Variable(encoder_outputs.data.new(B, 256).zero_()) decoder_rnn_hiddens = [ Variable(encoder_outputs.data.new(B, 256).zero_()) for _ in range(len(self.decoder_rnns)) ] current_attention = Variable(encoder_outputs.data.new(B, 256).zero_()) # Time first (T_decoder, B, in_dim) if inputs is not None: inputs = inputs.transpose(0, 1) outputs = [] alignments = [] t = 0 current_input = initial_input while True: if t > 0: current_input = outputs[-1] if greedy else inputs[t - 1] # Prenet current_input = self.prenet(current_input) # Attention RNN attention_rnn_hidden, current_attention, alignment = self.attention_rnn( current_input, current_attention, attention_rnn_hidden, encoder_outputs, processed_memory=processed_memory, mask=mask, ) # Concat RNN output and attention context vector decoder_input = self.project_to_decoder_in( torch.cat((attention_rnn_hidden, current_attention), -1) ) # Pass through the decoder RNNs for idx in range(len(self.decoder_rnns)): decoder_rnn_hiddens[idx] = self.decoder_rnns[idx]( decoder_input, decoder_rnn_hiddens[idx] ) # Residual connectinon decoder_input = decoder_rnn_hiddens[idx] + decoder_input output = decoder_input output = self.proj_to_mel(output) outputs += [output] alignments += [alignment] t += 1 if greedy: if t > 1 and is_end_of_frames(output): break elif t > self.max_decoder_steps: print("Warning! doesn't seems to be converged") break else: if t >= T_decoder: break assert greedy or len(outputs) == T_decoder # Back to batch first alignments = torch.stack(alignments).transpose(0, 1) outputs = torch.stack(outputs).transpose(0, 1).contiguous() return outputs, alignments def is_end_of_frames(output, eps=0.2): return (output.data <= eps).all() class Tacotron(nn.Module): def __init__( self, n_vocab, embedding_dim=256, mel_dim=80, linear_dim=1025, r=5, padding_idx=None, use_memory_mask=False, ): super(Tacotron, self).__init__() self.mel_dim = mel_dim self.linear_dim = linear_dim self.use_memory_mask = use_memory_mask self.embedding = nn.Embedding(n_vocab, embedding_dim, padding_idx=padding_idx) # Trying smaller std self.embedding.weight.data.normal_(0, 0.3) self.encoder = Encoder(embedding_dim) self.decoder = Decoder(mel_dim, r) self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.last_linear = nn.Linear(mel_dim * 2, linear_dim) def forward(self, inputs, targets=None, input_lengths=None): B = inputs.size(0) inputs = self.embedding(inputs) # (B, T', in_dim) encoder_outputs = self.encoder(inputs, input_lengths) if self.use_memory_mask: memory_lengths = input_lengths else: memory_lengths = None # (B, T', mel_dim*r) mel_outputs, alignments = self.decoder( encoder_outputs, targets, memory_lengths=memory_lengths ) # Post net processing below # Reshape # (B, T, mel_dim) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) return mel_outputs, linear_outputs, alignments @classmethod def from_checkpoint(cls, checkpoint_path): checkpoint = torch.load(checkpoint_path) model = cls( n_vocab=checkpoint["n_vocab"], embedding_dim=checkpoint["embedding_dim"], mel_dim=checkpoint["mel_dim"], linear_dim=checkpoint["linear_dim"], r=checkpoint["r"], padding_idx=checkpoint["padding_idx"], use_memory_mask=checkpoint["use_memory_mask"], ) model.load_state_dict(checkpoint["state_dict"]) return model if __name__ == "__main__": tacotron = Tacotron(n_vocab=32_000) print(tacotron)
class UsersController < ApplicationController before_action :user_signed_in, only: [:new, :create] def new # @user = User.find(params[:id]) render :new end def create @user = User.new(user_params) login_user!(@user) if @user.save redirect_to cats_url else render json: @user.errors.full_messages, status: :unprocessable_entity end end private def user_params params.require(:user).permit(:user_name, :password) end end
import React from 'react'; import { useForm, SubmitHandler } from 'react-hook-form'; import { Navigate, useNavigate } from 'react-router-dom'; import { RoutePath } from '../components/RoutesComponent'; import FirebaseAPI from '../services/FirebaseAPI'; import FormInputComponent from '../components/FormInputComponent'; import AuthContext from '../context/AuthContext'; interface IFormInput { name: string; description: string; price: number; } export default function ProductAddPage() { const { register, handleSubmit, formState: { errors } } = useForm<IFormInput>(); const navigate = useNavigate(); const context = React.useContext(AuthContext); const [didSubmit, setDidSubmit] = React.useState<boolean>(false); const inputs = [ {label: 'Name', name: 'name', type: 'text'}, {label: 'Description', name: 'description', type: 'text'}, {label: 'Price', name: 'price', type: 'number'} ]; const onSubmit: SubmitHandler<IFormInput> = async data => { if (didSubmit) { window.alert('Form already submitted, please wait!'); return; } setDidSubmit(true); try { const documentId = await FirebaseAPI.saveProduct(data); window.alert('Product created! You are going to be redirected to the product page.'); navigate(`${RoutePath.PRODUCT}/${documentId}`); } catch (error: any) { window.alert(`Error creating product! ${error}`); } setDidSubmit(false); }; const renderInputs = () => { return inputs.map((input: any) => ( <FormInputComponent key={input.name} label={input.label} type={input.type} register={{...register(input.name, { required: true })}} errors={errors[input?.name as keyof typeof errors]} /> )); }; if (!context.isUserLoggedIn) { return <Navigate to={RoutePath.LOGIN}></Navigate>; } return ( <> <h1>Add Product</h1> <div> <form onSubmit={handleSubmit(onSubmit)}> {renderInputs()} <button className="formButton" type="submit" disabled={didSubmit}>Add</button> </form> </div> </> ); }
// src/app/flashcard-add/flashcard-add.component.ts import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FlashcardService } from '../flashcard.service'; @Component({ selector: 'app-flashcard-add', templateUrl: './flashcard-add.component.html', styleUrls: ['./flashcard-add.component.css'] }) export class FlashcardAddComponent { flashcardForm: FormGroup; constructor(private formBuilder: FormBuilder, private flashcardService: FlashcardService) { this.flashcardForm = this.formBuilder.group({ question: ['', Validators.required], answer: ['', Validators.required], }); } onSubmit() { if (this.flashcardForm.valid) { const newFlashcard = this.flashcardForm.value; this.flashcardService.addFlashcard(newFlashcard); this.flashcardForm.reset(); } else { console.log('Form is invalid. Please check the required fields.'); } } }
import React, { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux'; import { Link, useLocation, useNavigate } from 'react-router-dom' import { toast } from 'react-toastify'; import { useRegisterMutation } from '../redux/api/userApiSlice' import { setCredentials } from '../redux/features/auth/authSlice'; const Register = () => { const [formData, setFormData] = useState({}); const dispatch = useDispatch() const navigate = useNavigate() const [register, { isLoading }] = useRegisterMutation() const { userInfo } = useSelector(state => state.auth) const { search } = useLocation() const sp = new URLSearchParams(search) const redirect = sp.get('redirect') || '/' useEffect(() => { if(userInfo){ navigate(redirect) } }, [navigate, redirect, userInfo]) const handleChange = (e) => { setFormData({...formData, [e.target.id]: e.target.value }); } const handleSubmit = async (e) => { e.preventDefault(); try { const res = await register(formData).unwrap() dispatch(setCredentials({...res})); navigate(redirect); } catch (error) { toast.error(error?.data?.message || error?.message || error); } } return ( <main className='max-w-5xl p-4 max-sm:pt-14 mx-auto'> <section className='flex flex-col items-center gap-2 md:flex-row h-[90vh]'> <div className='md:flex-1 p-4'> <h1 className='head_text max-md:text-center mb-4'>Bienvenue sur Train-Trip - Votre plateforme ultime de réservation de train !</h1> <p className="desc max-md:text-center">Inscrivez-vous pour créer un compte et commencer à réserver vos voyages en toutes simplicité</p> </div> <div className='flex-1 mb-4'> <form onSubmit={handleSubmit} className='shadow-md rounded-lg p-8'> <div className='mb-4'> <label className='label' htmlFor="username">Nom d'utilisateur</label> <input className='input' type="text" name="username" id="username" onChange={handleChange}/> </div> <div className='mb-4'> <label className='label' htmlFor="email">E-mail</label> <input className='input' type="text" name="email" id="email" onChange={handleChange}/> </div> <div className='mb-6 w-full'> <label className='label' htmlFor="username">Mot de passe</label> <input className='input' type="password" name="password" id="password" onChange={handleChange}/> </div> <div className="flex items-center gap-2 justify-between"> <button disabled={isLoading} className="button_primary" type="submit">{isLoading ? "Chargement..." : "Enregistrer"}</button> <Link to={'/login'} className="inline-block align-baseline font-bold text-sm text-indigo-500 hover:text-indigo-800">Vous avez déja un compte ?</Link> </div> </form> </div> </section> </main> ) } export default Register
<!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> </head> <body> <!-- Logo --> <div class="container-fluid"> <div class="row"> <div class="col-md-12 "> <img class="rounded mx-auto d-block" src="./Imagenes/Olympic_flag.svg" width="350" /> </div> </div> <!-- Menu Navbar --> <div class="row"> <div class="col-md-12 "> <nav class="sticky-top navbar navbar-expand-lg navbar-dark bg-primary mb-2" > <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#" >Inicio <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">Menu Item 1</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Menu Item 2</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Menu Item 3</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Menu Item 4</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Menu Item 5</a> </li> </ul> </div> </nav> </div> </div> <!-- Contenido Principal --> <div class="row"> <div class="col-md-6 mb-2"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="./Video/History_of_the_Olympics__National_Geographic.mp4.mp4" allowfullscreen ></iframe> </div> </div> <!-- Contenido --> <div class="col-sm-12 col-md-6 "> <div class="row"> <div class="col-sm-6 col-md-6 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/1.jpg" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos olimpicos Grecia 1985.</p> </div> </div> </div> <div class="col-sm-6 col-md-6 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" style="height: 14rem;" src="./Imagenes/2.jpg" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos olimpicos Estocolmo 1912.</p> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6 col-md-6 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/3.jpg" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos Olimpicos los Angeles 1954.</p> </div> </div> </div> <div class="col-sm-6 col-md-6 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/4.jpg" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos Olimpicos Barcelona 1992.</p> </div> </div> </div> </div> </div> </div> <!-- SECCION --> <div class="row"> <div class="col-md-12 "> <p class="text-center text-white bg-primary display-1">SECCION</p> </div> </div> <!-- Imagenes de la seccion --> <div class="row justify-content-center "> <div class="col-sm-7 col-md-3 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/1.jpg" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos olimpicos Grecia 1985.</p> </div> </div> </div> <div class="col-sm-7 col-md-3 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/2.jpg" style="height: 14em;" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos olimpicos Grecia 1985.</p> </div> </div> </div> <div class="col-sm-7 col-md-3 "> <div class="card" style="width: 20rem;margin-bottom: 2em;"> <img class="card-img-top" src="./Imagenes/3.jpg" style="height: 14em;" alt="Juegos 1" /> <div class="card-body"> <p class="card-text">Juegos olimpicos Grecia 1985.</p> </div> </div> </div> </div> <!-- Contacto --> <div class="row"> <div class="col-md-12 "> <p class="text-center text-white bg-primary display-1">CONTACTO</p> </div> </div> <div class="row justify-content-center"> <div class="col-sm-4 col-md-2"> <form method="post" class=justify-content-center> <div class="form-group"> Nombre: <input type="text" class="form-control"> </div> <div class="form-group"> Apellidos: <input type="text" class="form-control"> </div> <textarea class="form-control"></textarea> <input type="submit" class="text-white bg-primary btn-group"> </form> </div> <div class="col-sm-4 col-md-2"> <p class="text-white bg-primary">Contacta con nosotros</p> <p class="text-weight-bold ">Hola</p> </div> </div> <div class="row"> <div class="col-md-12 justify-content-center bg-primary"> <p class="text-center"> <img src="./Imagenes/twitter.jpg" height="60" class="mt-3"> <img src="./Imagenes/facebook.jpg" height="60" class="mt-3"> <img src="./Imagenes/youtube.jpg" height="60" class="mt-3"> </p> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous" ></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous" ></script> </body> </html>
import { Text, VStack } from "@chakra-ui/react"; import React from "react"; import CustomSkeleton from "../CustomSkeleton"; import ProfileCards from "../ProfileCards"; const SearchResult = ({ loading, searchResult, createChat, message, label, addUser, }) => { return ( <div className="custom-scrollbar-search" style={{ width: "100%", maxHeight: "400px", overflowY: "scroll" }} > {loading && <CustomSkeleton number={1} lines={2} />} {searchResult?.length === 0 && !loading && ( <Text fontWeight="300" fontSize="18px" textAlign="center"> {message.length === 0 ? label || "Search for your friends here!!" : message} </Text> )} <VStack spacing={"15px"}> {searchResult?.slice(0, 10).map((item, ind) => { if (!item) return null; return ( <ProfileCards key={ind} user={item} createChat={createChat || addUser} /> ); })} </VStack> </div> ); }; export default SearchResult;
import { ArrowRightOutlined } from '@ant-design/icons'; import { MessageDisplay } from '@/components/common'; import { ProductShowcaseGrid } from '@/components/product'; import { FEATURED_PRODUCTS, RECOMMENDED_PRODUCTS, SHOP } from '@/constants/routes'; import { useDocumentTitle, useFeaturedProducts, useRecommendedProducts, useScrollTop } from '@/hooks'; import bannerImg from '@/images/do-an-vat-gia-si-1.jpg'; import React from 'react'; import { Link } from 'react-router-dom'; import { withTranslation, Trans } from 'react-i18next'; //import i18n from './i18n'; const Home = () => { useDocumentTitle('khoapham | Home'); useScrollTop(); const { featuredProducts, fetchFeaturedProducts, isLoading: isLoadingFeatured, error: errorFeatured } = useFeaturedProducts(6); const { recommendedProducts, fetchRecommendedProducts, isLoading: isLoadingRecommended, error: errorRecommended } = useRecommendedProducts(6); return ( <main className="content"> <div className="home"> <div className="banner"> <div className="banner-desc"> <h1 className="text-thin"> <strong>Đồ</strong> &nbsp;Ăn vặt&nbsp; <strong>Online</strong> </h1> <p> Mua đồ ăn vặt sẽ khiến bạn vui vẻ và ưa nhìn, tiền rủng rỉnh trong túi. Nhu cầu ăn vặt giữa giờ hay vào xế chiều của dân công sở, các bạn học sinh, sinh viên ngày càng tăng cao. Tuy nhiên, vì đang trong giờ học, giờ làm, thời gian ăn uống hạn chế khiến họ khó có thể ra ngoài mua đồ nên dần hình thành thói quen đặt đồ ăn online trên mạng. Hơn nữa, vấn đề vệ sinh an toàn thực phẩm tại các hàng quán vỉa hè, các xe đẩy lề đường đang trở nên nhức nhối nên những người thích ăn vặt mong muốn tìm những địa chỉ bán đồ ăn vặt uy tín, ngon miệng, sạch sẽ để đặt hàng. </p> <br /> <Link to={SHOP} className="button"> Shop Now &nbsp; <ArrowRightOutlined /> </Link> </div> <div className="banner-img"><img src={bannerImg} alt="" /></div> </div> <div className="display"> <div className="display-header"> <h1>Sản phẩm đặc sắc</h1> <Link to={FEATURED_PRODUCTS}>Tất cả</Link> </div> {(errorFeatured && !isLoadingFeatured) ? ( <MessageDisplay message={errorFeatured} action={fetchFeaturedProducts} buttonLabel="Thử lại" /> ) : ( <ProductShowcaseGrid products={featuredProducts} skeletonCount={6} /> )} </div> <div className="display"> <div className="display-header"> <h1>Sản phẩm Khuyến khích</h1> <Link to={RECOMMENDED_PRODUCTS}>Tất cả</Link> </div> {(errorRecommended && !isLoadingRecommended) ? ( <MessageDisplay message={errorRecommended} action={fetchRecommendedProducts} buttonLabel="Thử lại" /> ) : ( <ProductShowcaseGrid products={recommendedProducts} skeletonCount={6} /> )} </div> </div> </main> ); }; export default Home;
#!/usr/bin/env python3 import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Twist from sensor_msgs.msg import PointCloud from nav_msgs.msg import Odometry from mrs_project_simulation.msg import Neighbours from mrs_project2_simulation.srv import SetGoalPosition import numpy as np import rospkg import math class AgentNode(): def __init__(self): self.PUB_RATE = 10 #ovo dobiva od odometrije self.x = 0 self.y = 0 self.vel_x = 0 self.vel_y = 0 self.initial_pos_set = False package = rospkg.RosPack().get_path('mrs_project2_simulation') formation_positions_param = rospy.get_param('~formation_positions_param', default="empty_triangle_random_form") robot_num = int(rospy.get_name()[-1]) #robot_0 -> 0 self.formations = np.loadtxt(package + f"/formation_positions/{formation_positions_param}.txt", delimiter=" ", comments="#") self.formation_position_x = self.formations[robot_num, 0] self.formation_position_y = self.formations[robot_num, 1] self.avoidance_factor = 0.25 self.is_leader = rospy.get_param('~is_leader', default=False) if self.is_leader: self.goal_position_x = self.formation_position_x self.goal_position_y = self.formation_position_y self.goal_pos_service = rospy.Service('set_goal_position', SetGoalPosition, self.handle_set_goal_position) self.neighbours_odoms = [] self.obstacles = PointCloud() self.publisher_vel = rospy.Publisher(f"{rospy.get_name()}/cmd_vel", Twist, queue_size=self.PUB_RATE) #ovo uzima stage i pomice robota,, publisha svoj cmd_vel rospy.Subscriber(f"{rospy.get_name()}/odom", Odometry, self.odom_callback, queue_size=1) #stage publisha na ovaj topic rospy.Subscriber(f"{rospy.get_name()}/neighbours", Neighbours, self.neighbours_callback, queue_size=1) #tu calc_neighbours_node publisha odom susjeda od ovog node-a rospy.Subscriber(f"{rospy.get_name()}/obstacles", PointCloud, self.map_callback, queue_size=1) self.rate = rospy.Rate(self.PUB_RATE) #frekvencija kojom publisha poruke, nece affectat to da missas poruke koje dobivas, ovo utjece samo na publishanje def handle_set_goal_position(self, request): # Save the goal position from the service request self.goal_position_x = request.x self.goal_position_y = request.y return True def odom_callback(self, odom_msg): self.x = odom_msg.pose.pose.position.x self.y = odom_msg.pose.pose.position.y self.vel_x = odom_msg.twist.twist.linear.x self.vel_y = odom_msg.twist.twist.linear.y def neighbours_callback(self, neighbours: Neighbours): self.neighbours_odoms = neighbours.neighbours_odoms #Neighbours je lista Odometry poruka def map_callback(self, obstacles: PointCloud): self.obstacles = obstacles def run(self): while not rospy.is_shutdown(): vel_x = 0 #vel za izracunat i outputat, a self.vel_x je trenutni vel dobiven iz odometrij vel_y = 0 if self.is_leader: #ako je leader, nece ni uzlazi u ovaj neighbours loop jer nema ni jednog susjeda,,, on ne prima pozicije od nikog i ne updatea svoju poziciju s obzirom na druge vel_x = self.goal_position_x - self.x vel_y = self.goal_position_y - self.y for neighbour in self.neighbours_odoms: neigh_x, neigh_y = neighbour.pose.pose.position.x, neighbour.pose.pose.position.y #print(neighbour.child_frame_id) neigh_index = int(neighbour.child_frame_id) vel_x += (neigh_x - self.x) - (self.formations[neigh_index, 0] - self.formation_position_x) vel_y += (neigh_y - self.y) - (self.formations[neigh_index, 1] - self.formation_position_y) if np.linalg.norm([vel_x, vel_y]) > 0.05: #inace ce djelit s 0 (ako je == 0, ovo da ne skalira bezveze ako je dosta mala brzina) desired_norm = 0.5 s = desired_norm / np.linalg.norm([vel_x, vel_y]) vel_x *= s vel_y *= s vel = Twist() vel.linear.x = vel_x vel.linear.y = vel_y vel_avoid = [0, 0] if len(self.obstacles.points) != 0: cordinate_difference = np.array([[self.x - obstacle.x, self.y - obstacle.y] for obstacle in self.obstacles.points]) euclidean_distances = np.array([[math.dist([self.x,self.y],[obstacle.x, obstacle.y])] for obstacle in self.obstacles.points]) for i,distance in enumerate(euclidean_distances): vel_avoid += cordinate_difference[i] / abs(distance**3) vel_avoid /= len(self.obstacles.points) vel.linear.x += vel_avoid[0] * self.avoidance_factor vel.linear.y += vel_avoid[1] * self.avoidance_factor self.publisher_vel.publish(vel) self.rate.sleep() pass if __name__ == '__main__': rospy.init_node('robot_0') #debug try: agent_node = AgentNode() agent_node.run() except rospy.ROSInterruptException: pass
import React from 'react' import { useEffect, useState } from 'react' import { useSelector } from 'react-redux' import { selectCurrentUser } from '../../features/auth/authSlice' import { useSearchUsersQuery } from '../../features/users/usersApiSlice' import Contact from '../userItem/Contact' import UserSearched from '../userItem/UserSearched' import AddContactBtn from './button/AddContactBtn' import './SearchMain.css' const SearchMain = () => { const [search, setSearch] = useState("") const currentUser = useSelector(selectCurrentUser) const { data, refetch } = useSearchUsersQuery({ search: search || "?", userId: currentUser.id }) useEffect(() => { }, [data]) const handleChange = (e) => { setSearch(e.target.value) } return ( <div className='searchContainer'> <div className="searchInputContainer"> <span class="material-symbols-outlined"> search </span> <input type={"text"} onChange={handleChange} value={search} placeholder={"Buscar usuario nuevo..."} /> </div> <ul className='resultsList'> { data?.results ? (data.results.map((user) => <li key={user.id} className="userResult"> <UserSearched img={user.img} name={user.name} userId={currentUser.id} contactId={user.id} userName={currentUser.name} /> </li>)) : (<div> </div>) } </ul> </div> ) } export default SearchMain
import * as admin from "firebase-admin"; import * as functions from "firebase-functions"; admin.initializeApp(); /** * Listening for any document in the 'listings' collection to newly be created, * use Google's geocoder and diststancematrix APIs to get location information * for a listing if a zip code is available. * * Distance calculations are based on the 'settings/location' origin location. */ export const setLocationOnListingIfMissing = functions.firestore .document("listings/{vin}") .onCreate(require("./functions/setLocationOnListingIfMissing").default); /** * Listening for any document in the 'listings' collection to newly be created, * save a copy of the first image in the `photo_urls` array, if present, to a * Firebase storage bucket. **/ export const saveRepresentativeImage = functions.firestore .document("listings/{vin}") .onCreate(require("./functions/saveRepresentativeImage").default); /** * At 5AM and 4PM Eastern Time, fetch the latest search results from supported * listing services, creating and updating documents in the 'listings' collection * in Cloud Firestore. */ export const syncListings = functions.pubsub .schedule("0 5,16 * * *") .timeZone("America/New_York") .onRun(require("./functions/syncListings").default); /** * When a user record is created or updated, make sure all the push tokens on file * for them are subscribed to the 'New Listings' topic. */ export const subscribeUserPushTokensToNewListingsTopic = functions.firestore .document("users/{uid}") .onWrite( require("./functions/subscribeUserPushTokensToNewListingsTopic").default );
import React, { useState } from "react"; import Product from "./ProductDetails"; import "./Daypack.css"; const GymBag1 = "https://images-bucket-yutk.s3.eu-north-1.amazonaws.com/Images/GymBagImages/GymBag1.jpg" const GymBag2 = "https://images-bucket-yutk.s3.eu-north-1.amazonaws.com/Images/GymBagImages/GymBag2.jpg" const GymBag3 = "https://images-bucket-yutk.s3.eu-north-1.amazonaws.com/Images/GymBagImages/GymBag3.jpg" const GymBag4 = "https://images-bucket-yutk.s3.eu-north-1.amazonaws.com/Images/GymBagImages/GymBag4.jpg" const GymBag5 = "https://images-bucket-yutk.s3.eu-north-1.amazonaws.com/Images/GymBagImages/GymBag5.jpg" function GymBag() { const product = { name: "YUTK Water Proof Shoulder Casual/College Outdoor Bag", mrp: "1500", price: "599", highlights: ` Casual College Outdoor and for other sports 2 full zipper compartments Can keep Book, pair of shoes, mobile , keys, water Bottle etc Ideal for Men and Women material: Made using water-resistant polyester fabric on the outside and polyester fabric on the inside`, description: `Top quality from Yutk`, }; const imageList = [ { type: "image", src: GymBag1 }, { type: "image", src: GymBag2 }, { type: "image", src: GymBag3 }, { type: "image", src: GymBag4 }, { type: "image", src: GymBag5 }, ]; const [selectedImage, setSelectedImage] = useState(imageList[0]); const handleImageSelect = (image) => { setSelectedImage(image); }; return ( <div className="main-display"> <div className="left-display"> <div className="left-pics"> {imageList.map((image, index) => ( <img key={index} src={image.src} alt={`Image ${index + 1}`} id="left-img" className={selectedImage === image ? "selected" : ""} onClick={() => handleImageSelect(image)} /> ))} </div> </div> <div className="right-display"> <img src={selectedImage.src} className="right-img" alt="Selected Image" /> </div> <div className="right-display2"> <Product name={product.name} mrp={product.mrp} price={product.price} highlights={product.highlights} description={product.description} /> </div> </div> ); } export default GymBag;
package com.oyoungy.controller; import com.oyoungy.ddd.application.command.AddPostingCommand; import com.oyoungy.ddd.application.dto.*; import com.oyoungy.ddd.application.query.PageQuery; import com.oyoungy.ddd.application.service.PostingService; import com.oyoungy.exceptions.WallBaseException; import com.oyoungy.exceptions.WallNotFoundException; import com.oyoungy.response.ResultDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.math.BigInteger; @RestController @RequestMapping("/posting") public class PostingController { @Autowired private PostingService postingService; @GetMapping("/hello") public ResultDTO<String> helloWorld(){ return ResultDTO.success("hello world !!"); } @GetMapping("/{categoryId}") ResultDTO<PageDTO<PostingBriefDTO, BigInteger>> getPostings( @PathVariable Long categoryId, @RequestParam(defaultValue = "0", name = "offset") BigInteger minId, @RequestParam(defaultValue = "10") Integer pageSize){ PageQuery<BigInteger> pageQuery = new PageQuery<>(); pageQuery.setLowerBound(minId); pageQuery.setPageSize(pageSize); return ResultDTO.success(postingService.queryPostingByCategory(categoryId, pageQuery)); } @GetMapping("/") ResultDTO<PostingQueryDTO> getPosting(@RequestParam(name = "postingId") BigInteger postingId) throws WallBaseException { return ResultDTO.success(postingService.queryPostingById(postingId)); } @PostMapping("/") ResultDTO<PostingStateDTO> addPosting(@RequestBody @Validated AddPostingCommand addPostingCommand){ return ResultDTO.success(postingService.addPosting(addPostingCommand)); } @DeleteMapping("/") ResultDTO<Void> deletePosting(@RequestParam(name = "postingId") BigInteger postingId) throws WallNotFoundException { postingService.deletePosting(postingId); return ResultDTO.success(null); } }
import React, { useState } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faShuffle } from "@fortawesome/free-solid-svg-icons"; import { ToggleShuffle } from "./../../lib/API/getInfo"; const ShuffleButton = ({ size }) => { const [shuffle, setShuffle] = useState(false); const [iconColor, setIconColor] = useState("#B2B2B2"); function handleShuffle() { if (!shuffle) { setShuffle(true); ToggleShuffle(true); setIconColor("#1db954"); } else { setShuffle(false); ToggleShuffle(false); setIconColor("#B2B2B2"); } } return ( <> <FontAwesomeIcon icon={faShuffle} size={size} style={{ color: iconColor }} className="cursor-pointer hover:scale-110 transition-transform duration-300 ease-in-out" onMouseEnter={() => { if (!shuffle) { setIconColor("#ffffff"); } }} onMouseLeave={() => { if (!shuffle) { setIconColor("#B2B2B2"); } }} onClick={handleShuffle} /> </> ); }; export default ShuffleButton;
using FluentValidation; using System; namespace LessonsManagement.Business.Models.Validations { public class FileImportedValidation : AbstractValidator<FileImported> { public FileImportedValidation() { RuleFor(f => f.FilePath) .NotEmpty().WithMessage("You must select a file to upload."); RuleFor(f => f.FileDescription) .NotEmpty().WithMessage("The field {PropertyName} is required.") .Length(0, 100) .WithMessage("The field {PropertyName} needs to be between {MinLength} and {MaxLength}."); RuleFor(f => f.StartDate) .NotEmpty().WithMessage("The field {PropertyName} is required.") .Must(ValidDate) .WithMessage("The field {PropertyName} needs to be greater than {MinLength} and less than {MaxLength}."); RuleFor(f => f.EndDate) .NotEmpty().WithMessage("The field {PropertyName} is required.") .Must(ValidDate) .WithMessage("The field {PropertyName} needs to be greater than {MinLength} and less than {MaxLength}."); } protected bool ValidDate(DateTime date) { if (date > DateTime.MinValue && date < DateTime.MaxValue) { return true; } return false; } } }
import Modal from "../Modal/Modal"; import styles from "./DeleteModal.module.css"; import Footer from "../Footer/Footer"; type Props = { description: string; disabled?: boolean; onClose: (update?: boolean) => void; onDelete: () => void; title: string; }; const DeleteModal = ({ description, disabled = false, onClose, onDelete, title, }: Props) => { return ( <Modal title={title} footer={ <Footer disabled={disabled} onClose={onClose} onSubmit={onDelete} submitLabel="Confirm" closeLabel="Close" /> } > <div className={styles.container}>{description}</div> </Modal> ); }; export default DeleteModal;
/* * Copyright (c) 2021, Azul Systems * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of [project] nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.loadgen.solr; /** * @author deepakr */ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.LockSupport; public class ThroughputController { private final AtomicLong operationCounter = new AtomicLong(); private final int throughputToAchieve; private final long intendedTimeBetweenSuccessiveOpsInNanos; private long operationStartTimeInNanos; private ThroughputController(int throughputToAchieve) { this.throughputToAchieve = throughputToAchieve; this.operationStartTimeInNanos = System.nanoTime(); intendedTimeBetweenSuccessiveOpsInNanos = TimeUnit.SECONDS.toNanos(1) / throughputToAchieve; } public static ThroughputController getInstance(int throughputToAchieve) { return new ThroughputController(throughputToAchieve); } public int getThroughputToAchieve() { return throughputToAchieve; } public void markCurrentTimeAsOperationStartTime() { // by default, the start time is set at the instance creation time (in the constructor) // use this method to reset it this.operationStartTimeInNanos = System.nanoTime(); } public long getOperationStartTimeInNanos() { return operationStartTimeInNanos; } public long getIntededStartTimeOfNthOperation(int n) { return operationStartTimeInNanos + n * intendedTimeBetweenSuccessiveOpsInNanos; } public long getTotalOperationsCompletedSoFar() { return operationCounter.get(); } public long blockUntilIntendedStartTimeOfNextOperation() { long totalRequestsCompletedSoFar = operationCounter.getAndIncrement(); long intendedStartTimeOfNextOperationInNanos = operationStartTimeInNanos + totalRequestsCompletedSoFar * intendedTimeBetweenSuccessiveOpsInNanos; // while(intendedStartTimeOfNextOperationInNanos < System.nanoTime()) { // totalRequestsCompletedSoFar = operationCounter.getAndIncrement(); // intendedStartTimeOfNextOperationInNanos = operationStartTimeInNanos + totalRequestsCompletedSoFar * intendedTimeBetweenSuccessiveOpsInNanos; // } long now; while ((now = System.nanoTime()) < intendedStartTimeOfNextOperationInNanos) { LockSupport.parkNanos(intendedStartTimeOfNextOperationInNanos - now); } return intendedStartTimeOfNextOperationInNanos; } public void reset() { markCurrentTimeAsOperationStartTime(); operationCounter.set(0); } }
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { CSVLink } from "react-csv"; import Form from "react-bootstrap/Form"; import Store from "../zustand/store.js"; import Button from "react-bootstrap/Button"; import Modal from "react-bootstrap/Modal"; const Dashboard = () => { let navigate = useNavigate(); const { setRegUser, RegUser } = Store(); const [localData, setLocalData] = useState(RegUser); const [searchData, setSearchData] = useState(""); const [filUserList, setFilUserList] = useState(RegUser); const [userList, setUserList] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [iteamParPage, setIteamParpage] = useState(2); const [show, setShow] = useState(false); const [formData, setFormData] = useState({ Fname: "", Email: "", company: "", salary: "", }); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const totalPages = Math.ceil(filUserList?.length / iteamParPage); const indexOfLastItem = currentPage * iteamParPage; const indexOfFirstItem = indexOfLastItem - iteamParPage; const currentItems = filUserList?.slice(indexOfFirstItem, indexOfLastItem); // Create an array of page numbers const pageNumbers = []; for (let i = 1; i <= totalPages; i++) { pageNumbers.push(i); } // Function to handle page changes const handlePageChange = (pageNumber) => { setCurrentPage(pageNumber); }; useEffect(() => { if (localStorage.getItem("useEmail")) { navigate("/dashboard"); getData(); } else { navigate("/"); } }, []); const getData = () => { setUserList(RegUser); }; const searchme = (e) => { let searchVal = e.target.value; setSearchData(e.target.value); console.log("Search value:", searchVal); if (e.target.value != "") { const mySearch = localData.filter( (item) => item.Fname.toLowerCase()?.includes(e.target.value.toLowerCase()) || item.salary?.includes(e.target.value) ); setFilUserList(mySearch); } else if (!e.target.value) { setFilUserList(localData); } }; const delMe = (id) => { let arr = localData; arr?.splice(id, 1); console.log("dgshghsdh:", arr); setRegUser(arr); }; const saveMe = () => { console.log("formData", formData); localData.push(formData); handleClose(); }; return ( <div> <h2>Welcome </h2> <div style={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <div className="row"> <div className="col-6"> Search <input type="text" onChange={searchme} /> </div> <div className="col-6"> <CSVLink data={filUserList ? filUserList : ""}> Download CSV </CSVLink> ; </div> <table className="audit table"> <thead className="table-th"> <tr> <th>S.No.</th> <th>First Name</th> <th>Company Name</th> <th>Email Id</th> <th>Salary</th> <center> <th>Action</th> </center> </tr> </thead> <tbody className="table-body"> {currentItems && currentItems.map((item, i) => ( <tr> <td>{i + 1}</td> <td> {item.Fname}</td> <td> {item.company}</td> <td>{item.Email}</td> <td>{item.salary}</td> <td> <center> <button onClick={(e) => delMe(i)}>Del</button> </center> </td> <td> <center> <button onClick={handleShow}>Add</button> </center> </td> </tr> ))} </tbody> </table> <div> {pageNumbers.map((pageNumber) => ( <button key={pageNumber} onClick={() => handlePageChange(pageNumber)} disabled={currentPage === pageNumber} > {pageNumber} </button> ))} </div> <div className="modal show" style={{ display: "block", position: "initial" }} > <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Modal heading</Modal.Title> </Modal.Header> <Modal.Body> <Form> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1" > <Form.Label>Name</Form.Label> <Form.Control type="text" placeholder="Name" value={formData.Fname} onChange={(e) => setFormData({ ...formData, Fname: e.target.value }) } /> <Form.Label>Company</Form.Label> <Form.Control type="text" placeholder="Company Name" value={formData.company} onChange={(e) => setFormData({ ...formData, company: e.target.value }) } /> <Form.Label>Email Id</Form.Label> <Form.Control type="email" placeholder="Email Id" value={formData.Email} onChange={(e) => setFormData({ ...formData, Email: e.target.value }) } /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1" > <Form.Label>salary</Form.Label> <Form.Control type="text" placeholder="salary" value={formData.salary} onChange={(e) => setFormData({ ...formData, salary: e.target.value }) } /> </Form.Group> </Form> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}> Close </Button> <Button variant="primary" onClick={saveMe}> Save Changes </Button> </Modal.Footer> </Modal> </div> </div> </div> </div> ); }; export default Dashboard;
import { Fragment, useState } from "react"; import { XMarkIcon, Bars3Icon, SquaresPlusIcon, CursorArrowRaysIcon, } from "@heroicons/react/24/outline"; import { Link } from 'react-router-dom'; import { ChevronDownIcon } from "@heroicons/react/20/solid"; import { Dialog, Disclosure, Popover, Transition } from "@headlessui/react"; import LoginPopup from "../Components/LoginModal/Modal"; import { getCredentials } from '../Functions/util'; import useAuth from '../State/AuthProvider'; const products = [ { name: "Shopping", description: "A List of products offered by RV Enterprises", href: "/products", icon: SquaresPlusIcon, }, { name: "FOREX TRADING", description: "Get an insight about RV enterprises Forex Trading", href: "/", icon: CursorArrowRaysIcon, }, ]; function classNames(...classes) { return classes.filter(Boolean).join(" "); } export default function Header() { const { logoutMutation } = useAuth(); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); const {userID} = getCredentials() || null; function handleLogout() { logoutMutation.mutate({}, { onSettled: () => window.location.reload() }); } return ( <header className="navbar bg-white"> <div className="text-sm pt-1 sm:visible invisible w-full h-6 bg-black"> <ul className="sm:flex flex-col sm:flex-row align-center justify-around cursor-pointer text-white"> <li className="hover:text-[#EEAA0F]">RESOURCES & DOWNLOADS</li> <li className="hover:text-[#EEAA0F]"> <Link to ="/privacy-policy">Privacy Policies</Link> </li> <li className="hover:text-[#EEAA0F]"> <Link to ="/term">Terms and condition</Link> </li> <a href="https://news.google.com/search?q=%22real%20value%22&hl=en-IN&gl=IN&ceid=IN%3Aen" target="blank"><li className="hover:text-[#EEAA0F]"> RV Newsletter</li></a> </ul> </div> <nav className="mx-auto flex max-w-7xl items-center justify-between p-4 lg:px-8" aria-label="Global"> <div className="flex lg:flex-1"> <Link to="/" className="-m-2"> <span className="sr-only">RV ENterprises</span> <img width={100} src="/logo-dark.png" alt="" /> </Link> </div> <div className="flex lg:hidden"> <button type="button" className="-m-2.5 inline-flex items-center justify-center rounded-md p-2.5 text-gray-700" onClick={() => setMobileMenuOpen(true)}> <span className="sr-only">Open main menu</span> <Bars3Icon className="h-6 w-6" aria-hidden="true" /> </button> </div> <Popover.Group className="hidden lg:flex lg:gap-x-12"> <Popover className="relative"> <Popover.Button className="flex outline-none items-center gap-x-1 text-sm font-semibold leading-6 text-gray-900"> Future Plans <ChevronDownIcon aria-hidden="true" className="h-5 w-5 flex-none text-gray-400" /> </Popover.Button> <Transition as={Fragment} enter="transition ease-out duration-200" enterFrom="opacity-0 translate-y-1" enterTo="opacity-100 translate-y-0" leave="transition ease-in duration-150" leaveFrom="opacity-100 translate-y-0" leaveTo="opacity-0 translate-y-1"> <Popover.Panel className="absolute -left-8 top-full z-10 mt-3 w-screen max-w-lg overflow-hidden rounded-3xl bg-white shadow-lg ring-1 ring-gray-900/5"> <div className="products-list flex column gap-l p-2"> {products.map((item) => ( <div key={item.name} className="group relative flex items-center gap-x-6 rounded-lg p-4 text-sm leading-6 hover:bg-gray-50"> <div className="flex h-11 w-11 flex-none items-center justify-center rounded-lg bg-gray-50 group-hover:bg-white"> <item.icon className="h-6 w-6 text-gray-600 group-hover:text-indigo-600" aria-hidden="true" /> </div> <div className="flex-auto"> <Link to={item.href} className="block text-left font-semibold text-gray-900"> {item.name} <span className="absolute inset-0" /> </Link> <p className="mt-1 text-left text-gray-600"> {item.description} </p> </div> </div> ))} </div> </Popover.Panel> </Transition> </Popover> <Link to="/" className="text-sm font-semibold leading-6 text-gray-900"> Home </Link> <Link to="/about" className="text-sm font-semibold leading-6 text-gray-900"> About Us </Link> <Link to="/contactus" className="text-sm font-semibold leading-6 text-gray-900"> Contact Us </Link> {/* <Link to="/companyplans" className="text-sm font-semibold leading-6 text-gray-900"> Company Plans </Link> */} </Popover.Group> <div className="hidden lg:flex lg:flex-1 lg:justify-end"> <div className="flex items-center space-x-4"> {/* { !userID && <Link to="/signup" className="text-sm font-semibold leading-6 text-gray-900"> <u>Sign Up</u> </Link> } */} <Popover className="relative"> <Popover.Button className="flex outline-none items-center gap-x-1 text-sm font-semibold leading-6 text-gray-900"> <span className="text-sm font-semibold leading-6 text-gray-900"> {userID ? 'My Profile' : "Log In"} </span> <ChevronDownIcon className="h-5 w-5 flex-none text-gray-400" aria-hidden="true" /> </Popover.Button> <Transition as={Fragment} enter="transition ease-out duration-200" enterFrom="opacity-0" enterTo="opacity-100 " leave="transition ease-in duration-150" leaveFrom="opacity-100" leaveTo="opacity-0 "> <Popover.Panel className="loginPopup absolute z-10 mt-3 max-w-md overflow-hidden rounded-3xl bg-white shadow-lg ring-1 ring-gray-900/5"> <LoginPopup /> </Popover.Panel> </Transition> </Popover> { !userID && <Link to="/joinus" className="text-sm font-semibold leading-6 text-white bg-gradient-to-r from-blue-500 to-purple-500 px-4 py-0 rounded-lg hover:bg-gradient-to-r hover:from-purple-500 hover:to-blue-500 transition duration-300"> Join Us </Link> } </div> </div> </nav> <Dialog as="div" className="lg:hidden" open={mobileMenuOpen} onClose={() => setMobileMenuOpen(false)}> <div className="fixed inset-0 z-10" /> <Dialog.Panel className="fixed inset-y-0 right-0 z-10 w-full overflow-y-auto bg-white px-6 py-6 sm:max-w-sm sm:ring-1 sm:ring-gray-900/10"> <div className="flex items-center justify-between"> <Link to="/" className="-m-1.5 p-1.5"> <span className="sr-only">RV Enterprises</span> <img alt="" className="h-8 w-auto" src="https://tailwindui.com/img/logos/mark.svg?color=indigo&shade=600"/> </Link> <button type="button" className="-m-2.5 rounded-md p-2.5 text-gray-700" onClick={() => setMobileMenuOpen(false)}> <span className="sr-only">Close menu</span> <XMarkIcon className="h-6 w-6" aria-hidden="true" /> </button> </div> <div className="mt-6 flow-root"> <div className="my-6 divide-y divide-gray-500/10"> <div className="space-y-2 py-6"> <Disclosure as="div" className="-mx-3"> {({ open }) => ( <> <Disclosure.Button className="flex w-full items-center justify-between rounded-lg py-2 pl-3 pr-3.5 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Future Plans <ChevronDownIcon className={classNames( open ? "rotate-180" : "", "h-5 w-5 flex-none" )} aria-hidden="true" /> </Disclosure.Button> <Disclosure.Panel className="mt-2 space-y-2"> {products.map((item) => ( <Disclosure.Button key={item.name} as="a" to={item.href} className="block rounded-lg py-2 pl-6 pr-3 text-sm font-semibold leading-7 text-gray-900 hover:bg-gray-50"> {item.name} </Disclosure.Button> ))} </Disclosure.Panel> </> )} </Disclosure> <Link to="/about" className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> About Us </Link> <Link to="/contactus" className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Contact Us </Link> {/* <Link to="/companyplans" className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Company Plans </Link> */} <Link to="/user" className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> My Profile </Link> <Link to="/joinus" className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Join Us </Link> </div> <div className="py-6"> { userID ? <button onClick={handleLogout}>Logout</button> : ( <> <Link to="/login" className="-mx-3 block rounded-lg px-3 py-2.5 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Log In </Link> <Link to="/signup" className="-mx-3 block rounded-lg px-3 py-2.5 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50"> Sign Up </Link></>) } </div> </div> </div> </Dialog.Panel> </Dialog> </header> ); }
// // FeedProfileView.swift // WonderLive // // Created by Taimur imam on 22/12/23. // import SwiftUI import SwiftyJSON struct FeedProfileView: View { var feed_model : Feed_Model var showOptionButton = true var isBackButton = false @State private var toastMessage = "" @State private var isToastMessage = false @State private var isShowingActionSheet = false var body: some View { HStack { // Left side: Profile details HStack(spacing: 8) { if isBackButton{ BackButton() .padding(.top) } // Profile image ProfileImage(url: feed_model.feed_owner.profile_img , width: 50, leading_padding: 0 , isNaviagtion: true , user_id: feed_model.feed_owner.user_id ) .overlay( Circle().stroke(Color.primary_color, lineWidth: 1.0) ) // Title and subtitle VStack(alignment: .leading, spacing: 7) { Text(feed_model.feed_owner.name) .font(.appFont(type: .medium, size: 18)) .foregroundStyle(Color.primary_color) TimerText(timeString: feed_model.feed_time) } .padding(.leading , 5) } .padding(.leading , isBackButton ? 5 : 15) Spacer() if showOptionButton{ // Right side: More button Button(action: { // Handle more button action isShowingActionSheet.toggle() }) { Image(systemName: "ellipsis") .padding(.vertical) .padding(.trailing , 2) .foregroundColor(.app_black) .font(.appFont(type: .Bold, size: 22)) } .padding(.trailing) } } .background(.clear) .padding(.vertical , 7) .actionSheet(isPresented: $isShowingActionSheet) { SwiftUI.ActionSheet(title: Text("Select option"), buttons: [ .destructive(Text("Report this post"), action: { reportFeed() }), .destructive(Text("Block \(feed_model.feed_owner.name)"), action: { bloackUser() }), .cancel() ]) } } func reportFeed(){ FeedApiCall().reportFeed(feed_id: feed_model.id) { _response in if _response.isSuccess{ toastMessage = "We have received your report regarding this post" isToastMessage.toggle() }else{ toastMessage = _response.strResMsg isToastMessage.toggle() } } } func bloackUser(){ UserApiCall().blockUser(blocked_user_id: feed_model.feed_owner.user_id) { _response, isSuccess in if isSuccess{ toastMessage = "You have successfully blocked \(feed_model.feed_owner.name)" isToastMessage.toggle() }else{ toastMessage = _response.strResMsg isToastMessage.toggle() } } } } #Preview { FeedProfileView(feed_model: Feed_Model(from: JSON())) }
import { useReactiveVar } from '@apollo/client' import { EditorOptions } from '@mashcard/legacy-editor' import { Blob } from '@mashcard/schema' import { useCallback, useMemo } from 'react' import { PageTree } from '../../../../_shared/DocumentPageSidebar/PageTree' import { DocMeta } from '../../../../_shared/DocMeta' import { FormulaContextVar } from '../../../../_shared/reactiveVars' import { blockProvider } from '../useDocSyncProvider' import { getCursorColor } from './cursorColor' import { useDiscussion } from './useDiscussion' import { useEmbed } from './useEmbed' import { useLink } from './useLink' import { useMentionCommands } from './useMentionCommands' export interface UseEditorOptions { docMeta: DocMeta docBlobs: Blob[] editable: boolean provider: blockProvider | undefined } export function useEditorOptions({ docMeta, docBlobs, editable, provider }: UseEditorOptions): EditorOptions { const discussion = useDiscussion(docMeta) const embed = useEmbed(docBlobs, docMeta) const formulaContext = useReactiveVar(FormulaContextVar) const mentionCommands = useMentionCommands(docMeta) const link = useLink(docMeta) const renderView = useCallback(() => <PageTree mode="subPage" />, []) const { currentUser } = globalThis.mashcardContext return useMemo<EditorOptions>( () => ({ base: { callout: { prepareFileUpload: embed.prepareFileUpload }, collaboration: provider ? { document: provider.document } : false, collaborationCursor: provider && currentUser ? { provider, user: { id: currentUser.name, name: currentUser.name, avatarData: currentUser.avatarData, operatorId: globalThis.mashcardContext.uuid, color: getCursorColor(`c:${currentUser.name}`) } } : false, discussion, embed, formula: { formulaContext }, link, mentionCommands, pageLink: { pages: mentionCommands.pages }, subPageMenu: { renderView } }, editable }), [embed, provider, currentUser, discussion, formulaContext, link, mentionCommands, renderView, editable] ) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Spense Landing Pages</title> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="media-query.css" /> <script src="https://kit.fontawesome.com/8ecc7da907.js" crossorigin="anonymous" ></script> </head> <body> <h1 class="banner"> 🎉 To celebrate Spense's launch, we will be waiving all fees for the entire month of April. <span> You will be receiving 100% of the earnings.</span> 🎉 </h1> <header> <p class="logo">spense.</p> <nav class="header_navbar"> <a href="#">Business</a> <a href="#">Pricing</a> <a href="#">Features</a> </nav> <form action="#"> <input type="email" name="Login" placeholder="Login" class="email" required /> <input type="submit" value="Get Started" /> </form> <img src="./Assets/Hamburger Menu.svg" alt="Hamburger Menu" class="hamburger_menu" /> </header> <main class="share_your_unfiltered"> <article class="sub_share_your_unfiltered"> <h2>Share your unfiltered thoughts. Get paid.</h2> <p> Spense is an open platform for individuals to share their unfiltered thoughts. Discuss the topic you love. </p> <div> <p> <img src="./Assets/Checkmark.svg" alt="Check mark" /> Receive 99% off the earnings. </p> <p> <img src="./Assets/Checkmark.svg" alt="Check mark" /> Get paid via Debit Card, ACH, or PayPal.💳 </p> <p> <img src="./Assets/Checkmark.svg" alt="Check mark" /> Withdraw your earnings anytime. </p> </div> <form action="#"> <input type="email" name="Login" placeholder="john@example.com" class="email" required /> <input type="submit" value="Get Started" /> </form> </article> <picture> <source media="(max-width: 768px)" srcset="./Assets/Hero Image (Mobile).png" /> <img src="./Assets/Hero Image (Desktop).png" alt="Hero Image" class="hero_image_desktop" /> </picture> </main> <section class="company_logos"> <div class="company_logos_mobile"> <img src="./Assets/Facebook Logo.png" alt="Facebook Logo" /> <img src="./Assets/Dribbble Logo.png" alt="Dribbble Logo" /> <img src="./Assets/Youtube Logo.png" alt="Youtube Logo" /> </div> <div class="company_logos_desktop"> <img src="./Assets/Facebook Logo.png" alt="Facebook Logo" /> <img src="./Assets/Dribbble Logo.png" alt="Dribbble Logo" /> <img src="./Assets/Youtube Logo.png" alt="Youtube Logo" /> <img src="./Assets/Pinterest Logo.png" alt="Pinterest Logo" /> <img src="./Assets/Twitter Logo.png" alt="Twitter Logo" /> <img src="./Assets/Reddit Logo.png" alt="Reddit Logo" /> <img src="./Assets/Google Logo.png" alt="Google Logo" /> <img src="./Assets/Slack Logo.png" alt="Slack Logo" /> </div> </section> <section class="secure_your_money"> <article class="sub_secure_your_money"> <h3>Secure your money with Escrow.</h3> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Reprehenderit alias iste eius inventore ducimus, quasi repellendus? Totam quidem fuga amet nemo aliquam! Molestias, repellendus quidem. </p> <a href="#">Learn about Ecscrow ➡</a> </article> <picture> <source media="(min-width: 768px)" srcset="./Assets/Phone Mockup (Mobile).png" /> <img src="./Assets/Phone Mockup (Desktop).png" alt="Phone Mockup" /> </picture> </section> <section class="create_amazing_content"> <article class="quill_video"> <img src="./Assets/Text Editor-Menu.png" alt="Text Editor-Menu" /> <div> <h3>Create amazing content</h3> <p> Using Quill as our text editor, we pull you into focus mode to make sure you create the best writings you can. </p> </div> <iframe title="Quill Text Editor" width="100%" height="100%" src="https://player.vimeo.com/video/253905163" frameborder="0" allow="autoplay; encrypted-media" >Quill Editor </iframe> </article> <article class="sub_create_amazing_content"> <h3>A text editor like no other.</h3> <p> Our text editor pulls you into focus mode with it's simplistic design and usability so you can put out your best writings. </p> <a href="https://quilljs.com/playground/" target="_blank"> Editor Live Demo ➡ </a> </article> </section> <footer> <div class="spense_text"> <p class="logo">spense.</p> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Fugit, quam aliquam veniam tenetur qui voluptates necessitatibus earum sint perspiciatis error. </p> </div> <nav> <div class="sitemap footer_info"> <p class="bold_text">Sitemap</p> <a href="#">Homepage</a> </div> <div class="resources footer_info"> <p class="bold_text">Resources</p> <a href="#">Support</a> <a href="#">Contact</a> <a href="#">faq</a> </div> <div class="company footer_info"> <p class="bold_text">Company</p> <a href="#">About</a> <a href="#">Customers</a> <a href="#">Blog</a> </div> <div class="opportunities footer_info"> <p class="bold_text">Opportunities</p> <a href="#">Jobs</a> </div> </nav> </footer> </body> </html>
<!-- 事件委托 --> <body> <ul id="ul1"> <li>111</li> <li>222</li> <li>333</li> <li>444</li> </ul> <div id="box"> <input type="button" id="add" value="添加" /> <input type="button" id="remove" value="删除" /> <input type="button" id="move" value="移动" /> <input type="button" id="select" value="选择" /> </div> </body> <script> /* window.onload = function(){ var oUl = document.getElementById("ul1"); var aLi = oUl.getElementsByTagName('li'); for(var i=0;i<aLi.length;i++){ aLi[i].onclick = function(){ alert(123); } } } */ /* 点击ul或子元素都会有效果 */ /* 这里用父级ul做事件处理,当li被点击时,由于冒泡原理,事件就会冒泡到ul上,因为ul上有点击事件,所以事件就会触发 */ /* window.onload=function(){ var oUL=document.getElementById("ul1"); oUL.onclick=function(){ alert(123); } */ /* 只有点击li才会触发 */ /* Event对象提供了一个属性叫target,可以返回事件的目标节点,我们成为事件源,也就是说, target就可以表示为当前的事件操作的dom,但是不是真正操作dom,当然,这个是有兼容性的, 标准浏览器用ev.target,IE浏览器用event.srcElement,此时只是获取了当前节点的位置,并不知道是什么节点名称, 这里我们用nodeName来获取具体是什么标签名,这个返回的是一个大写的,我们需要转成小写再做比较(习惯问题) */ window.onload = function(){   var oUl = document.getElementById("ul1");   oUl.onclick = function(ev){     var ev = ev || window.event;     var target = ev.target || ev.srcElement;     if(target.nodeName.toLowerCase() == 'li'){          alert(123);         alert(target.innerHTML);     }   } } /* 每个input被点击的效果不一样 */ window.onload=function(){ var box=document.getElementById("box"); box.onclick=function(ev){ var ev=ev||window.event; var target=ev.target||ev.srcElement; if(target.nodeName.toLowerCase()=="input"){ switch(target.id){ case 'add': alert("添加"); break; case 'remove': alert("删除"); break; case 'move': alert("移动"); break; case 'select': alert("选择"); break; } } } } </script>
/* * A simple protocol to allow players to match into pairs when looking for the same type of match * * This files contains the implementation of a state manager which watches for messages and uses * them to build a picture of state on the network, and an agent which executes the protocol. * * The protocol implements the following process: * * A user wishing to join a game first checks if there are any games already existing in the state that match the game they want * If there are, the user makes a `claim` to join one of those games. If they are accepted the host sends an `ack` starting the game * If there are no ready games the player will advertise a new game as host. When another player claims a seat in their game they * ack it and start the game * * The matcher uses 4 pubsub channels, 1 for each type of message to keep the protocol very simply for just now (each stream has only 1 type of message) * * The unadvertise message is used to clear an advert from the network state. It is sent both when a game is successfully filled and when the advertiser wants to cancel the game */ import { IRoundPubSub } from './RoundTable' import { PublicKey } from "@solana/web3.js" import { timeStamp } from 'console'; import { getTextOfJSDocComment } from 'typescript'; export const ADVERTISE_TIMEOUT = 15000; export const SERVING_REBROADCAST_TIMEOUT = 10000; export const CLAIM_ACK_TIMEOUT = 5000; export const MATCH_ADVERTISE_PUBSUB_CHANNEL = "-match-advertise"; export const MATCH_UNADVERTISE_PUBSUB_CHANNEL = "-match-unadvertise"; export const MATCH_CLAIM_PUBSUB_CHANNEL = "-match-claim"; export const MATCH_ACK_PUBSUB_CHANNEL = "-match-ack"; export function getMatchID(advertiser: PublicKey, match: string): string { return advertiser.toString() + match } export class MatchAdvertiseMessage { advertiser: PublicKey; match: string; counter: number; constructor( user: PublicKey, match: string, counter: number ) { this.advertiser = user; this.match = match; this.counter = counter; } serialise(): any { return { advertiser: this.advertiser.toString(), match: this.match, counter: this.counter } } static deserialise(msg: any) { return new MatchAdvertiseMessage( new PublicKey(msg.advertiser), msg.match, msg.counter ) } } export class MatchUnadvertiseMessage { matchId: string; constructor( matchId: string ) { this.matchId = matchId; } serialise(): any { return { matchId: this.matchId } } static deserialise(msg: any) { return new MatchUnadvertiseMessage( msg.matchId, ) } } export class MatchClaimMessage { matchId: string; user: PublicKey; counter: number; constructor( matchId: string, user: PublicKey, counter: number ) { this.matchId = matchId; this.user = user; this.counter = counter; } serialise(): any { return { matchId: this.matchId, user: this.user.toString(), counter: this.counter } } static deserialise(msg: any) { return new MatchClaimMessage( msg.matchId, new PublicKey(msg.user), msg.counter ) } } export class MatchAckMessage { matchId: string; user: PublicKey; constructor( matchId: string, user: PublicKey ) { this.matchId = matchId; this.user = user; } serialise(): any { return { matchId: this.matchId, user: this.user.toString() } } static deserialise(msg: any) { return new MatchAckMessage( msg.matchId, new PublicKey(msg.user) ) } } export type MatchEventListener = (match: MatchState) => void; export class MatchState { advertiser: PublicKey; advertiserCounter: number; match: string; matchId: string; lastSeen: number; claimsSeen: ([PublicKey, number])[]; acksSeen: PublicKey[]; constructor( advertiser: PublicKey, advertiserCounter: number, match: string, lastSeen: number ) { this.advertiser = advertiser; this.advertiserCounter = advertiserCounter; this.match = match; this.matchId = getMatchID(advertiser, match); this.lastSeen = lastSeen; this.claimsSeen = []; this.acksSeen = []; } getCounter(id: PublicKey) { if (this.advertiser.equals(id)) { return this.advertiserCounter; } else { for (var i = 0; i < this.claimsSeen.length; i++) { if (this.claimsSeen[i][0].equals(id)) { return this.claimsSeen[i][1] } } } return -1; } } export class MatchStateManager { matchMap: { [matchId: string]: MatchState; } = {}; listeners: MatchEventListener[] = []; constructor() { } handleAdvertiseMessage(msg: MatchAdvertiseMessage) { console.log("Matcher: Got advertise message") const matchId = getMatchID(msg.advertiser, msg.match); if (this.matchMap[matchId]) { this.matchMap[matchId].lastSeen = (new Date()).getTime(); } else { this.matchMap[matchId] = new MatchState(msg.advertiser, msg.counter, msg.match, (new Date()).getTime()); } this.raiseUpdateEvent(matchId); } handleUnadvertiseMessage(msg: MatchUnadvertiseMessage) { console.log("Matcher: Got unadvertise message") if (this.matchMap[msg.matchId]) { delete this.matchMap[msg.matchId]; } } handleClaimMessage(msg: MatchClaimMessage) { console.log("Matcher: Got claim message") if (this.matchMap[msg.matchId]) { for (var c in this.matchMap[msg.matchId].claimsSeen) { if (this.matchMap[msg.matchId].claimsSeen[c][0].equals(msg.user)) { return; } } this.matchMap[msg.matchId].claimsSeen.push([msg.user, msg.counter]) this.raiseUpdateEvent(msg.matchId); } } handleAckMessage(msg: MatchAckMessage) { console.log("Matcher: Got Ack message") if (this.matchMap[msg.matchId]) { const match = this.matchMap[msg.matchId]; for (var a in match.acksSeen) { if (match.acksSeen[a].equals(msg.user)) { return; } } match.acksSeen.push(msg.user) this.raiseUpdateEvent(msg.matchId); this.remove(msg.matchId); } } remove(matchId: string) { delete this.matchMap[matchId]; } raiseUpdateEvent(matchId: string) { for (var l in this.listeners) { try { this.listeners[l](this.matchMap[matchId]); } catch (e: any) { console.log("Matcher: Exception in stateUpdateEvent") console.log(e) } } } checkTimeouts(time: number) { const t = (new Date()).getTime(); for (var m in this.matchMap) { if ((t - this.matchMap[m].lastSeen) > ADVERTISE_TIMEOUT) { delete this.matchMap[m]; } } } addListener(listener: MatchEventListener) { this.listeners.push(listener) } } export enum MatchAgentsStates { IDLE = 0, SERVING_WAITING_CLAIMS, JOINING_WAITING_ACK }; export class MatchResult { match: MatchState | null = null; constructor(match: MatchState | null) { this.match = match; } } export class MatchAgent { id: PublicKey; state: MatchAgentsStates = MatchAgentsStates.IDLE; counter: number; lastActionStart: number = 0; targetMatch: string[] | null = null; matchId: string | null = null; manager: MatchManager; matchCallback: ((result: MatchResult) => void) | null = null; constructor(manager: MatchManager, id: PublicKey, counter: number = 0) { this.manager = manager; this.id = id; this.counter = counter; } clearState() { this.state = MatchAgentsStates.IDLE; this.matchId = null; this.targetMatch = null; this.matchCallback = null; } restartMatch() { if (this.state == MatchAgentsStates.IDLE || !this.targetMatch || !this.matchCallback) { return; } this.state = MatchAgentsStates.IDLE this.startMatch(this.targetMatch, this.counter, this.matchCallback); } startMatch(targetMatch: string[], counter: number, matchCallback: (result: MatchResult) => void): boolean { console.log("Matcher: Starting match: " + targetMatch) if (this.state != MatchAgentsStates.IDLE) { // Cannot start matching, already matching console.log("Matcher: Can't start match, not IDLE") return false; } this.counter = counter; this.targetMatch = targetMatch; this.matchCallback = matchCallback; this.matchId = null; // Check if there is already a match that we can try to join // Randomise order for better matching with more peers const items = Object.entries(this.manager.matchStateManager.matchMap); const randomItems = items.sort((a,b) => {return Math.random() - 0.5}); for (var m in randomItems) { var match = randomItems[m][1]; if ( (this.targetMatch.indexOf(match.match) > -1) && (!match.advertiser.equals(this.id)) && (match.acksSeen.length == 0)) { console.log("Matcher: Joining existing game with id: " + match.matchId) this.state = MatchAgentsStates.JOINING_WAITING_ACK; this.lastActionStart = (new Date()).getTime(); this.manager.sendClaimMessage(new MatchClaimMessage( match.matchId, this.id, this.counter )) this.matchId = match.matchId; console.log("Matcher: Set match ID " + this.matchId) return true; } } console.log("Matcher: Advertising game") // Or start to advertise our own match this.matchId = getMatchID(this.id, this.targetMatch[0]); console.log("Matcher: Setting matchId " + this.matchId) this.state = MatchAgentsStates.SERVING_WAITING_CLAIMS; this.lastActionStart = (new Date()).getTime(); this.manager.sendAdvertiseMessage(new MatchAdvertiseMessage( this.id, this.targetMatch[0], this.counter )) return true; } stopMatch() { if (this.state == MatchAgentsStates.IDLE) { // Cannot stop matching, not matching } else if (this.state == MatchAgentsStates.SERVING_WAITING_CLAIMS) { if (this.matchId) { this.manager.sendUnadvertiseMessage(new MatchUnadvertiseMessage( this.matchId )) } this._matchCallback(new MatchResult(null)); this.clearState(); } else if (this.state == MatchAgentsStates.JOINING_WAITING_ACK) { this._matchCallback(new MatchResult(null)); this.clearState(); } } handleMatchStateUpdate(matchState: MatchState) { if (this.matchId != matchState.matchId) { // This is not state for the current match //console.log("Matcher: Wrong matchId " + this.matchId + " " + matchState.matchId) return; } console.log("Matcher: Handling match state update in state: " + MatchAgentsStates[this.state]) if (this.state == MatchAgentsStates.SERVING_WAITING_CLAIMS) { if (matchState.claimsSeen.length != 0) { this.manager.sendAckMessage(new MatchAckMessage( this.matchId, matchState.claimsSeen[0][0] )) this.manager.matchStateManager.remove(matchState.matchId) try { this._matchCallback(new MatchResult(matchState)); } catch (e: any) { console.log("Matcher: Exception in match callback: ") console.log(e) } this.clearState(); } } else if (this.state == MatchAgentsStates.JOINING_WAITING_ACK) { if (matchState.acksSeen.length != 0) { if (this.id.equals(matchState.acksSeen[0])) { this.manager.matchStateManager.remove(matchState.matchId) try { this._matchCallback(new MatchResult(matchState)); } catch (e: any) { console.log("Matcher: Exception in match callback: ") console.log(e) } this.clearState(); } else { console.log("Matcher: Restarting") this.restartMatch(); } } } else { console.log("Matcher: Bad state") } } _matchCallback(result: MatchResult) { if (this.matchCallback) { this.matchCallback(result); } } poll(time: number) { if (this.state == MatchAgentsStates.SERVING_WAITING_CLAIMS) { if (time - this.lastActionStart > SERVING_REBROADCAST_TIMEOUT) { console.log("Matcher: Timed out creating game") this.restartMatch(); } } else if (this.state == MatchAgentsStates.JOINING_WAITING_ACK) { if (this.matchId && !this.manager.matchStateManager.matchMap[this.matchId]) { console.log("Matcher: Invalid game") this.restartMatch(); } else if (this.matchId && this.manager.matchStateManager.matchMap[this.matchId].acksSeen.length > 0) { if (!this.manager.matchStateManager.matchMap[this.matchId].acksSeen[0].equals(this.id)) { console.log("Matcher: Not in game") this.restartMatch(); } } else if (time - this.lastActionStart > CLAIM_ACK_TIMEOUT) { console.log("Matcher: Timed out waiting for ack") this.restartMatch(); } } } } export class MatchManager { pubSub: IRoundPubSub; matchStateManager: MatchStateManager; matchAgent: MatchAgent; listeners: MatchEventListener[] = []; constructor(roundNet: IRoundPubSub, id: PublicKey) { this.pubSub = roundNet; this.pubSub.sub(MATCH_ADVERTISE_PUBSUB_CHANNEL, msg => { this._handleAdvertiseMessage(msg) }); this.pubSub.sub(MATCH_UNADVERTISE_PUBSUB_CHANNEL, msg => { this._handleUnadvertiseMessage(msg) }); this.pubSub.sub(MATCH_CLAIM_PUBSUB_CHANNEL, msg => { this._handleClaimMessage(msg) }); this.pubSub.sub(MATCH_ACK_PUBSUB_CHANNEL, msg => { this._handleAckMessage(msg) }); this.matchAgent = new MatchAgent(this, id); this.matchStateManager = new MatchStateManager(); this.matchStateManager.addListener(state => { this.matchAgent.handleMatchStateUpdate(state); }) setInterval(() => { this.matchAgent.poll((new Date()).getTime()) }, 100); setInterval(() => { this.matchStateManager.checkTimeouts((new Date()).getTime()) }, 2000); } _handleAdvertiseMessage(msg: any) { try { const msgData = new TextDecoder().decode(msg.data); var aMsg = MatchAdvertiseMessage.deserialise(JSON.parse(msgData)); this.matchStateManager.handleAdvertiseMessage(aMsg) } catch (e: any) { console.log("Matcher: Exception whilst handling Advertise Message") console.log(e) } } _handleUnadvertiseMessage(msg: any) { try { const msgData = new TextDecoder().decode(msg.data); const uMsg = MatchUnadvertiseMessage.deserialise(JSON.parse(msgData)); this.matchStateManager.handleUnadvertiseMessage(uMsg) } catch (e: any) { console.log("Matcher: Exception whilst handling Unadvertise Message") console.log(e) } } _handleClaimMessage(msg: any) { try { const msgData = new TextDecoder().decode(msg.data); const cMsg = MatchClaimMessage.deserialise(JSON.parse(msgData)); this.matchStateManager.handleClaimMessage(cMsg) } catch (e: any) { console.log("Matcher: Exception whilst handling Claim Message") console.log(e) } } _handleAckMessage(msg: any) { try { const msgData = new TextDecoder().decode(msg.data); const ackMsg = MatchAckMessage.deserialise(JSON.parse(msgData)); this.matchStateManager.handleAckMessage(ackMsg) } catch (e: any) { console.log("Matcher: Exception whilst handling Ack Message") console.log(e) } } sendAdvertiseMessage(msg: MatchAdvertiseMessage) { const encoded = new TextEncoder().encode(JSON.stringify(msg.serialise())) this.pubSub.pub( MATCH_ADVERTISE_PUBSUB_CHANNEL, encoded ); this._handleAdvertiseMessage({ data: encoded }); } sendUnadvertiseMessage(msg: MatchUnadvertiseMessage) { const encoded = new TextEncoder().encode(JSON.stringify(msg.serialise())) this.pubSub.pub( MATCH_UNADVERTISE_PUBSUB_CHANNEL, encoded ); this._handleUnadvertiseMessage({ data: encoded }); } sendClaimMessage(msg: MatchClaimMessage) { const encoded = new TextEncoder().encode(JSON.stringify(msg.serialise())) this.pubSub.pub( MATCH_CLAIM_PUBSUB_CHANNEL, encoded ); this._handleClaimMessage({ data: encoded }); } sendAckMessage(msg: MatchAckMessage) { const encoded = new TextEncoder().encode(JSON.stringify(msg.serialise())) this.pubSub.pub( MATCH_ACK_PUBSUB_CHANNEL, encoded ); this._handleAckMessage({ data: encoded }); } addMatchStateListener(listener: MatchEventListener) { this.matchStateManager.addListener(listener) } }
# Função para obter o peso do cachorro def cachorro_peso(): while True: try: peso = float(input("Digite o peso do cachorro (em kg): ")) if peso < 3: return 40 elif peso < 10: return 50 elif peso < 30: return 60 elif peso < 50: return 70 else: print("Não aceitamos cachorros tão grandes (50 kg).") except ValueError: print("Você digitou um valor não númerico.") # Função para obter o tipo de pelo do cachorro def cachorro_pelo(): while True: pelo = input("Digite o tipo de pelo do cachorro\nc - curto\nm - médio\nl - longo\n") if pelo in ['c', 'm', 'l']: if pelo == 'c': return 1 elif pelo == 'm': return 1.5 else: return 2 else: print("Opção de pelo inválida. Digite 'c', 'm' ou 'l'.") # Função para obter os serviços adicionais def cachorro_extra(): valor_extra = 0 while True: extra = input("Deseja adcionar mais algum serviço?\n1 - Corte de Unhas - R$10,00\n2 - Escovar Dentes - R$12,00\n3 - Limpeza de Orelhas R$15,00\n0 - Não desejo mais nada\n") if extra == '1': valor_extra += 10 elif extra == '2': valor_extra += 12 elif extra == '3': valor_extra += 15 elif extra == '0': return valor_extra else: print("Opção inválida. Digite '1', '2', '3' ou '0'.") print("Bem-vindo ao PetShop do Matheus Belarmino Pignata!") # Chamando as funções base = cachorro_peso() multiplicador = cachorro_pelo() extra = cachorro_extra() # Calculo do total total = base * multiplicador + extra # Print do retorno final print(f"Valor total a pagar: R$ {total:.2f} (peso: {base} * pelo: {multiplicador} + adicional(is): {extra})")
from drf_writable_nested import WritableNestedModelSerializer from rest_framework import serializers from cases.models import Case from invoices.serializers import RepairInvoiceSerializer from parties.serializers import ClientSerializer, ThirdPartySerializer, ProviderSerializer from .AccidentSerializer import AccidentSerializer from .CaseCreatorDetailsSerializer import CaseCreatorSerializer from .CaseFeeSerializer import CaseFeeSerializer from .ClawbackDetailSerializer import ClawbackDetailSerializer from .FileHandlerSerializer import FileHandlerSerializer from .HireAgreementSerializer import HireAgreementSerializer from .HireDetailSerializer import HireDetailSerializer from .HireValidationSerializer import HireValidationSerializer from .PIDetailSerializer import PIDetailSerializer from .RecoveryDetailSerializer import RecoveryDetailSerializer from .StorageDetailSerializer import StorageDetailSerializer class CaseDetailSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): client = ClientSerializer(allow_null=True, required=False) third_party = ThirdPartySerializer(allow_null=True, required=False) accident = AccidentSerializer(allow_null=True, required=False) hire_detail = HireDetailSerializer(allow_null=True, required=False) hire_validation = HireValidationSerializer(allow_null=True, required=False) hire_agreement = HireAgreementSerializer(required=False, allow_null=True) storage_detail = StorageDetailSerializer(allow_null=True, required=False) pi_detail = PIDetailSerializer(allow_null=True, required=False) recovery_detail = RecoveryDetailSerializer(allow_null=True, required=False) clawback_detail = ClawbackDetailSerializer(allow_null=True, required=False) provider = ProviderSerializer(allow_null=True, required=False) case_fee = CaseFeeSerializer(allow_null=True, required=False) repair_invoice = RepairInvoiceSerializer(allow_null=True, required=False) case_creator = CaseCreatorSerializer(allow_null=True, required=True) file_handler = FileHandlerSerializer(allow_null=True, required=True) case_price = serializers.ReadOnlyField(source="case_value", read_only=True) case_selections = serializers.SerializerMethodField(read_only=True) class Meta: model = Case fields = ( 'id', 'case_price', 'case_selections', 'services', 'service_providers', 'cc_ref', 'case_creator', 'file_handler', 'instruction_date', 'client', 'accident', 'third_party', 'solicitor', 'payment_status', 'solicitor_ref', 'provider', 'retained_date', 'introducer', 'introducer_fee', 'hire_detail', 'hire_validation', 'hire_agreement', 'storage_detail', 'pi_detail', 'recovery_detail', 'clawback_detail', 'status', 'status_description', 'case_fee', 'case_source', 'repair_invoice', 'recovery_agent' ) def get_case_selections(self, obj): hire_detail = False vd_repairable = False if obj.hire_detail.vehicle is not None or obj.hire_detail.start_date is not None or obj.hire_detail.end_date is not None: hire_detail = True if obj.hire_validation.repairable: vd_repairable = True data = { 'hire_detail': hire_detail, 'vd_repairable': vd_repairable } return data
import React from 'react'; import { useSearchParams } from 'react-router-dom'; import ContactList from '../components/ContactList'; import SearchBar from '../components/SearchBar'; // import { deleteContact } from '../utils/data'; import { getContacts, deleteContact } from '../utils/api'; //? get contact by id login function HomePageWrapper() { const [searchParams, setSearchParams] = useSearchParams(); const keyword = searchParams.get('keyword'); function changeSearchParams(keyword) { setSearchParams({ keyword }); } return <HomePage defaultKeyword={keyword} keywordChange={changeSearchParams} /> } class HomePage extends React.Component { constructor(props) { super(props); this.state = { contacts: [], keyword: props.defaultKeyword || '', //? isnull } this.onDeleteHandler = this.onDeleteHandler.bind(this); this.onKeywordChangeHandler = this.onKeywordChangeHandler.bind(this); //? bind onEvent } //? lifecycle componentDidMount async componentDidMount() { const { data } = await getContacts(); this.setState(() => { return { contacts: data } }) } // onDeleteHandler(id) { // deleteContact(id); // // update the contact state from data.js // this.setState(() => { // return { // contacts: getContacts(), // } // }); // } async onDeleteHandler(id) { await deleteContact(id); // update the contact state from data.js const { data } = await getContacts(); this.setState(() => { return { contacts: data, } }); } onKeywordChangeHandler(keyword) { this.setState(() => { return { keyword, } }); //? menyelaraskan nilai keyword yang berada di Search Bar dengan URL this.props.keywordChange(keyword); } render() { //? add condition by data state.contacts const contacts = this.state.contacts.filter((contact) => { return contact.name.toLowerCase().includes( this.state.keyword.toLowerCase() ); }); return ( <section> {/* //? call component searchBar */} <SearchBar keyword={this.state.keyword} keywordChange={this.onKeywordChangeHandler} /> <h2>Daftar Kontak</h2> <ContactList contacts={contacts} onDelete={this.onDeleteHandler} /> </section> ) } } export default HomePageWrapper;
let apiRoot = "/@ralphwetzel/systeminformation"; let API = require("./api.js"); let si = require("systeminformation"); module.exports = function(RED) { function si_node(config) { RED.nodes.createNode(this,config); let node = this; let poll_timer; node.processing = 0; let _lookup = {}; Object.keys(API).forEach( (g) => { Object.keys(API[g]).forEach ( (f) => { _lookup[f] = g; }) }) let run_si = function(func, params, msg, send, done, changed_cb) { let g = _lookup[func]; if (!g) return; let api = API?.[g]?.[func]; msg.topic = func; // prepare the params for the function call let _params = []; let error = false; Object.keys(api.params ?? []).forEach( (p) => { if (params[p]) { try { _params.push(RED.util.evaluateNodeProperty(params[p], api.params[p].type, node)); } catch { node.error(`Failed to parse '${params[p]}' to type '${api.params[p].type}'.`); error = true; } } else { _params.push(api.params[p].default ?? ""); } }); if (error) return; let run; let timer; node.processing += 1; if (api.sync) { // only 'version' or 'time' are called sync run = new Promise( resolve => { resolve(si[func]()) }); } else { // the rest is async run = si[func](..._params); timer = setTimeout(function() { node.status({ fill: "blue", shape: (node.processing) % 2 ? "dot" : "ring", text: `processing${node.processing > 1 ? `: ${node.processing}` : "..."}` }); }, 250); } run.then( data => { if (changed_cb && typeof(changed_cb) == "function") { if (false == changed_cb(data)) { if (done) done(); return; }; } msg.payload = data; if (send) { send(msg); } else { node.send.apply(node, [msg]); } if (done) done(); }).catch( (err) => { // Hmmm.... }).finally(() => { clearTimeout(timer); node.processing -= 1; if (node.processing > 0) { node.status({ fill: "blue", shape: (node.processing) % 2 ? "dot" : "ring", text: `processing${node.processing > 1 ? `: ${node.processing}` : "..."}` }); } else { node.status({}); } }); }; node.on('input', function(msg, send, done) { if (msg.topic && _lookup[msg.topic]) { return run_si(msg.topic, ("object" !== typeof msg.payload) ? {} : msg.payload, msg, send, done); } return run_si(config.func, config.params, msg, send, done); }); node.on('close', function(done) { if (poll_timer) { clearInterval(poll_timer); } done(); }); let error = isNaN(config.interval); let interval = RED.util.evaluateNodeProperty(config.interval, "num"); if (!error) { error = (interval <= 0) } if (error) { node.warn(`Unsupported value '${config.interval}' to define observation interval; observer launched with 5s polling interval.`); interval = 5; }; // Not using the built-in observer functionality here!! if (config.poll && !API?.[config.group]?.[config.func].dont_poll) { if (config.onchangeonly) { // used by check_changed to store the result of the last call let _data = JSON.stringify({}); let check_changed = function(data) { let d = JSON.stringify(data); let res = (d !== _data); _data = d; return res; } poll_timer = setInterval( function() { let msg = { topic: config.func } return run_si(config.func, config.params, msg, undefined, undefined, check_changed); }, interval * 1000); } else { poll_timer = setInterval( function() { let msg = { topic: config.func } return run_si(config.func, config.params, msg); }, interval * 1000); } } } RED.nodes.registerType("systeminformation", si_node); RED.httpAdmin.get(`${apiRoot}/api`, (req, res) => { res.status(200).send(API); }) }
package com.myEdu.ws.service; import com.myEdu.ws.model.*; import com.myEdu.ws.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CourseProgramOutcomeResultsService { @Autowired private ProgramOutcomeRepository programOutcomeRepository; @Autowired private ProgramOutcomeCalculationService programOutcomeCalculationService; @Autowired private CourseRepository courseRepository; @Autowired private LearningOutcomeProgramOutcomeRepository learningOutcomeProgramOutcomeRepository; @Autowired private CourseProgramOutcomeResultsRepository courseProgramOutcomeResultsRepository; public ResponseEntity<String> createCourseProgramOutcomeResults(Course course) { calculateAndSetProgramOutcomeTarget(course); return new ResponseEntity<>("Başarıyla oluşturuldu", HttpStatus.CREATED); } public void calculateAndSetProgramOutcomeTarget(Course course) { Department department = course.getDepartment(); Long id = department.getId(); List<ProgramOutcome> programOutcomes = programOutcomeRepository.findByDepartmentId(id); for (ProgramOutcome programOutcome : programOutcomes) { Optional<CourseProgramOutcomeResults> optionalResults = courseProgramOutcomeResultsRepository.findByCourseAndProgramOutcome(course, programOutcome); CourseProgramOutcomeResults courseProgramOutcomeResults; if (optionalResults.isPresent()) { courseProgramOutcomeResults = optionalResults.get(); } else { courseProgramOutcomeResults = new CourseProgramOutcomeResults(); courseProgramOutcomeResults.setCourse(course); courseProgramOutcomeResults.setProgramOutcome(programOutcome); } double target = programOutcomeCalculationService.calculateProgramOutcomeTarget(programOutcome); courseProgramOutcomeResults.setTarget(target); calculateAndSetAssessmentValueForProgramOutcome(courseProgramOutcomeResults, programOutcome); } } public void calculateAndSetAssessmentValueForProgramOutcome(CourseProgramOutcomeResults courseProgramOutcomeResults, ProgramOutcome programOutcome) { List<LearningOutcomeProgramOutcome> mappings = learningOutcomeProgramOutcomeRepository.findByProgramOutcome(programOutcome); double assessmentValue = 0.0; for (LearningOutcomeProgramOutcome mapping : mappings) { LearningOutcome learningOutcome = mapping.getLearningOutcome(); double contribution = mapping.getContribution(); double learningOutcomeAssessmentSum = learningOutcome.getAssessmentSum(); double valueToAdd = (learningOutcomeAssessmentSum * contribution) / 100; assessmentValue += valueToAdd; } courseProgramOutcomeResults.setAssessmentValue(assessmentValue); calculateAndSetScoreAndLevelOfProvisionForProgramOutcome(courseProgramOutcomeResults, programOutcome, assessmentValue); } public void calculateAndSetScoreAndLevelOfProvisionForProgramOutcome(CourseProgramOutcomeResults courseProgramOutcomeResults, ProgramOutcome programOutcome, double assessmentValue) { List<LearningOutcomeProgramOutcome> mappings = learningOutcomeProgramOutcomeRepository.findByProgramOutcome(programOutcome); double score = 0.0; for (LearningOutcomeProgramOutcome mapping : mappings) { LearningOutcome learningOutcome = mapping.getLearningOutcome(); double contribution = mapping.getContribution(); double learningOutcomeScoreSum = learningOutcome.getScoreSum(); double valueToAdd = (learningOutcomeScoreSum * contribution) / 100; score += valueToAdd; } double levelOfProvision = score / assessmentValue * 100; courseProgramOutcomeResults.setLevelOfProvision(levelOfProvision); courseProgramOutcomeResults.setScore(score); courseProgramOutcomeResultsRepository.save(courseProgramOutcomeResults); } public List<CourseProgramOutcomeResults> getCourseProgramOutcomeResultsByCourse(Long courseId) { return courseProgramOutcomeResultsRepository.findByCourseCourseId(courseId); } }
<?php namespace App\Models; use App\Models\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Factories\HasFactory; class Video extends Model { use HasFactory, SoftDeletes; protected $fillable = [ 'url', 'title', 'user_id' ]; public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); } public function user(): BelongsTo { return $this->belongsTo(User::class); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using fitness_app_back.Data; using fitness_app_back.Entities; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace fitness_app_back { public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }) .Build(); using var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; try { var context = services.GetRequiredService<DataContext>(); //Sets the services var userManager = services.GetRequiredService<UserManager<AppUser>>(); var roleManager = services.GetRequiredService<RoleManager<AppRole>>(); var mapper = services.GetRequiredService<IMapper>(); await context.Database.MigrateAsync(); //applies the migrations to the database if((await context.Packs.ToListAsync()).Count() == 0) { await Seed.SeedRoles(roleManager); //seeds initial data to the db await Seed.SeedPacks(context); //Seeds some packs await Seed.SeedUsers(userManager,mapper); //Seeds users await Seed.SeedPlans(context); //Seed workoutplans and diet plans await Seed.SeedVideoCourses(context,mapper); //Seed video Courses await Seed.SeedPerks(context,mapper); //Seed Perks await Seed.SeedVideos(context); //Seed Videos } } catch (System.Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); //Sets up the logger logger.LogError(ex,"An error occured during migration"); //logs the error } await host.RunAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
import { ReactElement, Ref, useCallback, useEffect, useRef, useState } from 'react'; import SelectComponent, { MultiValue, SingleValue, createFilter, } from 'react-select'; export type OptionType = { value: string | number; label: string | ReactElement; }; type SelectPropsType = { fieldName?: string; label?: string; isLoading?: boolean; placeholder?: string; options: OptionType[]; initialValue?: string | number; className?: string; handleChange?: (value: string | number) => void; }; export const Select: React.FC<SelectPropsType> = ({ label, options, isLoading, placeholder, initialValue, fieldName = '1', className, handleChange, ...props }) => { const [values, setValues] = useState<string | number | null>(null); const [isFocus, setFocus] = useState(false); const inputRef = useRef<any>(null); //add initailValue useEffect(() => { if (initialValue === undefined) return; setValues(initialValue); }, [initialValue]); //find selected value const selectedValue = useCallback(() => { if (values || values === 0) return options.find((i) => i.value === values); else return ''; }, [values, options])(); const changeHandler = ( newValue: MultiValue<string | OptionType> | SingleValue<string | OptionType> ) => { setValues((newValue as OptionType).value); handleChange((newValue as OptionType).value); }; const containerHandler = () => { inputRef.current?.focus(); setFocus(true); }; const inputBlurHandler = () => setFocus(false); return ( <div className={className}> <p className="text_body">{label}</p> <div onClick={containerHandler} className={`w-[100%] h-[52px] rounded-[15px] flex items-center justify-center mt-[8px] rounded-[15px] ${ isFocus || values ? 'bg-gradient-to-r from-[rgba(139,228,217,0.6)] via-[rgba(200,184,128,0.6)] to-[rgba(255,144,47,0.5)]' : 'input_default_border hover:bg-gradient-to-r hover:from-[rgba(139,228,217,0.6)] hover:via-[rgba(200,184,128,0.6)] hover:to-[rgba(255,144,47,0.5)]' }`} > <div className={`w-[calc(100%-2px)] h-[50px] rounded-[15px] bg-brown ${ values ? 'input_typing_bg' : 'bg-brown' }`} > <SelectComponent ref={inputRef} classNamePrefix="custom_select" onChange={changeHandler} hideSelectedOptions={false} value={selectedValue} options={options} id={`long-value-select ${fieldName}`} instanceId={`long-value-select ${fieldName}`} isLoading={isLoading} placeholder=" " onBlur={inputBlurHandler} filterOption={createFilter({ matchFrom: 'start', })} {...props} /> </div> </div> </div> ); };
using System; using System.Runtime.CompilerServices; using TerraFX.Interop.DirectX; using Voltium.Core.Devices; using Voltium.Common; using ResourceType = Voltium.Core.Devices.ResourceType; using SysDebug = System.Diagnostics.Debug; namespace Voltium.Core.Memory { public unsafe sealed class GraphicsAllocator : ComputeAllocator { private GraphicsDevice _device; /// <summary> /// Creates a new allocator /// </summary> /// <param name="device">The <see cref="ID3D12Device"/> to allocate on</param> internal GraphicsAllocator(GraphicsDevice device) : base(device) { SysDebug.Assert(device is not null); _device = device; _hasMergedHeapSupport = device.Info.MergedHeapSupport; _4kbTextures = new(); _64kbTextures = new(); _4mbTextures = new(); if (!_hasMergedHeapSupport) { _64kbRtOrDs = new(); _4mbRtOrDs = new(); } _accelerationStructureHeap = new(); } /// <summary> /// Allocates a buffer for use as a raytracing acceleration structure /// </summary> /// <param name="info">The <see cref="AccelerationStructureBuildInfo"/> containing the required sizes of the buffers</param> /// <param name="scratch">On return, this is filled with a <see cref="Buffer"/> with a large anough size to be used as the scratch buffer in a raytracing acceleration structure build</param> /// <returns>A <see cref="RaytracingAccelerationStructure"/> with a large anough size to be used as the destination in a raytracing acceleration structure build</returns> public RaytracingAccelerationStructure AllocateRaytracingAccelerationBuffer(in AccelerationStructureBuildInfo info, out Buffer scratch) => AllocateRaytracingAccelerationBuffer(info, AllocFlags.None, out scratch); /// <summary> /// Allocates a buffer for use as a raytracing acceleration structure /// </summary> /// <param name="info">The <see cref="AccelerationStructureBuildInfo"/> containing the required sizes of the buffers</param> /// <param name="scratch">On return, this is filled with a <see cref="Buffer"/> with a large anough size to be used as the scratch buffer in a raytracing acceleration structure build</param> /// <param name="allocFlags">Any additional allocation flags</param> /// <returns>A <see cref="RaytracingAccelerationStructure"/> with a large anough size to be used as the destination in a raytracing acceleration structure build</returns> public RaytracingAccelerationStructure AllocateRaytracingAccelerationBuffer(in AccelerationStructureBuildInfo info, AllocFlags allocFlags, out Buffer scratch) { scratch = AllocateBuffer(info.ScratchSize, MemoryAccess.GpuOnly, ResourceFlags.AllowUnorderedAccess | ResourceFlags.DenyShaderResource, allocFlags); return AllocateRaytracingAccelerationBuffer(info.DestSize, allocFlags); } /// <summary> /// Allocates a buffer for use as a raytracing acceleration structure or scratch buffer for a raytracing acceleration structure build /// </summary> /// <param name="length">The length, in bytes, to allocate</param> /// <param name="allocFlags">Any additional allocation flags</param> /// <returns>A <see cref="RaytracingAccelerationStructure"/></returns> public RaytracingAccelerationStructure AllocateRaytracingAccelerationBuffer(ulong length, AllocFlags allocFlags = AllocFlags.None) { InternalAllocDesc allocDesc = default; CreateAllocDesc( length, &allocDesc, allocFlags ); if (TryGetFreeBlock(&allocDesc, out var heap, out var index, out var offset)) { var info = new AllocationInfo { HeapIndex = index, HeapInfo = heap.Info, Length = allocDesc.Size, Alignment = allocDesc.Alignment, Offset = offset }; var buffer = _device.AllocateRaytracingAccelerationStructure(length, heap, offset, new(this, &_Return)); SetAllocationInfo(buffer.Handle, info); return buffer; } else { return _device.AllocateRaytracingAccelerationStructure(length); } } /// <summary> /// Allocates a texture /// </summary> /// <param name="alias">The buffer to alias</param> /// <param name="desc">The <see cref="TextureDesc"/> describing the texture</param> /// <param name="initialResourceState">The state of the resource when it is allocated</param> /// <param name="allocFlags">Any additional allocation flags</param> /// <returns>A new <see cref="Texture"/></returns> public Texture AllocateTextureAliasing( in Buffer alias, in TextureDesc desc, ResourceState initialResourceState, AllocFlags allocFlags = AllocFlags.None ) { var info = GetAllocationInfo(alias.Handle); if (info.HasImplicitHeap) { ThrowHelper.ThrowArgumentException("Cannot alias with a committed resource"); } var heap = GetHeapPool(info.HeapInfo)[(int)info.HeapIndex].Heap; return _device.AllocateTexture(desc, initialResourceState, heap, info.Offset); } /// <summary> /// Allocates a texture /// </summary> /// <param name="alias">The texture to alias</param> /// <param name="desc">The <see cref="TextureDesc"/> describing the texture</param> /// <param name="initialResourceState">The state of the resource when it is allocated</param> /// <param name="allocFlags">Any additional allocation flags</param> /// <returns>A new <see cref="Texture"/></returns> public Texture AllocateTextureAliasing( in Texture alias, in TextureDesc desc, ResourceState initialResourceState, AllocFlags allocFlags = AllocFlags.None ) { var info = GetAllocationInfo(alias.Handle); if (info.HasImplicitHeap) { ThrowHelper.ThrowArgumentException("Cannot alias with a committed resource"); } var heap = GetHeapPool(info.HeapInfo)[(int)info.HeapIndex].Heap; return _device.AllocateTexture(desc, initialResourceState, heap, info.Offset); } /// <summary> /// Allocates a texture /// </summary> /// <param name="desc">The <see cref="TextureDesc"/> describing the texture</param> /// <param name="initialResourceState">The state of the resource when it is allocated</param> /// <param name="allocFlags">Any additional allocation flags</param> /// <returns>A new <see cref="Texture"/></returns> public Texture AllocateTexture( in TextureDesc desc, ResourceState initialResourceState, AllocFlags allocFlags = AllocFlags.None ) { InternalAllocDesc allocDesc = default; CreateAllocDesc(desc, &allocDesc, initialResourceState, allocFlags); if (TryGetFreeBlock(&allocDesc, out var heap, out var index, out var offset)) { var info = new AllocationInfo { HeapIndex = index, HeapInfo = heap.Info, Length = allocDesc.Size, Alignment = allocDesc.Alignment, Offset = offset }; var tex = _device.AllocateTexture(desc, initialResourceState, heap, offset, new(this, &_Return)); SetAllocationInfo(tex.Handle, info); return tex; } else { return _device.AllocateTexture(desc, initialResourceState); } } internal void CreateAllocDesc( in TextureDesc desc, InternalAllocDesc* pDesc, ResourceState initialResourceState, AllocFlags allocFlags ) { var (alignment, size) = _device.GetAllocationInfo(desc); var heapInfo = new HeapInfo { Alignment = (Alignment)alignment, Access = MemoryAccess.GpuOnly, Type = IsRenderTargetOrDepthStencil(desc.ResourceFlags) ? ResourceType.RenderTargetOrDepthStencilTexture : ResourceType.Texture }; *pDesc = new InternalAllocDesc { Desc = new (desc), InitialState = initialResourceState, AllocFlags = allocFlags, Alignment = alignment, Size = size, HeapInfo = heapInfo, Flags = desc.ResourceFlags }; } } }
const mongoose = require("mongoose"); mongoose .connect("mongodb://localhost/playground") .then(() => console.log("Connected to MongoDB...")) .catch((err) => console.error("Could not connect to MongoDB...", err)); const authorSchema = new mongoose.Schema({ name: String, bio: String, website: String, }); const courseSchema = new mongoose.Schema({ name: String, authors: [authorSchema], }); const Course = mongoose.model("Course", courseSchema); const Author = mongoose.model("Author", authorSchema); async function createCourse(name, authors) { const course = new Course({ name, authors, }); const result = await course.save(); console.log(result); } async function listCourses() { const courses = await Course.find(); console.log(courses); } // createCourse("Node Course", [ // new Author({ name: "Mosh" }), // new Author({ name: "John" }), // ]); // async function updateAuthor(courseId) { // const course = await Course.findByIdAndUpdate(courseId, { // $unset: { // author: "", // }, // }); // } // updateAuthor("62ed09a1ecb06bca0e5dabaf"); async function addAuthor(courseId, author) { const course = await Course.findById(courseId); course.authors.push(author); course.save(); } // addAuthor("62ed0fed4e3c550e75406815", new Author({ name: "Emily Smith" })); async function removeAuthor(courseId, authorId) { const course = await Course.findById(courseId); const author = course.authors.id(authorId); author.remove(); course.save(); } removeAuthor("62ed0fed4e3c550e75406815", "62ed11cd647da489e792e52c");
package dev.shulika.podologia.service.impl; import dev.shulika.podologia.dto.specialist.SpecialistRequestDTO; import dev.shulika.podologia.dto.specialist.SpecialistResponseDTO; import dev.shulika.podologia.exception.ObjectNotFoundException; import dev.shulika.podologia.exception.ServiceBusinessException; import dev.shulika.podologia.model.Specialist; import dev.shulika.podologia.repository.SpecialistRepository; import dev.shulika.podologia.service.SpecialistService; import dev.shulika.podologia.util.SpecialistMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; @Service @Transactional @RequiredArgsConstructor @Slf4j public class SpecialistServiceImpl implements SpecialistService { private final SpecialistRepository specialistRepository; @Override public Page<SpecialistResponseDTO> findAll(Pageable pageable) { log.info("IN SpecialistServiceImpl - findAll - STARTED"); Page<Specialist> specialistPages = specialistRepository.findAll(pageable); log.info("IN SpecialistServiceImpl - findAll - FINISHED SUCCESSFULLY - SpecialistMapper::toDTO NOW"); return specialistPages.map(SpecialistMapper::toDTO); } @Override public SpecialistResponseDTO findById(Long id) { log.info("IN SpecialistServiceImpl - findById: {} - STARTED", id); Specialist specialist = specialistRepository.findById(id) .orElseThrow(() -> new ObjectNotFoundException(id.toString(), "Specialist not found with id: " + id)); log.info("IN SpecialistServiceImpl - findById: {} - FINISHED SUCCESSFULLY - SpecialistMapper.toDTO NOW", id); return SpecialistMapper.toDTO(specialist); } @Override public SpecialistResponseDTO create(SpecialistRequestDTO specialistRequestDTO) { log.info("IN SpecialistServiceImpl - create - STARTED"); if (specialistRepository.existsByName(specialistRequestDTO.getName())) throw new ServiceBusinessException(specialistRequestDTO.getName(), "A specialist with this name already exists"); Specialist specialistReturned = specialistRepository.save(SpecialistMapper.fromDTO(specialistRequestDTO)); log.info("IN SpecialistServiceImpl - created - FINISHED SUCCESSFULLY"); return SpecialistMapper.toDTO(specialistReturned); } @Override public SpecialistResponseDTO update(Long id, SpecialistRequestDTO specialistRequestDTO) { log.info("IN SpecialistServiceImpl - update specialist by id: {} - STARTED", id); Optional<Specialist> existingSpecialist = specialistRepository.findById(id); if (!existingSpecialist.isPresent()) throw new ObjectNotFoundException(id.toString(), "Specialist not found with id: " + id); Specialist specialist = existingSpecialist.get(); specialist.setName(specialistRequestDTO.getName()); specialist.setDescription(specialistRequestDTO.getDescription()); specialist.setEnabled(specialistRequestDTO.getEnabled()); Specialist specialistReturned = specialistRepository.save(specialist); log.info("IN SpecialistServiceImpl - update specialist by id: {} - FINISHED SUCCESSFULLY", id); return SpecialistMapper.toDTO(specialistReturned); } @Override public SpecialistResponseDTO updateSpecialistFields(Long id, Map<String, Object> fields) { log.info("IN SpecialistServiceImpl - updateSpecialistFields: STARTED"); Optional<Specialist> existingSpecialist = specialistRepository.findById(id); if (!existingSpecialist.isPresent()) { throw new ObjectNotFoundException(id.toString(), "Specialist not found with id: " + id); } fields.forEach((key, value) -> { Field field = ReflectionUtils.findField(Specialist.class, key); field.setAccessible(true); ReflectionUtils.setField(field, existingSpecialist.get(), value); }); Specialist specialistReturned = specialistRepository.save(existingSpecialist.get()); log.info("IN SpecialistServiceImpl - updateSpecialistFields - FINISHED SUCCESSFULLY"); return SpecialistMapper.toDTO(specialistReturned); } @Override public void delete(Long id) { log.info("IN SpecialistServiceImpl - delete by id: {} - STARTED", id); if (!specialistRepository.existsById(id)) throw new ObjectNotFoundException(id.toString(), "Specialist not found with id: " + id); specialistRepository.deleteById(id); log.info("IN SpecialistServiceImpl - delete by id: {} - FINISHED SUCCESSFULLY", id); } }
describe('Comandos con Cypress checkbox y radio', () => { beforeEach('Funcionamiento de comandos para checkbox y radio', () => { cy.visit('https://example.cypress.io/commands/actions'); }); it('Solo selecciona los checkbox y radio que no estan agrupadoss', () => { cy.log('verificación coincidentes o elementos de radio en sucesión'); cy.get('.action-checkboxes [type="checkbox"]').not('[disabled]').check(); cy.get('.action-checkboxes [type="checkbox"]').not('[disabled]').should('be.checked'); cy.log('Valida que se puedan checkear y selecciona los dos radio pero solo uno puede estar checkeado'); cy.get('.action-radios [type="radio"]').not('[disabled]').check(); cy.get('.action-radios [type="radio"]').not('[disabled]').should('be.checked'); }); it('selecciona los checkbox que tengan el valor checkbox1 y checkbox2 que estan en el array', () => { cy.get('.action-multiple-checkboxes [type="checkbox"]').check(['checkbox1', 'checkbox2']); cy.get('.action-multiple-checkboxes [type="checkbox"]').should('be.checked'); }); it('selecciona los checkbox y radio que no se puedan seleccionar',()=>{ cy.get('.action-checkboxes [disabled]').check({ force: true }); cy.get('.action-checkboxes [disabled]').should('be.checked'); cy.get('.action-radios [type="radio"]').check('radio3', { force: true }); cy.get('.action-radios [type="radio"]').should('be.checked'); }); }); describe('Comandos con Cypress Select',()=>{ beforeEach('Funcionamiento de comandos para Select', () => { cy.visit('https://example.cypress.io/commands/actions'); cy.wait(1000); }); it('Valida el valor de la primera opcion',()=>{ cy.get('.action-select').should('have.value', '--Select a fruit--'); }); it('Selecciona la opcion que hace match',()=>{ cy.get('.action-select').select('apples'); cy.log('confirma seleccion de apples'); cy.get('.action-select').should('have.value', 'fr-apples'); }); it('Seleccion multiple opciones',()=>{ cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas']); cy.log('al obtener multiples valores seleccionados los compara usando chai'); cy.get('.action-select-multiple').invoke('val').should('deep.equal', ['fr-apples', 'fr-oranges', 'fr-bananas']); }); }); describe('Para obtener un elemento DOM en un índice específico',()=>{ it('como usar el comando .eq() para multiples elementos con el mismo id',()=>{ cy.visit('https://example.cypress.io/commands/traversal'); cy.get('.traversal-list>li').eq(1).should('contain', 'siamese'); }); });
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, sort_child_properties_last, non_constant_identifier_names, must_be_immutable, use_key_in_widget_constructors, avoid_unnecessary_containers, avoid_print, unnecessary_null_comparison import 'package:blogapp/services/crud.dart'; import 'package:blogapp/views/uploadblog/blogbook.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:cached_network_image/cached_network_image.dart'; class UserBlogs extends StatefulWidget { const UserBlogs({super.key}); @override State<UserBlogs> createState() => _UserBlogsState(); } class _UserBlogsState extends State<UserBlogs> { // ignore: unnecessary_new CrudMethod crudMethod = new CrudMethod(); Stream<QuerySnapshot>? blogStream = FirebaseFirestore.instance.collection('dets').snapshots(); Widget UserBlogList() { if (blogStream == null) { return Container( child: Center( child: CircularProgressIndicator(), ), ); } else { return Column( children: [ StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('dets').where('UserId', isEqualTo: crudMethod.getuid().toString()).snapshots(), builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) { return Expanded( child: ListView.builder( physics: AlwaysScrollableScrollPhysics(), shrinkWrap: true, itemCount: snapshot.data?.docs.length ?? 0, itemBuilder: (context, index) { var data = snapshot.data?.docs[index].data() as Map<String, dynamic>; return UserBlogTile( imgUrl: data['imgUrl'], title: data['title'], desc: data['desc'], authorName: data['authorName'], ); }, ), ); }), ], ); } } @override void initState() { super.initState(); crudMethod.getUserData().then((result) { blogStream = result; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: GestureDetector( onTap: () { Get.offAll(BlogBook()); }, child: Icon(Icons.navigate_before), ), automaticallyImplyLeading: false, title: Text("UserBlog"), centerTitle: true, ), body: UserBlogList(), ); } } class UserBlogTile extends StatelessWidget { String? authorName, title, desc, imgUrl; UserBlogTile({this.imgUrl, this.title, this.desc, this.authorName}); @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.all(Radius.circular(50)), child: Container( margin: EdgeInsets.all(10), height: 300, color: Color.fromARGB(131, 128, 128, 128), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.all(10.0), child: ClipRRect( borderRadius: BorderRadius.circular(12), child: CachedNetworkImage( imageUrl: '$imgUrl', height: 200, width: double.infinity, fit: BoxFit.cover, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 0.0), child: Column( children: [ Row( children: [ Row( children: [ Text("Author Name:- $authorName"), ], ), ], ), Row( children: [ Text("Title:-$title"), ], ), Row(children: [ Expanded( child: Text( "Description:-$desc", overflow: TextOverflow.ellipsis, ), ), ]), SizedBox( height: 20, ), ], ), ), ], )), ); } }
#! /usr/bin/perl use strict; use warnings; use DBD::Mock; use DBI; use File::Temp qw/ tempfile /; use File::Basename qw/ dirname /; use File::Spec; use Test::RedisServer; use Test::Spec; use Redis; use Resque; use Honeydew::Config; use Honeydew::Queue::Nightly; describe 'Nightly' => sub { my ($nightly, $dbh, $config); $dbh = DBI->connect( 'DBI:Mock:', '', '' ) || die "Cannot create handle: $DBI::errstr\n"; my ($fh, $filename) = tempfile(); print $fh qq/[header]\nkey=value/; close ($fh); before each => sub { $config = Honeydew::Config->instance( file => $filename ); $config->{honeydew}->{basedir} = File::Spec->catfile( dirname(__FILE__), 'fixture' ); $nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config ); }; describe 'sets' => sub { it 'should query the monitor table for expected sets' => sub { mock_expected_sets( $dbh ); my $expected_sets = $nightly->expected_sets; is( $expected_sets->[0], 'fake.set fake_host fake_browser' ); is( $expected_sets->[1], 'other_fake.set other_fake_host other_fake_browser' ); }; describe 'all-runner' => sub { it 'should not query the setRun table when running all' => sub { my $run_all_nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config, run_all => 1 ); is_deeply( $run_all_nightly->actual_sets, {} ); }; it 'should determine run all on its own' => sub { @ARGV = qw/ execute all /; my $run_all_nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config ); ok( $run_all_nightly->run_all ); }; after each => sub { @ARGV = () }; }; it 'should query the setRun table for existing sets' => sub { mock_actual_sets( $dbh ); my $actual_sets = $nightly->actual_sets; is_deeply( $actual_sets, { 1 => 'fake.set fake_host fake_browser' }); }; it 'should get a proper list of the sets to be queued' => sub { mock_expected_sets( $dbh ); mock_actual_sets( $dbh ); my $missing_sets = $nightly->sets_to_run; is( $missing_sets->[0], 'other_fake.set other_fake_host other_fake_browser' ); }; describe 'commands' => sub { my $command_nightly; before each => sub { my $sets_to_run = [ 'fake.set fake_host fake_browser', 'fake2.set fake2_host AB fake_browser Local', 'invalid.set invalid_host invalid_browser' ]; my $all_expected_features = { 'fake.set' => [ 'fake.feature' ], 'fake2.set' => [ 'fake.feature' ] }; my $config = { local => { AB => '1.2.3.4' } }; $command_nightly = Honeydew::Queue::Nightly->new( sets_to_run => $sets_to_run, all_expected_features => $all_expected_features, config => $config ); }; it 'should get a validated list of set commands to run' => sub { my $cmds = $command_nightly->set_commands_to_run; like($cmds->[0], qr/browser=fake_browser \(set\)\^host=fake_host\^setName=fake.set\^setRunId=.*?\^user=croneyDew/); }; it 'should include the local address if applicable' => sub { my $cmds = $command_nightly->set_commands_to_run; like($cmds->[1], qr/\^local=1\.2\.3\.4/); }; it 'should only include sets with features' => sub { my $cmds = $command_nightly->set_commands_to_run; # There are 3 sets to run, but only 2 in features to # run, so we should be dropping the invalid one. is( scalar @$cmds, 2 ); }; }; describe 'convenience fns' => sub { it 'should count which needles can be found in a haystack ' => sub { my $haystack = [ qw/a b c d e/ ]; my $needle = [ qw/a c e/ ]; my $counted_sets = Honeydew::Queue::Nightly::_set_count( $haystack, $needle ); is_deeply($counted_sets, { a => 1, b => 0, c => 1, d => 0, e => 1 }); }; it 'should return the missing needles from a haystack' => sub { my $haystack = { a => 1, b => 0, c => 1, d => 0 }; my $missing = Honeydew::Queue::Nightly::_get_missing( $haystack ); is_deeply( $missing, [ qw/b d/ ] ); }; }; }; describe 'features' => sub { it 'should get features from a list of set files' => sub { my $nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config, sets_to_run => [ 'fixture.set', 'empty_fixture.set', 'not_a_file.set' ] ); my $expected_features = $nightly->all_expected_features; is_deeply( $expected_features->{'empty_fixture.set'}, [] ); is_deeply( $expected_features->{'not_a_file.set'}, [] ); is_deeply( $expected_features->{'fixture.set'}, [ 'fake.feature' ] ); }; it 'should query the database for actually executed features' => sub { my $nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config, actual_sets => { 1 => 'actual.set' } ); mock_actual_features( $dbh ); my $actual_features = $nightly->actual_features; is_deeply( $actual_features, { 'actual.set' => [ 'executed.feature' ] } ); }; it 'should figure out which features are missing' => sub { my $nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, config => $config, all_expected_features => { 'fake.set' => [ 'executed.feature', 'missing.feature' ] }, actual_sets => { 1 => 'fake.set Localhost Chrome' } ); mock_actual_sets( $dbh ); mock_actual_features( $dbh ); my $features_to_run = $nightly->feature_run_status; is_deeply( $features_to_run, { '1 fake.set Localhost Chrome' => { 'executed.feature' => 1, 'missing.feature' => 0 } }); }; it 'should produce a filtered list of filter commands ' => sub { my $nightly = Honeydew::Queue::Nightly->new( dbh => $dbh, # in config, the features_dir is set to # __DIR__/fixture/features. feature_commands_to_run # depends on this value config => $config, all_expected_features => { 'fake.set' => [ 'executed.feature', 'missing.feature' ] }, actual_sets => { 1 => 'fake.set Localhost Chrome' } ); mock_actual_sets( $dbh ); mock_actual_features( $dbh ); mock_set_run_ids( $dbh ); my $cmds = $nightly->feature_commands_to_run; # note that the executed.feature isn't in this list since # it's already included in the sub mock_actual_features() # below like( $cmds->[0], qr/browser=Chrome \(set\)\^feature=.*?t\/fixture\/features\/missing\.feature\^host=Localhost\^setName=fake.set\^setRunId=unique\^user=croneyDew/); is( scalar @$cmds, 1 ); }; }; describe 'enqueing' => sub { my ($nightly, $redis_server); before each => sub { mock_expected_sets( $dbh ); mock_actual_features( $dbh ); mock_set_run_ids( $dbh ); $config->{redis} = { redis_background_channel => 'test_channel' }; $config->{perl} = { libs => '' }; my %args = ( dbh => $dbh, config => $config, all_expected_features => { 'fake.set' => [ 'executed.feature', 'missing.feature', 'missing2.feature' ], 'other_fake2.set' => [ 'missing.feature', 'missing2.feature' ], }, actual_sets => { 1 => 'fake.set Localhost Chrome' }, execute => 1 ); $redis_server = get_redis_server(); if ($redis_server) { $args{resque} = Resque->new( redis => Redis->new( $redis_server->connect_info ) ); } $nightly = Honeydew::Queue::Nightly->new( %args ); }; it 'should consolidate all commands' => sub { my $cmds = $nightly->all_commands_to_run; foreach (@$cmds) { $_ =~ s/setRunId=.*\^/setRunId=unique^/; $_ =~ s{feature=.*(t/fixture/features/missing2?\.feature)}{feature=$1}; } my $expected_cmds = [ 'browser=fake_browser (set)^host=fake_host^setName=fake.set^setRunId=unique^user=croneyDew', 'browser=other_fake_browser (set)^host=other_fake_host^setName=other_fake2.set^setRunId=unique^user=croneyDew', 'browser=Chrome (set)^feature=t/fixture/features/missing.feature^host=Localhost^setName=fake.set^setRunId=unique^user=croneyDew', 'browser=Chrome (set)^feature=t/fixture/features/missing2.feature^host=Localhost^setName=fake.set^setRunId=unique^user=croneyDew' ]; is_deeply( $cmds, $expected_cmds ); }; it 'should enqueue the correct number of commands' => sub { SKIP: { skip 'No temporary resque server available', 1 unless $nightly->has_resque; # avoid hitting a real database, since this is tightly # coupled to Honeydew::Reports, which is not yet open # sourced. Honeydew::Queue::JobRunner->expects('create_set_report'); my $resque = $nightly->resque; $nightly->enqueue_all; # there are two features enqueued, and two sets # enqueued. only one of the sets has one actual # feature, so that gives three expected resque jobs in # all. is($resque->size('test_channel'), 3); } }; it 'should enqueue the correct commands' => sub { SKIP: { skip 'No temporary resque server available', 1 unless $nightly->has_resque; # avoid hitting a real database, since this is tightly # coupled to Honeydew::Reports, which is not yet open # sourced. Honeydew::Queue::JobRunner->expects('create_set_report'); my $resque = $nightly->resque; $nightly->enqueue_all; my @queued_jobs = $resque->peek('test_channel', 0, -1); my @queued_commands = map { $_->args->[0]->{cmd} } @queued_jobs; my @uniform_commands = sort map { $_ =~ s/setRunId=[^ ]*/setRunId=unique/; $_ =~ s{[^ =]*(t/fixture/[^ ]*)}{$1}g; $_ } @queued_commands; my @expected = [ 'perl t/fixture/bin/honeydew.pl -database -browser="Chrome (set)" -feature=t/fixture/features/missing.feature -host=Localhost -setName=fake.set -setRunId=unique -user=croneyDew', 'perl t/fixture/bin/honeydew.pl -database -browser="Chrome (set)" -feature=t/fixture/features/missing2.feature -host=Localhost -setName=fake.set -setRunId=unique -user=croneyDew', 'perl t/fixture/bin/honeydew.pl -database -browser="fake_browser (set)" -feature=t/fixture/features/missing.feature -host=fake_host -setName=t/fixture/sets/fake.set -setRunId=unique -user=croneyDew' ]; is_deeply( \@uniform_commands, @expected ); } }; after each => sub { delete $config->{redis}; }; }; }; sub mock_expected_sets { my ($dbh) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT `set` as setName,`host`,`browser` FROM monitor WHERE `on` = 1', results => [ [ 'setName' , 'host' , 'browser' ], [ 'fake.set' , 'fake_host' , 'fake_browser' ], [ 'other_fake.set' , 'other_fake_host' , 'other_fake_browser' ], [ 'other_fake2.set' , 'other_fake_host' , 'other_fake_browser' ], ] }; } sub mock_actual_sets { my ($dbh) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT id,setName,host,browser FROM setRun WHERE `userId` = 2 AND `startDate` >= now() - INTERVAL 12 HOUR;', results => [ [ 'id' , 'setName', 'host', 'browser' ], [ 1 , 'fake.set', 'fake_host', 'fake_browser' ] ] }; } sub mock_actual_features { my ($dbh) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT featureFile from report where setRunId = ?', results => [ [ 'featureFile' ], [ 'executed.feature' ] ] }; } sub mock_set_run_ids { my ($dbh) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT setRunUnique as setRunId from setRun where id = ?', results => [ [ 'setRunId' ], [ 'unique' ] ] }; } sub get_redis_server { my $redis_server; my $has_server = eval { $redis_server = Test::RedisServer->new; }; return $redis_server; } runtests;
package uz.uzkassa.smartpos.feature.category.list.domain import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.* import uz.uzkassa.smartpos.core.data.source.resource.category.model.Category import uz.uzkassa.smartpos.core.manager.coroutine.CoroutineContextManager import uz.uzkassa.smartpos.core.utils.extensions.flatMapResult import uz.uzkassa.smartpos.feature.category.common.domain.CategoryCommonInteractor import uz.uzkassa.smartpos.feature.category.list.data.CategoryListRepository import uz.uzkassa.smartpos.feature.category.list.data.params.EnabledCategoriesParams import javax.inject.Inject internal class CategoryListInteractor @Inject constructor( private val categoryListRepository: CategoryListRepository, private val coroutineContextManager: CoroutineContextManager ) : CategoryCommonInteractor() { fun getCategories(): Flow<Result<List<Category>>> = categoryListRepository .getEnabledCategories() .map { it -> it.filter { it.isEnabled } } .onEach { setCategories(it) } .flatMapResult() .flowOn(coroutineContextManager.ioContext) fun addCategory(category: Category): Flow<List<Category>> = flowOf(upsertCategory(category, true)) .onEach { setCategories(it) } .flowOn(coroutineContextManager.ioContext) @FlowPreview fun deleteCategory(category: Category): Flow<Result<List<Category>>> { return flow { emit(toggleChildCategories(category, isEnabled = false)) } .flatMapConcat { disabledCategory -> categoryListRepository .setEnabledCategories(EnabledCategoriesParams(listOf(disabledCategory))) .map { upsertCategory(disabledCategory, false) } .map { it -> it.filter { it.isEnabled } } .onEach { setCategories(it) } .flatMapResult() .flowOn(coroutineContextManager.ioContext) } } private fun toggleChildCategories(category: Category, isEnabled: Boolean): Category { val list: MutableList<Category> = arrayListOf() return if (category.childCategories.isEmpty()) category.copy(isEnabled = isEnabled) else { category.childCategories.forEach { val childCategory: Category = toggleChildCategories(it, isEnabled) list.add(childCategory) } category.copy(isEnabled = isEnabled, childCategories = list) } } }
/* * Copyright 2022 Junichi Kato * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.j5ik2o.adceet.api.write.aggregate import com.github.j5ik2o.adceet.domain.ThreadEvents.{ ThreadCreated, ThreadEvent } import com.github.j5ik2o.adceet.domain.ThreadId import com.github.j5ik2o.adceet.domain.Thread sealed trait ThreadState { def applyEvent(threadEvent: ThreadEvent): ThreadState = { (this, threadEvent) match { case (ts: ThreadState.Empty, t: ThreadCreated) => ts.create(t) case (ts: ThreadState.Just, t) => ts.update(t) } } } object ThreadState { case class Empty(threadId: ThreadId) extends ThreadState { def create(event: ThreadCreated): Just = Just(Thread.applyEvent(event)) } case class Just(thread: Thread) extends ThreadState { def update(threadEvent: ThreadEvent): Just = Just(thread.updateEvent(threadEvent)) } }
import React, {useContext} from 'react'; import {View, ScrollView, RefreshControl} from 'react-native'; import {HeaderTitle} from '../components/HeaderTitle'; import {appStyles} from '../theme/appTheme'; import {useState} from 'react'; import {ThemeContext} from '../context/themeContext/ThemeContext'; export const PullToRefreshScreen = () => { const [refreshing, setRefreshing] = useState(false); const { theme: {colors, dividerColor, dark}, } = useContext(ThemeContext); const [data, setData] = useState<string>(); const onRefresh = () => { setRefreshing(true); setTimeout(() => { console.log('Terminamos'); setRefreshing(false); setData('Hola Mundo'); }, 3000); }; return ( <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} progressViewOffset={10} progressBackgroundColor={dividerColor} colors={['orange', 'red', 'orange']} // style={{backgroundColor: '#5856D6'}} tintColor={dark ? 'white' : 'black'} /> }> <View style={appStyles.globalMargin}> <HeaderTitle title="Pull to refresh" /> {data && <HeaderTitle title={data} />} </View> </ScrollView> ); };
import { Inject, Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { ClientProxy } from '@nestjs/microservices'; import { TaskHelper } from './helper/task.helper'; import * as moment from "moment"; import { Company, CompanyRepository, EVENT_JOB_NAME, IJobTask, JobLog, JobLogRepository, JobState, SALARY_SERVICE_QUEUE, User, UserRepository, generateJobKey } from '@app/common'; @Injectable() export class TaskService { private readonly logger = new Logger(TaskService.name); constructor( @Inject(SALARY_SERVICE_QUEUE) private salaryClient: ClientProxy, private readonly companyRepository: CompanyRepository, private readonly userRepository: UserRepository, private readonly jobLogRepository: JobLogRepository, private taskHelper: TaskHelper, ) { this.salaryClient.connect(); } @Cron(CronExpression.EVERY_HOUR) async handleCron() { try { const currentTimeHour = moment().hour(); const timeZoneAtMidNight = this.taskHelper.getMidNightTimezone(currentTimeHour); this.logger.log("CurrentTimeHour", { currentTimeHour, timeZoneAtMidNight }); const companyByTimezones: Company[] = await this.companyRepository.getCompaniesByTimezones(timeZoneAtMidNight); // Check if no companies run at midnight -> return; if (!companyByTimezones.length) return; for (const company of companyByTimezones) { const usersBelongToCompany: User[] = await this.userRepository.getAllUserByCompany(company._id.toString()); if (!usersBelongToCompany.length) return; const timeCalculate = this.taskHelper.getCurrentCompanyTimeCalculate(company.timezone); for (const user of usersBelongToCompany) { const jobKey = generateJobKey(user._id.toString(), company._id.toString()); const isJobCreated: JobLog | false = await this.isCreatedJobTask(jobKey, timeCalculate); // If job (include companyId and userId) not created then create new job logs if (!isJobCreated) { await Promise.all([ this.createNewTaskJob(company._id.toString(), user._id.toString(), timeCalculate), // create job logs this.jobLogRepository.create({ job_key: jobKey, day_caculate: timeCalculate, job_state: JobState.PENDING }) ]); } else if (isJobCreated.job_state === JobState.PENDING) { // if job state still pending then send again await this.createNewTaskJob(company._id.toString(), user._id.toString(), timeCalculate) } } } } catch (error) { this.logger.error("HandleCronError", JSON.stringify(error)); } } async createNewTaskJob(companyId: string, userId: string, dateTime: number): Promise<void> { try { const payload: IJobTask = { user_id: userId, company_id: companyId, dateTime }; this.salaryClient.emit(EVENT_JOB_NAME, payload); } catch (error) { this.logger.error('CANNOT_SEND_TASK_HANDLE', JSON.stringify({ companyId, userId, date: moment()})); throw error; } } async isCreatedJobTask(jobKey: string, calculateTime: number): Promise<JobLog | false> { const jobLog = await this.jobLogRepository.getJobLogByKey(jobKey) return (jobLog && jobLog.day_caculate === calculateTime) ? jobLog : false; } }
import React from 'react' import axios from 'axios' import styles from './styles.module.scss' import MovieCard from '../../commons/Movie-Card/MovieCard' import { MdNavigateBefore, MdNavigateNext } from 'react-icons/md' const API_KEY = '9c3fd4dd152d57af68bd8d3ebd55fce0' const GenericMovies = ({ movieName }) => { const [movies, setMovies] = React.useState([]) let cardsSectionRef = React.useRef() const scroll = (scrollOffset) => { if (cardsSectionRef.current) { cardsSectionRef.current.scrollLeft += scrollOffset } } React.useEffect(() => { axios .get( `https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&language=en-US&query=${movieName}` ) .then((res) => setMovies(res.data.results)) .catch((err) => console.log(err)) }, []) return ( <> <div className={styles.blurContainer}></div> <div className={styles.PMwrapper}> <div className={styles.heading}>{movieName} Movies</div> <div ref={cardsSectionRef} className={styles.cardsContainer}> {movies.map((element, idx) => ( <MovieCard key={element.id} movieData={element} /> ))} <button type="button" className={styles.prevButton} onClick={() => scroll(-1400)} > <MdNavigateBefore className={styles.buttonIcons} /> </button> <button type="button" className={styles.nextButton} onClick={() => scroll(1400)} > <MdNavigateNext className={styles.buttonIcons} /> </button> </div> </div> </> ) } export default GenericMovies
import 'package:daramge/components/create_tile.dart'; import 'package:daramge/components/medicine_tile.dart'; import 'package:daramge/components/option_tile.dart'; import 'package:daramge/models/medicine.dart'; import 'package:daramge/models/medicine_shop.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class ShopPage extends StatefulWidget { const ShopPage({Key? key}) : super(key: key); @override State<ShopPage> createState() => _ShopPageState(); } class _ShopPageState extends State<ShopPage> { void addToBag(Medicine medicine) async { if (medicine.price.length > 1) { medicine = await showDialog( context: context, builder: (context) => MedicineDetailsDialog(medicine: medicine), ); } Provider.of<MedicineShop>(context, listen: false).addItemToBag(medicine); await showDialog( context: context, builder: (context) => Center( child: AlertDialog( content: Container( width: MediaQuery.of(context).size.width * 0.7, // 70% of screen width child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( "약을 담았습니다", textAlign: TextAlign.center, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20), // Add some vertical space Text( "${medicine.type.length == 1 && medicine.type[0] != "기본" ? medicine.type[0] : medicine.name}, ${medicine.price[0]}원", textAlign: TextAlign.center, style: TextStyle(fontSize: 16), ), ], ), ), ), ), ); } Future<void> addNewMedicine() async { final newMedicine = await showAddMedicineDialog(context); print(1); print(newMedicine); // if (newMedicine != null) { // // Add the new medicine to your data source or perform any other necessary action // Provider.of<MedicineShop>(context, listen: false).addMedicine( // Medicine( // name: "새로운 약", // type: ["기본"], // price: [10000], // imagePath: "lib/images/1.png", // ), // ); // } } @override Widget build(BuildContext context) { return Consumer<MedicineShop>( builder: (context, value, child) => Scaffold( appBar: AppBar( title: Text( '연세소래메디칼 수액리스트', style: TextStyle(fontSize: 24.0, color: Colors.white), ), centerTitle: true, backgroundColor: Colors.teal, ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: SizedBox( height: MediaQuery.of(context).size.height * 0.8, child: ListView.builder( itemCount: value.medicineBag.length, itemBuilder: (context, index) { Medicine eachMedicine = value.medicineBag[index]; return MedicineTile( medicine: eachMedicine, icon: Icon(Icons.add), onPressed: () => addToBag(eachMedicine), ); }, ), ), ), // Padding( // padding: const EdgeInsets.all(8.0), // child: Align( // alignment: Alignment.bottomRight, // child: ElevatedButton( // onPressed: () => addNewMedicine(), // child: Text( // '새로운 약 추가', // style: TextStyle(color: Colors.white), // ), // style: ElevatedButton.styleFrom( // backgroundColor: Colors.teal, // padding: EdgeInsets.all(16.0), // ), // ), // ), // ), ], ), ), ), ); } }
package com.rodi1.androidbackend.controller; import com.rodi1.androidbackend.entity.Authority; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import com.rodi1.androidbackend.controller.dto.UserProfileDto; import com.rodi1.androidbackend.controller.dto.UserRegisterDto; import com.rodi1.androidbackend.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping("/androidbackend/v1/") public class UserController { private final UserService userService; @PostMapping("user/register") @ResponseStatus(HttpStatus.CREATED) public UserProfileDto add(@RequestBody UserRegisterDto userRegisterDto) { return userService.add(userRegisterDto); } @GetMapping("user") @ResponseStatus(HttpStatus.OK) public List<UserProfileDto> getAll() { return userService.getAll(); } @GetMapping("user/{id}") @ResponseStatus(HttpStatus.OK) public UserProfileDto getById(@PathVariable Long id) { return userService.getById(id); } @PutMapping("user/{id}") @ResponseStatus(HttpStatus.OK) public UserProfileDto update(@PathVariable Long id, @RequestBody UserProfileDto userProfileDto) { return userService.update(id, userProfileDto); } @PutMapping("/authority/{id}") @ResponseStatus(HttpStatus.OK) public void update(@PathVariable Long id, @RequestBody Authority authority) { userService.update(id, authority); } @DeleteMapping("user/{id}") @ResponseStatus(HttpStatus.OK) public void deleteById(@PathVariable Long id) { userService.deleteById(id); } @GetMapping("user/username/{username}") @ResponseStatus(HttpStatus.OK) public String getByUsername(@PathVariable String username) { UserProfileDto byUsername = userService.getByUsername(username); return "User with username " + byUsername.getUsername() + " is registered!"; } @GetMapping("user/login") @ResponseStatus(HttpStatus.OK) public UserProfileDto login(Authentication authentication) { return userService.getByUsername(authentication.getName()); } }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { NotFoundComponent } from './not-found/not-found.component'; import { StoreDetailsComponent } from './store-details/store-details.component'; import { StoresListViewComponent } from './stores-list-view/stores-list-view.component'; const routes: Routes = [ { path: 'home', component : HomeComponent}, { path: '', redirectTo: '/home', pathMatch: 'full'}, { path: 'details', component: StoreDetailsComponent}, { path: 'StoresListView', component: StoresListViewComponent}, { path: '404', component : NotFoundComponent}, { path: '**', redirectTo: '/404'} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import './envconfig'; import routes from './routes'; import bodyParser from 'body-parser'; import cors from 'cors'; import createDebug from 'debug'; import express from 'express'; import formData from 'express-form-data'; import jsdocSwagger from 'express-jsdoc-swagger'; import lusca from 'lusca'; import { auth } from 'middlewares/auth/auth'; import logger from 'morgan'; import { expressRouter } from 'trpc/router'; import { StatusError } from 'utils/errors'; const debug = createDebug('backend-ts:app'); /** * JSDoc Swagger options */ const options = { info: { version: '0.1.0', title: 'PIU-TOP TS backend', description: '', }, security: { BasicAuth: { type: 'http', scheme: 'basic' } }, baseDir: __dirname, filesPattern: './**/*.ts', swaggerUIPath: '/api-docs', exposeSwaggerUI: true, notRequiredAsNullable: false, swaggerUiOptions: {}, }; /** * Create Express server */ export const app = express(); jsdocSwagger(app)(options); const isTest = process.env.NODE_ENV === 'test'; !isTest && app.use(logger('tiny')); app.use(bodyParser.json({ limit: '2mb' })); app.use(bodyParser.urlencoded({ extended: false })); app.use(formData.parse()); // app.use(formData.stream()); app.use(lusca.xframe('SAMEORIGIN')); app.use(lusca.xssProtection(true)); app.use( cors({ origin: process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : 'https://pumpking.top', credentials: true, optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204 }) ); app.use(auth); app.use((req, _res, next) => { debug(`[${req.method}] ${req.path}`); next(); }); app.use('/', routes); app.use('/trpc', expressRouter); app.use((req, res, next) => { next(new StatusError(404, 'Not Found')); }); // error handler app.use( ( err: Error | StatusError<unknown>, _req: express.Request, res: express.Response, _next: express.NextFunction ) => { if (err instanceof StatusError) { debug(err.status, err.message); res.status(err.status).json({ message: err.message, data: err.data, }); } else { debug(err); res.status(500).json({ message: 'Internal Server Error: ' + err.message, }); } } );
package com.zizaike.app.api.controller.search; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.zizaike.app.api.BaseAjaxController; import com.zizaike.app.api.service.SignService; import com.zizaike.app.api.sign.SignValid; import com.zizaike.core.bean.ResponseResult; import com.zizaike.core.framework.exception.IllegalParamterException; import com.zizaike.core.framework.exception.ZZKServiceException; import com.zizaike.entity.base.ChannelType; import com.zizaike.entity.solr.BNBServiceType; import com.zizaike.entity.solr.SearchType; import com.zizaike.entity.solr.ServiceSearchVo; import com.zizaike.is.redis.HotRecommendRedisService; import com.zizaike.is.redis.RecommendAreaRedisService; import com.zizaike.is.solr.UserSolrService; @Controller @RequestMapping("/search/recommend") public class RecommendController extends BaseAjaxController { @Autowired private HotRecommendRedisService hotRecommendRedisService; @Autowired private SignService signService; @Autowired private RecommendAreaRedisService recommendAreaRedisService; @Autowired private UserSolrService userSolrService; @RequestMapping(value = "hot", method = RequestMethod.GET) @ResponseBody @SignValid(ingore={"request"}) public ResponseResult getHotRecommend(HttpServletRequest request ,@RequestParam("apiSign") String apiSign,@RequestParam("apiKey") String apiKey ,@RequestParam("multilang") Integer multilang) throws ZZKServiceException { ResponseResult result = new ResponseResult(); result.setInfo(hotRecommendRedisService.qury()); return result; } /** * * getLocAndHotRecommend:地址与热推. <br/> * @author snow.zhang * @return * @throws ZZKServiceException * @since JDK 1.7 */ @RequestMapping(value = "area_recommend", method = RequestMethod.GET) @ResponseBody @SignValid public ResponseResult getLocAndHotRecommend(@RequestParam("apiSign") String apiSign,@RequestParam("apiKey") String apiKey,@RequestParam("multilang") Integer multilang) throws ZZKServiceException { ResponseResult result = new ResponseResult(); result.setInfo(recommendAreaRedisService.query()); return result; } /** * * getLocAndHotRecommendByDest:根据目的地获得地址与热推. <br/> * @author alex * @return * @throws ZZKServiceException * @since JDK 1.7 */ @RequestMapping(value = "area_recommend_bydest", method = RequestMethod.GET) @ResponseBody @SignValid public ResponseResult getLocAndHotRecommendByDest(@RequestParam("apiSign") String apiSign,@RequestParam("apiKey") String apiKey,@RequestParam("multilang") Integer multilang,@RequestParam("destId") Integer destId) throws ZZKServiceException { ResponseResult result = new ResponseResult(); result.setInfo(recommendAreaRedisService.queryByDest(destId)); return result; } /** * * service:服务推荐. <br/> * * @author snow.zhang * @param userId * @param multiprice * @param apiSign * @param apiKey * @param multilang * @return * @throws ZZKServiceException * @since JDK 1.7 */ @RequestMapping(value = "service", method = RequestMethod.GET) @ResponseBody @SignValid public ResponseResult service(@RequestParam(value="destId",required=false) String destId,@RequestParam(value="userId",required=false) Integer userId, @RequestParam(value="searchid",required=false) String searchid,@RequestParam(value="searchType",required=false) SearchType searchType, @RequestParam(value="serviceType",required=false) BNBServiceType serviceType, @RequestParam(value="page",required=true) String page, @RequestParam("multiprice") Integer multiprice,@RequestParam("apiSign") String apiSign,@RequestParam("apiKey") String apiKey,@RequestParam("multilang") Integer multilang ) throws ZZKServiceException { ServiceSearchVo searchVo = new ServiceSearchVo(); Pattern pattern = Pattern.compile("[0-9]*"); searchVo.setChannel(ChannelType.APP); searchVo.setUserId(userId); searchVo.setMultiprice(multiprice); if(userId!=null){ searchVo.setUserId(userId); } if (!pattern.matcher(page).matches()) { throw new IllegalParamterException("page type error"); } searchVo.setPage(Integer.parseInt(page)); ResponseResult result = new ResponseResult(); result.setInfo(userSolrService.serviceRecommend(searchVo)); return result; } }
// The MIT License (MIT) // // Copyright (c) 2018-2019 Darrell Wright // // 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 once #include <string> #include <vector> #include <daw/daw_utility.h> #include "action_status.h" #include "logging.h" #include "proc.h" #include "utilities.h" namespace daw::glean { template<typename SvnAction, typename OutputIterator> action_status svn_runner( SvnAction &&svn_action, fs::path work_tree, OutputIterator &&out_it ) { auto args = svn_action.build_args( std::move( work_tree ) ); log_message << "Running svn"; for( auto arg : args ) { log_message << ' ' << arg; } log_message << "\n\n"; auto run_process = Process( std::forward<OutputIterator>( out_it ) ); if( run_process( "svn", std::move( args ) ) == EXIT_SUCCESS ) { return action_status::success; } return action_status::failure; } struct svn_action_update { std::vector<std::string> build_args( fs::path const &work_tree ) const; }; struct svn_action_checkout { std::string remote_uri{}; std::vector<std::string> build_args( fs::path const &work_tree ) const; }; } // namespace daw::glean
import { inject, injectable } from "tsyringe"; import { StatusCodes as HTTP } from "http-status-codes"; import { IFileService } from "types/services/IFileService"; import { IVariantRepository } from "types/repositories/IVariantRepository"; import { ControllerImplementation } from "types/controllers/ControllerImplementation"; import { GetContentByIdControllerTypes } from "types/controllers/Variant/GetContentByIdController"; import { Di } from "@enums/Di"; import { BaseController } from "@controllers/BaseController"; const { v1 } = BaseController.ALL_VERSION_DEFINITIONS; @injectable() export class GetContentByIdController extends BaseController { constructor( @inject(Di.VariantRepository) private _variantRepository: IVariantRepository, @inject(Di.FileService) private _fileService: IFileService ) { super(); } implementations: ControllerImplementation[] = [ { version: v1, handle: this.v1.bind(this), }, ]; static readonly ALL_VERSIONS = [v1]; async v1( request: GetContentByIdControllerTypes.v1.Request, response: GetContentByIdControllerTypes.v1.Response ) { const { params: { id }, query: { workspaceId }, } = request; const variant = await this._variantRepository.getById(id); if (!variant) { return response.status(HTTP.NOT_FOUND).send(); } const content = await this._fileService.getContent({ variant, from: { workspaceId }, }); if (!content) { return response.status(HTTP.NOT_FOUND).send(); } return this.finalizeRequest(response, HTTP.OK, content); } }
import React, { useEffect, useState } from 'react' import { isEmpty } from 'lodash'; import LoadingScreen from 'react-loading-screen'; import { useRecoilState } from 'recoil'; import LoggedInComponentRoutes from './modules/loggedInComponents/LoggedInComponentRoutes'; import LoggedOutComponentRoutes from './modules/loggedIOutComponents/LoggedOutComponentRoutes'; import CricFunnLogo from './resources/cricfunn.png'; import { userAtom } from './store/userStore'; import { auth } from './firebase/config'; import { getUserByKey } from './apis/usercontroller'; import { showToastMessage } from './components/Toast'; const Routes = () => { const [user, setUser] = useRecoilState(userAtom); const [isLoading, setIsLoading] = useState(false); useEffect(() => { setIsLoading(true); auth.onAuthStateChanged(handleAuthStateChange); },[]); const handleAuthStateChange = async (user) => { try { if(user) { const userSnapshot = await getUserByKey("username", user.displayName); const userDetails = !isEmpty(userSnapshot.docs) ? userSnapshot.docs[0].data() : {}; setUser(userDetails); } } catch (e) { showToastMessage("error", `Error in loading your details: ${e.message}`); console.log(e.message); } setIsLoading(false); } return ( <LoadingScreen loading={isLoading} bgColor="rgb(17,24,39)" spinnerColor="#fff" textColor="#fff" text="Loading your details. Please wait..." logoSrc={CricFunnLogo} > { !isEmpty(user) ? <LoggedInComponentRoutes /> : <LoggedOutComponentRoutes /> } </LoadingScreen> ); } export default Routes;
package com.bytecause.nautichart.ui.view.fragment.dialog import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.DialogFragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bytecause.nautichart.R import com.bytecause.nautichart.data.local.room.tables.CustomPoiCategoryEntity import com.bytecause.nautichart.data.local.room.tables.CustomPoiEntity import com.bytecause.nautichart.databinding.AddCustomMarkerBinding import com.bytecause.nautichart.ui.adapter.GenericRecyclerViewAdapter import com.bytecause.nautichart.ui.adapter.RecyclerViewBindingInterface import com.bytecause.nautichart.ui.view.custom.FullyExpandedRecyclerView import com.bytecause.nautichart.ui.view.delegate.viewBinding import com.bytecause.nautichart.ui.viewmodels.CustomMarkerViewModel import com.bytecause.nautichart.ui.viewmodels.MapSharedViewModel import com.bytecause.nautichart.util.MapUtil import com.bytecause.nautichart.util.TAG import com.bytecause.nautichart.util.Util import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import kotlin.properties.Delegates // TODO("Refactor") @AndroidEntryPoint class CustomMarkerDialog : DialogFragment(), ConfirmationDialog.ConfirmationDialogListener { private val binding by viewBinding(AddCustomMarkerBinding::inflate) private val mapSharedViewModel: MapSharedViewModel by activityViewModels() private val viewModel: CustomMarkerViewModel by viewModels() private lateinit var categoryRecyclerView: FullyExpandedRecyclerView private lateinit var categoryGenericRecyclerViewAdapter: GenericRecyclerViewAdapter<CustomPoiCategoryEntity> private lateinit var poiRecyclerView: FullyExpandedRecyclerView private lateinit var poiGenericRecyclerViewAdapter: GenericRecyclerViewAdapter<CustomPoiEntity> private val poiCategoriesList = mutableListOf<CustomPoiCategoryEntity>() private val poiList = mutableListOf<CustomPoiEntity>() private var categoryAddButton by Delegates.notNull<CustomPoiCategoryEntity>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { if (dialog != null && dialog?.window != null) { dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) } categoryAddButton = CustomPoiCategoryEntity( categoryName = "Add custom", drawableResourceName = resources.getResourceEntryName(R.drawable.baseline_dashboard_customize_24) ) val gridLayoutManager = object : GridLayoutManager(requireContext(), 5) { override fun canScrollVertically(): Boolean { return false } } @SuppressLint("ResourceType") val categoryBindingInterface = object : RecyclerViewBindingInterface<CustomPoiCategoryEntity> { override fun bindData( item: CustomPoiCategoryEntity, itemView: View, itemPosition: Int ) { itemView.findViewById<TextView?>(R.id.categoryName).apply { text = item.categoryName tag = item.drawableResourceName setCompoundDrawablesWithIntrinsicBounds( null, ResourcesCompat.getDrawable( resources, resources.getIdentifier( item.drawableResourceName, "drawable", requireActivity().packageName ), null ), null, null ) } itemView.apply { setOnClickListener { if (!Util().lastClick(300)) return@setOnClickListener if (itemPosition == categoryGenericRecyclerViewAdapter.itemCount - 1 && categoryRecyclerView.getChildAt( itemPosition ) .findViewById<TextView>(R.id.categoryName).text == categoryAddButton.categoryName ) { viewModel.setItemViewPosition(RecyclerView.NO_POSITION) resetClickedButtonState() //findNavController().navigate(R.id.action_customMarkerDialog_to_addCustomMarkerCategoryDialog) navigate() //poiList.clear() updatePoiList(poiList) return@setOnClickListener } resetClickedButtonState() // Store the selected position for future reference viewModel.setItemViewPosition(itemPosition) animateClick(itemView) lifecycleScope.launch { val categoryName = itemView.findViewById<TextView>( R.id.categoryName ).text.toString() viewModel.getCategoryWithPois( categoryName ) .firstOrNull()?.let { updatePoiList(it.pois) } /*viewModel.getPoisByCategoryName( itemView.findViewById<TextView>( R.id.categoryName ).text.toString() ) .firstOrNull().let { updatePoiList(it) }*/ } } setOnLongClickListener { if (itemPosition > 2 && categoryRecyclerView.getChildAt( itemPosition ) .findViewById<TextView>(R.id.categoryName).text != categoryAddButton.categoryName ) { viewModel.setRemoveIndex(itemPosition) val confirmationDialog = ConfirmationDialog.newInstance( resources.getString(R.string.delete_category_title), resources.getString(R.string.delete_category_description), null, "delete_poi_category" ) confirmationDialog.show( childFragmentManager, confirmationDialog.tag ) } return@setOnLongClickListener true } } } } @SuppressLint("ResourceType") val poiBindingInterface = object : RecyclerViewBindingInterface<CustomPoiEntity> { override fun bindData(item: CustomPoiEntity, itemView: View, itemPosition: Int) { val removeCustomPoi: ImageButton = itemView.findViewById(R.id.remove_custom_poi) val poiIconImageView: ImageView = itemView.findViewById(R.id.poi_icon) itemView.findViewById<TextView?>(R.id.poi_name).apply { text = item.poiName tag = item.poiId //item.categoryName } poiIconImageView.setImageResource( resources.getIdentifier( item.drawableResourceName, "drawable", requireActivity().packageName ) ) removeCustomPoi.setOnClickListener { viewModel.setRemoveIndex(itemPosition) val confirmationDialog = ConfirmationDialog.newInstance( resources.getString(R.string.delete_poi_marker_title), null, null, "delete_poi_marker" ) confirmationDialog.show(childFragmentManager, confirmationDialog.tag) } } } categoryRecyclerView = binding.categoryRecyclerView categoryRecyclerView.layoutManager = gridLayoutManager poiRecyclerView = binding.poiListRecyclerView poiRecyclerView.layoutManager = LinearLayoutManager(requireContext()) viewModel.setItemViewPosition(0) // Initialize and set the adapter categoryGenericRecyclerViewAdapter = GenericRecyclerViewAdapter( poiCategoriesList, R.layout.recyclerview_marker_category, categoryBindingInterface ) categoryRecyclerView.adapter = categoryGenericRecyclerViewAdapter poiGenericRecyclerViewAdapter = GenericRecyclerViewAdapter( poiList, R.layout.recyclerview_poi_list_layout, poiBindingInterface ) poiRecyclerView.adapter = poiGenericRecyclerViewAdapter viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.getAllCategories.collect { if (it.isEmpty()) { Log.d(TAG(), "first run") // ID's aren't static, so drawable name has to be used instead. val initCategories = listOf( CustomPoiCategoryEntity( categoryName = "Favorite", drawableResourceName = resources.getResourceEntryName(R.drawable.baseline_favorite_24) ), CustomPoiCategoryEntity( categoryName = "Travel plans", drawableResourceName = resources.getResourceEntryName(R.drawable.baseline_mode_of_travel_24) ), CustomPoiCategoryEntity( categoryName = "Nautical POI", drawableResourceName = resources.getResourceEntryName(R.drawable.nautical_poi_icon) ) ) for (x in initCategories) { viewModel.insertCategory(x) } categoryGenericRecyclerViewAdapter.notifyItemRangeChanged( 0, poiCategoriesList.size ) postAndNotifyAdapter(Handler(Looper.getMainLooper()), categoryRecyclerView) } else if (poiCategoriesList.isNotEmpty()) { Log.d(TAG(), "poi list not empty") if (poiCategoriesList.size <= 20) { poiCategoriesList.let { list -> list.removeLast() list.addAll( it.filter { poiCategoriesList.none { presentCategory -> presentCategory == it } } ) list.add(categoryAddButton) } categoryGenericRecyclerViewAdapter.notifyItemRangeChanged( 3, poiCategoriesList.size - 3 ) } if (poiCategoriesList.size > 20) { poiCategoriesList.removeLast() categoryGenericRecyclerViewAdapter.notifyItemRangeRemoved( poiCategoriesList.size, 1 ) } } else { Log.d(TAG(), "second run") for (x in it) { poiCategoriesList.add(x) } if (poiCategoriesList.size < 20) poiCategoriesList.add(categoryAddButton) categoryGenericRecyclerViewAdapter.notifyItemRangeChanged( 0, poiCategoriesList.size ) postAndNotifyAdapter(Handler(Looper.getMainLooper()), categoryRecyclerView) } } } } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.markerNameInput.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged( s: CharSequence?, start: Int, before: Int, count: Int ) { } override fun afterTextChanged(s: Editable?) { showErrorWhenEmpty() } }) binding.markerDescriptionLayout.visibility = when { viewModel.isMarkerDescriptionVisible -> View.VISIBLE else -> View.GONE } binding.toolbar.apply { navBack.setOnClickListener { findNavController().popBackStack() } destNameTextView.text = getString(R.string.add_marker) } binding.saveButton.setOnClickListener { requireNotNull(binding.markerNameInput.text).let { if (it.isNotEmpty() && viewModel.itemViewPosition != RecyclerView.NO_POSITION) { val categoryNameTextView = categoryRecyclerView.layoutManager?.findViewByPosition(viewModel.itemViewPosition) ?.findViewById<TextView>(R.id.categoryName) viewModel.insertCustomPoi( CustomPoiEntity( poiName = binding.markerNameInput.text.toString(), latitude = mapSharedViewModel.geoPoint?.latitude ?: 0.0, longitude = mapSharedViewModel.geoPoint?.longitude ?: 0.0, description = when (!binding.markerDescriptionInput.text.isNullOrEmpty()) { true -> binding.markerDescriptionInput.text.toString() else -> "" }, categoryName = categoryNameTextView?.text?.toString() ?: "Favorite", drawableResourceName = categoryNameTextView?.tag as? String ?: resources.getResourceEntryName(R.drawable.baseline_favorite_24) ) ) this.dismiss() } else showErrorWhenEmpty() } } mapSharedViewModel.geoPoint?.let { geoPoint -> binding.coordinatesTextview.text = resources.getString(R.string.split_two_strings_formatter).format( MapUtil.latitudeToDMS(geoPoint.latitude), MapUtil.longitudeToDMS(geoPoint.longitude) ) } binding.expandDescriptionEdittext.setOnClickListener { when { binding.markerDescriptionLayout.visibility != View.VISIBLE -> { binding.markerDescriptionLayout.visibility = View.VISIBLE viewModel.isMarkerDescriptionVisible(true) binding.addDescriptionTextview.text = resources.getString(R.string.remove_description) binding.addDescriptionImageview.setImageDrawable( ContextCompat.getDrawable( requireContext(), R.drawable.baseline_remove_circle_outline_24 ) ) } else -> { binding.markerDescriptionLayout.visibility = View.GONE viewModel.isMarkerDescriptionVisible(false) binding.markerDescriptionInput.setText("") binding.addDescriptionTextview.text = resources.getString(R.string.add_description) binding.addDescriptionImageview.setImageDrawable( ContextCompat.getDrawable( requireContext(), R.drawable.baseline_description_24 ) ) } } } } private fun navigate() { findNavController().navigate(R.id.action_customMarkerDialog_to_addCustomMarkerCategoryDialog) } // Recursive function which will invoke performClick() on first itemView in recyclerView after layout completion. private fun postAndNotifyAdapter(handler: Handler, recyclerView: RecyclerView) { if (findNavController().currentDestination?.id == R.id.addCustomMarkerCategoryDialog) return // if (sharedViewModel.isAddCategoryDialogShowing) return handler.post { if (!recyclerView.isComputingLayout) { (recyclerView.findViewHolderForLayoutPosition( when (viewModel.itemViewPosition) { categoryRecyclerView.childCount - 1 -> 0 else -> viewModel.itemViewPosition } ) as GenericRecyclerViewAdapter.ViewHolder?)?.itemView?.performClick() } else { postAndNotifyAdapter(handler, recyclerView) } } } private fun animateClick(view: View) { val animDuration: Long = 200 val scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, 0.6f, 1f) val scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.6f, 1f) scaleX.duration = animDuration scaleY.duration = animDuration val animatorSet = AnimatorSet() animatorSet.playTogether(scaleX, scaleY) ContextCompat.getDrawable(requireContext(), R.drawable.rounded_background)?.apply { setTint(ContextCompat.getColor(requireContext(), R.color.button_state_color)) view.background = this } animatorSet.start() } private fun showErrorWhenEmpty() { if (findNavController().currentDestination?.id == R.id.addCustomMarkerCategoryDialog) return // if (sharedViewModel.isAddCategoryDialogShowing) return binding.markerNameLayout.let { if (binding.markerNameInput.text.isNullOrEmpty()) it.error = "Type name!" else it.error = null } } // Resets background drawable for all item views. private fun resetClickedButtonState() { for (x in 0..<categoryRecyclerView.childCount) { categoryRecyclerView.getChildViewHolder(categoryRecyclerView.getChildAt(x)).itemView.setBackgroundColor( ContextCompat.getColor(requireContext(), R.color.transparent) ) } } private fun updatePoiList(list: List<CustomPoiEntity>?, position: Int? = null) { list ?: return val itemCount = poiList.size if (position != null) { poiList.removeAt(position) poiGenericRecyclerViewAdapter.notifyItemRangeRemoved(position, itemCount) if (poiList.isEmpty()) binding.emptyListTextView.visibility = View.VISIBLE } else if (list.isNotEmpty()) { poiList.clear() poiGenericRecyclerViewAdapter.notifyItemRangeRemoved(0, itemCount) for (x in list) { poiList.add(x) } poiGenericRecyclerViewAdapter.notifyItemRangeChanged(0, poiList.size) binding.emptyListTextView.visibility = View.GONE } else { if ((categoryRecyclerView.getChildAt(viewModel.itemViewPosition) ?: categoryRecyclerView.getChildAt(categoryGenericRecyclerViewAdapter.itemCount - 1)) .findViewById<TextView>(R.id.categoryName).text == categoryAddButton.categoryName ) { binding.emptyListTextView.visibility = View.GONE poiGenericRecyclerViewAdapter.itemCount } else { poiList.clear() poiGenericRecyclerViewAdapter.notifyItemRangeRemoved(0, itemCount) binding.emptyListTextView.visibility = View.VISIBLE } } } private fun removePoiCategory() { viewLifecycleOwner.lifecycleScope.launch { requireNotNull(viewModel.removeIndex).let { viewModel.setItemViewPosition(RecyclerView.NO_POSITION) viewModel.removeCategory(poiCategoriesList[it]) poiCategoriesList.removeAt(it) updatePoiList(poiList) categoryGenericRecyclerViewAdapter.notifyItemRemoved(it) resetClickedButtonState() } } } private fun removePoiMarker() { viewLifecycleOwner.lifecycleScope.launch { requireNotNull(viewModel.removeIndex).let { poiRecyclerView.layoutManager?.findViewByPosition(it) ?.findViewById<TextView>(R.id.poi_name).let { textView -> if (textView != null) { viewModel.removeCustomPoi(textView.tag as Long) } } updatePoiList(poiList, it) } } } override fun onDialogPositiveClick(dialogId: String, additionalData: Any?) { when (dialogId) { "delete_poi_category" -> removePoiCategory() "delete_poi_marker" -> removePoiMarker() } } override fun onStart() { super.onStart() // Apply the fullscreen dialog style dialog?.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) dialog?.window?.setBackgroundDrawable( ColorDrawable( ContextCompat.getColor( requireContext(), R.color.dialog_background ) ) ) } }
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatTableDataSource } from '@angular/material/table'; import { AddTeacherDialogComponent } from '../add-teacher-dialog/add-teacher-dialog.component'; import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component'; import { MatSnackBar } from '@angular/material/snack-bar'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; interface TeacherData { name: string; class: string; section: string; // subject?: string; // Add subject field subjects: string[]; // Change subject to subjects array status: string; selected?: boolean; } @Component({ selector: 'app-teacher-master', templateUrl: './teacher-master.component.html', styleUrls: ['./teacher-master.component.css'] }) export class TeacherMasterComponent implements OnInit { displayedColumns: string[] = ['select', 'name', 'class', 'section', 'subject', 'status', 'action']; dataSource: MatTableDataSource<TeacherData>; @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; teacherData: TeacherData[] = []; constructor(public dialog: MatDialog, private snackBar: MatSnackBar) { this.dataSource = new MatTableDataSource<TeacherData>(this.teacherData); } ngOnInit(): void { this.loadTeacherData(); } ngAfterViewInit(): void { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } // loadTeacherData(): void { // const savedTeacherData = JSON.parse(localStorage.getItem('teacherData') || '[]'); // const employees = JSON.parse(localStorage.getItem('employees') || '[]'); // this.teacherData = employees // .filter((emp: any) => emp.role === 'teacher') // .map((emp: any) => { // const savedData = savedTeacherData.find((t: TeacherData) => t.name === emp.name) || {}; // return { // name: emp.name, // class: savedData.class || '', // section: savedData.section || '', // subject: savedData.subject || '', // Initialize subject // status: savedData.status || 'Pending', // selected: false // }; // }); // this.dataSource.data = this.teacherData; // } loadTeacherData(): void { const savedTeacherData = JSON.parse(localStorage.getItem('teacherData') || '[]'); const employees = JSON.parse(localStorage.getItem('employees') || '[]'); this.teacherData = employees .filter((emp: any) => emp.role === 'teacher') .map((emp: any) => { const savedData = savedTeacherData.find((t: TeacherData) => t.name === emp.name) || {}; return { name: emp.name, class: savedData.class || '', section: savedData.section || '', subjects: savedData.subjects || [], // Initialize subjects as array status: savedData.status || 'Pending', selected: false }; }); this.dataSource.data = this.teacherData; } // openAddTeacherDialog(): void { // const selectedTeachers = this.dataSource.data.filter(teacher => teacher.selected); // if (selectedTeachers.length === 0) return; // if (selectedTeachers.length > 8) { // this.snackBar.open('You can only assign up to 8 teachers at a time.', 'Close', { // duration: 3000, // }); // return; // } // const dialogRef = this.dialog.open(AddTeacherDialogComponent, { // width: '400px', // data: { selectedTeachers } // }); // dialogRef.afterClosed().subscribe(result => { // if (result) { // this.assignTeachers(result.class, result.section, result.subject); // } // }); // } // openAssignDialog(teacher: TeacherData): void { // const dialogRef = this.dialog.open(AddTeacherDialogComponent, { // width: '400px', // data: { selectedTeachers: [teacher] } // }); // dialogRef.afterClosed().subscribe(result => { // if (result) { // this.assignTeacher(teacher, result.class, result.section,result.subject,); // } // }); // } openAddTeacherDialog(): void { const selectedTeachers = this.dataSource.data.filter(teacher => teacher.selected); if (selectedTeachers.length === 0) return; if (selectedTeachers.length > 8) { this.snackBar.open('You can only assign up to 8 teachers at a time.', 'Close', { duration: 3000, }); return; } const dialogRef = this.dialog.open(AddTeacherDialogComponent, { width: '400px', data: { selectedTeachers } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.assignTeachers(result.class, result.section, result.subjects); } }); } openAssignDialog(teacher: TeacherData): void { const dialogRef = this.dialog.open(AddTeacherDialogComponent, { width: '400px', data: { selectedTeachers: [teacher] } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.assignTeacher(teacher, result.class, result.section, result.subjects); } }); } // assignTeachers(selectedClass: string, selectedSection: string, selectedSubject: string): void { // this.dataSource.data.forEach(teacher => { // if (teacher.selected) { // this.assignTeacher(teacher, selectedClass, selectedSection, selectedSubject); // teacher.selected = false; // } // }); // this.saveTeacherData(); // this.dataSource.data = [...this.teacherData]; // } // assignTeacher(teacher: TeacherData, selectedClass: string, selectedSection: string, selectedSubject: string): void { // teacher.class = selectedClass; // teacher.section = selectedSection; // teacher.subject = selectedSubject; // Assign subject // teacher.status = 'Assigned'; // this.saveTeacherData(); // } assignTeachers(selectedClass: string, selectedSection: string, selectedSubjects: string[]): void { this.dataSource.data.forEach(teacher => { if (teacher.selected) { this.assignTeacher(teacher, selectedClass, selectedSection, selectedSubjects); teacher.selected = false; } }); this.saveTeacherData(); this.dataSource.data = [...this.teacherData]; } assignTeacher(teacher: TeacherData, selectedClass: string, selectedSection: string, selectedSubjects: string[]): void { teacher.class = selectedClass; teacher.section = selectedSection; teacher.subjects = selectedSubjects; // Assign subjects array teacher.status = 'Assigned'; this.saveTeacherData(); } openUnassignDialog(teacher: TeacherData): void { const dialogRef = this.dialog.open(ConfirmDialogComponent, { width: '300px', data: { message: 'Do you want to unassign?' } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.unassignTeacher(teacher); } }); } // unassignTeacher(teacher: TeacherData): void { // teacher.class = ''; // teacher.section = ''; // teacher.subject = ''; // Unassign subject // teacher.status = 'Unassigned'; // this.saveTeacherData(); // this.dataSource.data = [...this.teacherData]; // } unassignTeacher(teacher: TeacherData): void { teacher.class = ''; teacher.section = ''; teacher.subjects = []; // Unassign subjects teacher.status = 'Unassigned'; this.saveTeacherData(); this.dataSource.data = [...this.teacherData]; } saveTeacherData(): void { localStorage.setItem('teacherData', JSON.stringify(this.teacherData)); } selectAll(event: any): void { const checked = event.checked; this.dataSource.data.forEach(teacher => { teacher.selected = checked; }); } }
import React from 'react'; import Link from 'next/link'; import { Box, DefaultSectionContainer, DefaultSectionHeader, Heading, SimpleGrid, Text, Wrapper, } from 'boemly'; import { CaretRight } from '@phosphor-icons/react'; import { MEDIUM_TRANSITION_DURATION } from '../../constants/animations'; import strapiLinkUrl from '../../utils/strapiLinkUrl'; import StrapiLink from '../../models/strapi/StrapiLink'; interface LinkCardsGridSlice { tagline?: string; title: string; text?: string; cards: { id: number; title: string; text?: string; link: StrapiLink; }[]; } export interface LinkCardsGridProps { slice: LinkCardsGridSlice; } export const LinkCardsGrid: React.FC<LinkCardsGridProps> = ({ slice, }: LinkCardsGridProps) => ( <DefaultSectionContainer title={slice.title}> <Wrapper> <DefaultSectionHeader tagline={slice.tagline} title={slice.title} text={slice.text} /> <SimpleGrid mt="16" columns={[1, null, null, null, 2]} gap="4"> {slice.cards.map(({ id, title, text, link }) => ( <Box key={id} as={Link} href={strapiLinkUrl(link)} data-testid="link" px="10" py="8" borderStyle="solid" borderWidth="thin" borderColor="gray.200" borderRadius="2xl" display="flex" flexDir="row" alignItems="center" justifyContent="space-between" cursor="pointer" transitionDuration={`${MEDIUM_TRANSITION_DURATION}s`} _hover={{ backgroundColor: 'gray.50' }} > <div> <Heading as="h4" size="lg"> {title} </Heading> {text && ( <Text mt="2" size="smRegularNormal"> {text} </Text> )} </div> <Box display="flex" alignItems="center" justifyContent="center" borderStyle="solid" borderWidth="thin" borderColor="gray.200" borderRadius="2xl" height="12" width="12" minWidth="12" minHeight="12" ml="6" backgroundColor="white" > <CaretRight /> </Box> </Box> ))} </SimpleGrid> </Wrapper> </DefaultSectionContainer> );
import { Expose, plainToClassFromExist } from "class-transformer"; import { IBaseMinimalEntity } from "../../common/base-entities"; export enum FilePolicyEnum { PUBLIC_READ = "public-read", PRIVATE = "private" } export enum FileSectionEnum { GENERAL = "GENERAL", SITE_LOGO = "SITE_LOGO", MAIN_SLIDESHOW = "MAIN_SLIDESHOW", USER = "USER", BLOG = "BLOG", NEWS = "NEWS", BRAND_LOGO = "BRAND_LOGO", PRODUCT = "PRODUCT", COURSE = "COURSE" } export enum ImageSizeCategories { SIZE_75 = "SIZE_75", SIZE_160 = "SIZE_160", SIZE_320 = "SIZE_320", SIZE_480 = "SIZE_480", SIZE_640 = "SIZE_640", SIZE_800 = "SIZE_800", SIZE_1200 = "SIZE_1200", SIZE_1600 = "SIZE_1600", ORIGINAL = "ORIGINAL" } export enum FileStatus { READY = "READY", IN_PROGRESS = "IN_PROGRESS", FAILED = "FAILED" } // Watermark Placement Enum export enum FilesWatermarkPlacementEnum { TOP_RIGHT = "TOP_RIGHT", TOP_CENTER = "TOP_CENTER", TOP_LEFT = "TOP_LEFT", MIDDLE = "MIDDLE", BOTTOM_RIGHT = "BOTTOM_RIGHT", BOTTOM_CENTER = "BOTTOM_CENTER", BOTTOM_LEFT = "BOTTOM_LEFT" } export interface IFileEntity extends IBaseMinimalEntity { key: string; policy: FilePolicyEnum; filename: string; type: string; size: number; status: FileStatus; section: FileSectionEnum; imageSizeCategory?: ImageSizeCategories; originalImage: IFileEntity; generatedImageChildren: IFileEntity[]; thumbnail: string | null; imageAlt: string | null; } export class FileCreateFormValues implements Partial<IFileEntity> { @Expose() key: string = ''; @Expose() policy: FilePolicyEnum = FilePolicyEnum.PUBLIC_READ; @Expose() filename: string = ''; @Expose() type: string = ''; @Expose() size: number = 0; @Expose() section: FileSectionEnum = FileSectionEnum.GENERAL; @Expose() imageAlt: string = ''; constructor ( init?: FileCreateFormValues ) { plainToClassFromExist( this, init, { excludeExtraneousValues: true } ); } } export class FileUpdateFormValues implements Partial<IFileEntity> { @Expose() filename?: string = undefined; @Expose() imageAlt?: string = undefined; @Expose() thumbnail?: string = undefined; constructor ( init?: FileUpdateFormValues ) { plainToClassFromExist( this, init, { excludeExtraneousValues: true } ); } }
<?php namespace App\Http\Livewire\Admin\Reports; use Carbon\Carbon; use Livewire\Component; use App\Models\Customer; use Illuminate\Support\Facades\Auth; use Maatwebsite\Excel\Facades\Excel; use App\Exports\CustomerReportExport; class CustomerReport extends Component { public $start_date,$end_date,$data=[],$search='',$lang; /* render the page */ public function render() { return view('livewire.admin.reports.customer-report'); } /* process before render */ public function mount() { $this->start_date = Carbon::today()->toDateString(); $this->end_date = Carbon::today()->toDateString(); $this->getData(); $this->lang = getTranslation(); if(!Auth::user()->can('customer_report')) { abort(404); } } /* feach customer sales report*/ public function getData() { $query = Customer::latest(); if($this->search != '') { $query = $query->where('name','like','%'.$this->search.'%'); } $query->withSum('invoices','total_amount'); $this->data = $query->get()->toArray(); } public function exportToExcel(){ return Excel::download(new CustomerReportExport($this->data), 'customer-report.xlsx'); } public function exportToPDF(){ return Excel::download(new CustomerReportExport($this->data), 'customer-report.pdf', \Maatwebsite\Excel\Excel::DOMPDF); } }
import { Body, Controller, Delete, Get, Param, Post, Put, Req, UseGuards } from "@nestjs/common"; import { ApiBearerAuth, ApiTags } from "@nestjs/swagger"; import { JwtAuthGuard } from "src/core/authentications/jwt-auth.guard"; import { BaseController } from "src/core/shared/controller/base-controller"; import { CustomRequest } from "src/core/shared/models/request-model"; import { DropdownService } from "src/core/shared/services/dropdown.service"; import { SearchClassroomDto } from "../classroom/classroom.dto"; import { SearchYearTermDto } from "../year-term/year-term.dto"; //import { SearchnullDto } from "src/api/null/null.dto"; import { CreateStudentHomeVisitDto, SearchStudentHomeVisitDto, UpdateStudentHomeVisitDto } from "./student-home-visit.dto"; import { StudentHomeVisitService } from "./student-home-visit.service"; @ApiTags("student-home-visit") @UseGuards(JwtAuthGuard) @ApiBearerAuth() @Controller('student-home-visit') export class StudentHomeVisitController extends BaseController{ constructor(private readonly studenthomevisitService:StudentHomeVisitService, ){ super() } @Get('item/:id') async item(@Param('id') id: number) { try{ return this.success(await this.studenthomevisitService.item(id)) }catch(e){ return this.error(e) } } @Get('item-student/:id') async itemStudent(@Param('id') id: number) { try{ return this.success(await this.studenthomevisitService.itemStudent(id)) }catch(e){ return this.error(e) } } @Post('list') async findAll(@Body() dto: SearchStudentHomeVisitDto) { try{ return this.success(await this.studenthomevisitService.list(dto)) }catch(e){ return this.error(e) } } @Get('current-term') async currentTerm() { try{ return this.success(await this.studenthomevisitService.currentTerm()) }catch(e){ return this.error(e) } } @Get('classroom-dropdown') async classroomDropdown(@Body() dto: SearchClassroomDto) { try{ return this.success(await this.studenthomevisitService.classroomDropdown(dto)) }catch(e){ return this.error(e) } } @Get('classroom-type-dropdown') async classroomTypeDropdown(@Body() dto: SearchClassroomDto) { try{ return this.success(await this.studenthomevisitService.classroomTypeDropdown(dto)) }catch(e){ return this.error(e) } } @Get('year-term-dropdown') async yearTermDropdown(@Body() dto: SearchYearTermDto) { try{ return this.success(await this.studenthomevisitService.yearTermDropdown(dto)) }catch(e){ return this.error(e) } } @Post('create') async create(@Body() dto: CreateStudentHomeVisitDto, @Req() req:CustomRequest,){ try{ return this.success(await this.studenthomevisitService.create(dto,req)) }catch(e){ return this.error(e) } } @Put('update/:id') async update(@Param('id') id: number,@Body() dto: UpdateStudentHomeVisitDto, @Req() req:CustomRequest,){ try{ return this.success(await this.studenthomevisitService.update(id,dto,req)) }catch(e){ return this.error(e) } } @Delete('delete/:id') async delete(@Param('id') id: number, @Req() req:CustomRequest,){ try{ return this.success(await this.studenthomevisitService.delete(id,req)) }catch(e){ return this.error(e) } } // @Get('classroom-dropdown') // async classroomDropdown(@Body() dto: SearchClassroomDto) { // try{ // return this.success(await this.studenthomevisitService.classroomDropdown(dto)) // }catch(e){ // return this.error(e) // } // } // @Get('classroom-type-dropdown') // async classroomTypeDropdown(@Body() dto: SearchClassroomDto) { // try{ // return this.success(await this.studenthomevisitService.classroomTypeDropdown(dto)) // }catch(e){ // return this.error(e) // } // } @Get('student-home-visit-initialData/:id') async getStudentHomeVisitInitialData(@Param('id') id: number) { try{ return this.success(await this.studenthomevisitService.getStudentHomeVisitInitialData(id)) }catch(e){ return this.error(e) } } @Get('get-current-term-data/:id') async getSDQCurrentTermDataPRT(@Param('id') id: number) { try{ return this.success(await this.studenthomevisitService.getCurrentTermData(id)) }catch(e){ return this.error(e) } } @Get('student-home-item/:id') async stditem(@Param('id') id: number) { try{ return this.success(await this.studenthomevisitService.stditem(id)) }catch(e){ return this.error(e) } } }
import React from "react"; import logo from "./logo.svg"; import "./App.css"; import HomePage from "./components/home/HomePage"; import LoginPage from "./components/auth/login/LoginPage"; import RegisterPage from "./components/auth/register/RegisterPage"; import { Route, Routes } from "react-router-dom"; import DefaultLayout from "./components/containers/default/DefaultLayout"; import CategoryCreatePage from "./components/admin/categories/create/CategoryCreatePage"; import AdminLayout from "./components/containers/admin/AdminLayout"; import CategoriesListPage from "./components/admin/categories/list/CategoriesListPage"; import ProductsListPage from "./components/admin/products/list/ProductsListPage"; import ProductCreatePage from "./components/admin/products/create/ProductCreatePage"; import ProductEditPage from "./components/admin/products/edit/ProductEditPage"; import ForbiddenPage from "./pages/403/ForbiddenPage"; const App = () => { return ( <> <Routes> <Route path="/" element={<DefaultLayout />}> <Route index element={<HomePage />} /> <Route path="login" element={<LoginPage />} /> <Route path="register" element={<RegisterPage />} /> </Route> <Route path="/pages"> <Route path="403" element={<ForbiddenPage/>}/> </Route> <Route path="/admin" element={<AdminLayout />}> <Route path="categories/create" element={<CategoryCreatePage />} /> <Route path="categories/list" element={<CategoriesListPage />} /> <Route path="products"> <Route index element={<ProductsListPage />} /> <Route path="create" element={<ProductCreatePage />} /> <Route path="edit"> <Route path=":id" element={<ProductEditPage />} /> </Route> </Route> </Route> </Routes> </> ); }; export default App;
import React, { useEffect, useState } from "react"; import Switch from "react-switch"; import { changeTheme, loadTheme } from "../../utils/theme"; import PropTypes from "prop-types"; import "./estilo.css"; const Header = ({ icon, title }) => { const [checked, setChecked] = useState(false); const handleChange = (nextChecked) => { setChecked(nextChecked); changeTheme(); }; useEffect(() => { setChecked(loadTheme()); }, []); return ( <nav className="Header bg-primary"> <h1> <i className={icon} /> {title} </h1> <Switch onChange={handleChange} checked={checked} className="react-switch" onColor="#888" offColor="#ccc" uncheckedIcon={false} checkedIcon={false} uncheckedHandleIcon={ <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", fontSize: 20, }} > ☀️ </div> } checkedHandleIcon={ <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", color: "red", fontSize: 18, }} > 🌓 </div> } /> </nav> ); }; Header.defaultProps = { title: "Reminders", icon: "fa-solid fa-list-check", }; Header.propTypes = { title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, }; export default Header;
import React, {useContext} from 'react'; import {useSelector, useDispatch} from 'react-redux'; import {toggleTodo} from '../actions/todoActions'; import {FilterContext} from '../contexts/FilterContext'; import withFilter from '../hoc/withFilter'; const TodoList = () => { const todos = useSelector(state => state.todos); const dispatch = useDispatch(); const {filter} = useContext(FilterContext); const filteredTodos = withFilter(todos, filter); const handleToggleTodo = (id) => { dispatch(toggleTodo(id)); }; return ( <ul> {filteredTodos.map(todo => ( <li key = {todo.id} onClick = {() => handleToggleTodo(todo.id)} style = {{textDecoration: todo.completed ? 'line-through' : 'none'}} > {todo.text} </li> ))} </ul> ); }; export default TodoList;
import uuid from datetime import datetime from common.date_utils import get_datetime_from_ts class Client: def __init__(self, client_id: bytes, name: str, password_hash: bytes, last_seen: datetime = None): """ This class represents a client in the AuthServer's memory. Do not confuse with the actual Client code. :param client_id: :param name: :param password_hash: :param last_seen: """ if len(client_id) == 16: self.client_id = client_id else: raise ValueError("Illegal client id") if len(name) <= 255: self.name = name else: raise ValueError("Illegal client name") if len(password_hash) == 32: self.password_hash = password_hash else: raise ValueError("Illegal client password hash") if last_seen is None: last_seen = datetime.now() self.last_seen = last_seen def get_id_string(self): return self.client_id.hex() @classmethod def from_line(cls, line: str): """ This class represents a client in the AuthServer's memory. Do not confuse with the actual Client code. A Client is initialized with a line string of the form: id:name:passwordHash:last_seen and is compatible with the auth server's clients file format :param line: """ parts = line.split(":") if len(parts) != 4: raise ValueError("Illegal client string was found!") line_time = get_datetime_from_ts(parts[3]) client_id = uuid.UUID(parts[0]).bytes return cls(client_id, parts[1], bytes.fromhex(parts[2]), line_time)
SET search_path = clique_bait; -- 2. Digital Analysis -- Using the available datasets - answer the following questions using a single query for each one: -- How many users are there? SELECT COUNT(DISTINCT user_id) FROM users; -- How many cookies does each user have on average? WITH num_cookies_user AS ( SELECT user_id, COUNT(cookie_id) AS num_cookies FROM users GROUP BY user_id ) SELECT AVG(num_cookies) FROM num_cookies_user; -- What is the unique number of visits by all users per month? SELECT EXTRACT(MONTH FROM event_time) AS month, COUNT(DISTINCT visit_id) FROM users u JOIN events e ON u.cookie_id = e.cookie_id GROUP BY month ORDER BY month; -- What is the number of events for each event type? SELECT e.event_type, event_name, COUNT(e.event_type) FROM events e JOIN event_identifier i ON e.event_type = i.event_type GROUP BY e.event_type, event_name ORDER BY e.event_type; -- What is the percentage of visits which have a purchase event? SELECT SUM( CASE WHEN i.event_name = 'Purchase' THEN 1 ELSE 0 END ) :: float / COUNT(DISTINCT visit_id) * 100 AS purchase_percentage FROM users u JOIN events e ON u.cookie_id = e.cookie_id JOIN event_identifier i ON e.event_type = i.event_type; -- What is the percentage of visits which view the checkout page but do not have a purchase event? WITH event_flags AS ( SELECT visit_id, SUM( CASE WHEN event_name = 'Page View' AND page_name = 'Checkout' THEN 1 ELSE 0 END ) AS viewed_checkout, SUM ( CASE WHEN i.event_name = 'Purchase' THEN 1 ELSE 0 END ) AS made_purchase FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id GROUP BY visit_id ) SELECT (SELECT COUNT(*) FROM event_flags WHERE viewed_checkout = 1 AND made_purchase = 0 LIMIT 1) / COUNT(*) :: float * 100 FROM event_flags; -- What are the top 3 pages by number of views? SELECT page_name, COUNT(event_name) AS view_count FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE event_name = 'Page View' GROUP BY page_name ORDER BY view_count DESC LIMIT 3; -- What is the number of views and cart adds for each product category? SELECT product_category, SUM ( CASE WHEN event_name = 'Page View' THEN 1 ELSE 0 END ) AS num_views, SUM ( CASE WHEN event_name = 'Add to Cart' THEN 1 ELSE 0 END ) AS num_add_to_cart FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE product_category IS NOT NULL GROUP BY product_category ORDER BY num_views DESC; -- What are the top 3 products by purchases? WITH purchase_flag AS ( SELECT visit_id FROM events WHERE event_type = 3 ) SELECT page_name, sum( CASE WHEN e.event_type = 2 THEN 1 ELSE 0 END ) AS num_purchases FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id JOIN purchase_flag f ON f.visit_id = e.visit_id WHERE page_name NOT IN('All Products', 'Checkout', 'Confirmation', 'Home Page') GROUP BY page_name ORDER BY num_purchases DESC LIMIT 3; -- 3. Product Funnel Analysis -- Using a single SQL query - create a new output table which has the following details: -- How many times was each product viewed? -- How many times was each product added to cart? -- How many times was each product added to a cart but not purchased (abandoned)? -- How many times was each product purchased? DROP TABLE IF EXISTS product_info; CREATE TABLE product_info AS ( WITH product_views AS ( SELECT e.page_id, COUNT(event_name) AS n_page_views FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE event_name = 'Page View' GROUP BY e.page_id ), add_to_cart AS ( SELECT e.page_id, SUM ( CASE WHEN event_name = 'Add to Cart' THEN 1 ELSE 0 END ) AS n_added_to_cart FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE product_category IS NOT NULL GROUP BY e.page_id ), abandoned AS ( SELECT e.page_id, SUM ( CASE WHEN event_name = 'Add to Cart' THEN 1 ELSE 0 END ) AS abandoned_in_cart FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE product_category IS NOT NULL AND NOT exists( SELECT visit_id FROM events WHERE event_type = 3 AND e.visit_id = visit_id ) GROUP BY e.page_id ), purchased AS ( SELECT e.page_id, SUM ( CASE WHEN e.event_type = '2' THEN 1 ELSE 0 END ) AS purchased_from_cart FROM events e JOIN event_identifier i ON e.event_type = i.event_type JOIN page_hierarchy p ON e.page_id = p.page_id WHERE page_name NOT IN('All Products', 'Checkout', 'Confirmation', 'Home Page') AND EXISTS( SELECT visit_id FROM events WHERE event_type = 3 AND e.visit_id = visit_id ) GROUP BY e.page_id ) SELECT ph.page_id, ph.page_name, ph.product_category, pv.n_page_views, ac.n_added_to_cart, pp.purchased_from_cart, pa.abandoned_in_cart FROM page_hierarchy AS ph JOIN product_views AS pv ON pv.page_id = ph.page_id JOIN purchased AS pp ON pp.page_id = ph.page_id JOIN abandoned AS pa ON pa.page_id = ph.page_id JOIN add_to_cart AS ac ON ac.page_id = ph.page_id ); SELECT * FROM product_info; -- Additionally, create another table which further aggregates the data for the above points -- but this time for each product category instead of individual products. DROP TABLE IF EXISTS category_info; CREATE TABLE category_info AS ( SELECT product_category, sum(n_page_views) AS total_page_view, sum(n_added_to_cart) AS total_added_to_cart, sum(purchased_from_cart) AS total_purchased, sum(abandoned_in_cart) AS total_abandoned FROM product_info GROUP BY product_category ); SELECT * FROM category_info; -- Use your 2 new output tables - answer the following questions: -- Which product had the most views, cart adds and purchases? WITH rankings AS ( SELECT page_name, n_page_views, RANK() OVER(ORDER BY n_page_views DESC) AS page_views_rank, n_added_to_cart, RANK() OVER(ORDER BY n_added_to_cart DESC) AS added_to_cart_rank, purchased_from_cart, RANK() OVER(ORDER BY purchased_from_cart DESC) AS purchased_from_cart_rank, abandoned_in_cart, RANK() OVER(ORDER BY abandoned_in_cart DESC) AS abandoned_in_cart_rank FROM product_info ) SELECT page_name, 'Most Viewed' AS ranking FROM rankings WHERE page_views_rank = 1 UNION SELECT page_name, 'Most Added' AS ranking FROM rankings WHERE added_to_cart_rank = 1 UNION SELECT page_name, 'Most Purchased' AS ranking FROM rankings WHERE purchased_from_cart_rank = 1; -- Which product was most likely to be abandoned? WITH rankings AS ( SELECT page_name, n_page_views, RANK() OVER(ORDER BY n_page_views DESC) AS page_views_rank, n_added_to_cart, RANK() OVER(ORDER BY n_added_to_cart DESC) AS added_to_cart_rank, purchased_from_cart, RANK() OVER(ORDER BY purchased_from_cart DESC) AS purchased_from_cart_rank, abandoned_in_cart, RANK() OVER(ORDER BY abandoned_in_cart DESC) AS abandoned_in_cart_rank FROM product_info ) SELECT page_name FROM rankings WHERE abandoned_in_cart_rank = 1; -- Which product had the highest view to purchase percentage? SELECT page_name, purchased_from_cart / n_page_views :: float * 100 AS purchase_view_percent FROM product_info ORDER BY purchase_view_percent DESC LIMIT 1; -- What is the average conversion rate from view to cart add? SELECT AVG(n_added_to_cart / n_page_views :: float * 100 ) AS cart_conversion FROM product_info; -- What is the average conversion rate from cart add to purchase? SELECT AVG(purchased_from_cart / n_added_to_cart :: float * 100 ) AS purchase_conversion FROM product_info; -- 4. Campaigns Analysis -- Generate a table that has 1 single row for every unique visit_id record and has the following columns: -- user_id -- visit_id -- visit_start_time: the earliest event_time for each visit -- page_views: count of page views for each visit -- cart_adds: count of product cart add events for each visit -- purchase: 1/0 flag if a purchase event exists for each visit -- campaign_name: map the visit to a campaign if the visit_start_time falls between the start_date and end_date -- impression: count of ad impressions for each visit -- click: count of ad clicks for each visit -- (Optional column) cart_products: a comma separated text value with products added to the cart sorted by the order they were added to the cart (hint: use the sequence_number) DROP TABLE IF EXISTS campaign_analysis; CREATE TABLE campaign_analysis AS ( WITH events_users_pages AS ( SELECT visit_id, user_id, events.page_id, page_hierarchy.page_name, events.event_type, event_identifier.event_name, sequence_number, event_time FROM events JOIN users ON users.cookie_id = events.cookie_id JOIN event_identifier ON event_identifier.event_type = events.event_type JOIN page_hierarchy ON page_hierarchy.page_id = events.page_id ORDER BY user_id, visit_id, sequence_number ), cart_items_added AS ( SELECT visit_id, STRING_AGG(page_name, ', ' ORDER BY sequence_number) AS cart_items FROM events JOIN page_hierarchy ON page_hierarchy.page_id = events.page_id WHERE event_type = 2 GROUP BY visit_id ) SELECT events_users_pages.visit_id, user_id, MIN(event_time) AS visit_start_time, SUM( CASE WHEN event_name = 'Page View' THEN 1 ELSE 0 END ) AS page_views, SUM( CASE WHEN event_name = 'Add to Cart' THEN 1 ELSE 0 END ) AS cart_adds, MAX( CASE WHEN event_name = 'Purchase' THEN 1 ELSE 0 END ) AS purchase, (SELECT campaign_name FROM campaign_identifier WHERE MIN(event_time) BETWEEN start_date AND end_date) AS campaign_name, SUM( CASE WHEN event_name = 'Ad Impression' THEN 1 ELSE 0 END ) AS impression, SUM( CASE WHEN event_name = 'Ad Click' THEN 1 ELSE 0 END ) AS click, cart_items FROM events_users_pages LEFT JOIN cart_items_added ON cart_items_added.visit_id = events_users_pages.visit_id GROUP BY events_users_pages.visit_id, user_id, cart_items ORDER BY user_id, visit_id ); SELECT * FROM campaign_analysis; -- Use the subsequent dataset to generate at least 5 insights for the Clique Bait team -- bonus: prepare a single A4 infographic that the team can use for their management reporting sessions, -- be sure to emphasise the most important points from your findings. -- Some ideas you might want to investigate further include: -- Identifying users who have received impressions during each campaign period and comparing each metric -- with other users who did not have an impression event -- Does clicking on an impression lead to higher purchase rates? -- What is the uplift in purchase rate when comparing users who click on a campaign impression versus -- users who do not receive an impression? What if we compare them with users who just an impression but do not click? SELECT impression, click, COUNT(DISTINCT visit_id) AS total_visits, COUNT(DISTINCT user_id) AS total_users, SUM(page_views) AS total_views, SUM(cart_adds) AS total_cart_adds, SUM(purchase) AS total_purchases, SUM(purchase) / COUNT(DISTINCT visit_id) :: float * 100 AS purchase_visit_ratio FROM campaign_analysis GROUP BY impression, click; -- What metrics can you use to quantify the success or failure of each campaign compared to each other? SELECT campaign_name, COUNT(DISTINCT visit_id) AS total_visits, COUNT(DISTINCT user_id) AS total_users, SUM(page_views) AS total_views, SUM(cart_adds) AS total_cart_adds, SUM(purchase) AS total_purchases, SUM(purchase) / COUNT(DISTINCT visit_id) :: float * 100 AS purchase_visit_ratio, SUM(cart_adds)/ SUM(page_views) :: float * 100 AS cart_conversion_ratio, SUM(purchase) / SUM(cart_adds) :: float * 100 AS purchase_conversion_ratio FROM campaign_analysis GROUP BY campaign_name ORDER BY purchase_visit_ratio DESC;
--gotta creat this type firt CREATE OR REPLACE TYPE activity_result AS OBJECT ( max_activities_day VARCHAR2(20), max_activities_count NUMBER, min_activities_day VARCHAR2(20), min_activities_count NUMBER ); ---------------the function ---------------- CREATE OR REPLACE FUNCTION find_activities(start_date_param DATE, end_date_param DATE) RETURN activity_result AS max_activities_day VARCHAR2(20); max_activities_count NUMBER; min_activities_day VARCHAR2(20); min_activities_count NUMBER; result activity_result; BEGIN BEGIN SELECT day_of_week, activity_count INTO max_activities_day, max_activities_count FROM ( SELECT TO_CHAR(start_date AT TIME ZONE 'UTC', 'DAY') AS day_of_week, COUNT(*) AS activity_count FROM activities WHERE start_date >= start_date_param AND start_date <= end_date_param GROUP BY TO_CHAR(start_date AT TIME ZONE 'UTC', 'DAY') ORDER BY activity_count DESC ) WHERE ROWNUM = 1; EXCEPTION WHEN NO_DATA_FOUND THEN max_activities_day := NULL; max_activities_count := 0; END; BEGIN SELECT day_of_week, activity_count INTO min_activities_day, min_activities_count FROM ( SELECT TO_CHAR(start_date AT TIME ZONE 'UTC', 'DAY') AS day_of_week, COUNT(*) AS activity_count FROM activities WHERE start_date >= start_date_param AND start_date <= end_date_param GROUP BY TO_CHAR(start_date AT TIME ZONE 'UTC', 'DAY') ORDER BY activity_count ASC ) WHERE ROWNUM = 1; EXCEPTION WHEN NO_DATA_FOUND THEN min_activities_day := NULL; min_activities_count := 0; END; -- Assign values to the result object result := activity_result(max_activities_day, max_activities_count, min_activities_day, min_activities_count); RETURN result; -- Return the result object END; -----------------calling the function ---------------- DECLARE start_date_param DATE := TO_DATE('2023-01-01', 'YYYY-MM-DD'); end_date_param DATE := TO_DATE('2023-12-31', 'YYYY-MM-DD'); result_activity activity_result; BEGIN result_activity := find_activities(start_date_param, end_date_param); DBMS_OUTPUT.PUT_LINE('Day with most activities: ' || result_activity.max_activities_day || ', Activities Count: ' || result_activity.max_activities_count); DBMS_OUTPUT.PUT_LINE('Day with least activities: ' || result_activity.min_activities_day || ', Activities Count: ' || result_activity.min_activities_count); END; /
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAdressesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('adresses', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); $table->string('cep'); $table->string('patio'); $table->string('district'); $table->string('complement')->nullable(); $table->string('number')->nullable(); $table->string('city'); $table->string('state'); $table->boolean('fav')->default(false); $table->unsignedBigInteger('client_id'); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('adresses'); } }
import React from 'react'; import './Message.css' class Message extends React.Component { constructor() { super(); this.state = { isLiked: false, counter: 0 }; this.handleClick = this.handleClick.bind(this) } handleClick() { const { isLiked, counter } = this.state; this.setState( {isLiked: !isLiked, counter: counter +1}); } render() { const { name, logo, title, text } = this.props; const { isLiked, counter } = this.state; const date = new Date(); const displayDate = `${date.getDate()}/${date.getMonth() +1}/${date.getFullYear()}` const btnClassName = `message-header-button ${isLiked ? 'is-active' : ''}` return ( <div className="message"> <div className="message-header"> <img src={logo} alt="" className="message-header-image" /> <div className="message-header-text_block"> <p className="message-header-title"> {name} </p> <span className="message-header-date"> {displayDate} </span> </div> <span className="message-header-counter"> {counter} </span> <button className={btnClassName} onClick={this.handleClick} /> </div> <div className="message-body"> <h2 className="message-body-title"> {title} </h2> <p className="message-body-content"> {text} </p> </div> </div> ); } } export default Message;
using UnityEngine; [NodeToolTip("Randomly sets the value of a Int variable.")] [NodeCopyright("Copyright 2011 by Detox Studios LLC")] [NodePath("Actions/Variables/Int")] [NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")] [NodeHelp("http://www.uscript.net/docs/index.php?title=Node_Reference_Guide#Set_Random_Int")] [FriendlyName("Set Random Int", "Randomly sets the value of a Int variable.")] public class uScriptAct_SetRandomInt : uScriptLogic { public bool Out { get { return true; } } public void In([SocketState(false, false)][FriendlyName("Min", "Minimum allowable integer value.")] int Min, [FriendlyName("Max", "Maximum allowable integer value. This value is inclusive and may be returned.")][SocketState(false, false)] int Max, [FriendlyName("Target Int", "The integer value that gets set.")] out int TargetInt) { if (Min > Max) { Min = Max; } TargetInt = Random.Range(Min, Max + 1); } }
<!DOCTYPE html> <html> <head> <title>Random Password Generator</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-image: url('bg.jpg'); background-size: cover; background-repeat: no-repeat; backdrop-filter: blur(5px); background-attachment: fixed; display: flex; justify-content: center; align-items: center; height: 100vh; } .mainbox { border: 2px solid black; border-radius: 10px; width: 400px; padding: 20px; background-color: rgba(255, 255, 255, 0.8); } #heading { text-align: center; color: black; font-weight: bold; margin-bottom: 20px; } #input_text { font-size: 18px; margin-bottom: 10px; } #passwordLength { width: 60px; height: 25px; margin-bottom: 10px; } #generateButton { display: block; margin: 0 auto; margin-bottom: 20px; padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; } #randomPassword { font-size: 18px; text-align: center; } .home-button { position: absolute; top: 10px; left: 10px; padding: 10px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; text-decoration: none; } </style> </head> <body> <a href="home.html" class="home-button">Home</a> <div class="mainbox"> <h1 id="heading">Random Password Generator</h1> <label for="passwordLength" id="input_text">Password Length:</label> <input type="number" id="passwordLength" value="12"><br> <button id="generateButton">Generate Password</button> <p id="randomPassword"></p> </div> <script> document.getElementById("generateButton").addEventListener("click", function () { const passwordLength = parseInt(document.getElementById("passwordLength").value, 10); const randomPassword = generateRandomPassword(passwordLength); document.getElementById("randomPassword").textContent = "Random Password: " + randomPassword; }); function generateRandomPassword(length) { const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+"; const randomPasswordArray = []; for (let i = 0; i < length; i++) { const randomIndex = Math.floor(Math.random() * characters.length); const randomChar = characters.charAt(randomIndex); randomPasswordArray.push(randomChar); } return randomPasswordArray.join(""); } </script> </body> </html>
package net.marsh.tutorialmod.block; import net.marsh.tutorialmod.TutorialMod; import net.marsh.tutorialmod.block.custom.GemInfusingStationBlock; import net.marsh.tutorialmod.block.custom.JumpyBlock; import net.marsh.tutorialmod.block.custom.ZirconLampBlock; import net.marsh.tutorialmod.fluid.ModFluidTypes; import net.marsh.tutorialmod.fluid.ModFluids; import net.marsh.tutorialmod.item.ModCreativeModeTab; import net.marsh.tutorialmod.item.ModItems; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.DropExperienceBlock; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.material.Material; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Supplier; public class ModBlocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, TutorialMod.MOD_ID); public static final RegistryObject<Block> ZIRCON_BLOCK = registerBlock("zircon_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE) .strength(6f).requiresCorrectToolForDrops()), ModCreativeModeTab.TUTORIAL_TAB); public static final RegistryObject<Block> ZIRCON_ORE = registerBlock("zircon_ore", () -> new DropExperienceBlock(BlockBehaviour.Properties.of(Material.STONE) .strength(6f).requiresCorrectToolForDrops(), UniformInt.of(3, 7)), ModCreativeModeTab.TUTORIAL_TAB); public static final RegistryObject<Block> DEEPSLATE_ZIRCON_ORE = registerBlock("deepslate_zircon_ore", () -> new DropExperienceBlock(BlockBehaviour.Properties.of(Material.STONE) .strength(6f).requiresCorrectToolForDrops(), UniformInt.of(3, 7)), ModCreativeModeTab.TUTORIAL_TAB); public static final RegistryObject<Block> JUMPY_BLOCK = registerBlock("jumpy_block", () -> new JumpyBlock(BlockBehaviour.Properties.of(Material.STONE) .strength(6f).requiresCorrectToolForDrops()), ModCreativeModeTab.TUTORIAL_TAB); public static final RegistryObject<Block> ZIRCON_LAMP = registerBlock("zircon_lamp", () -> new ZirconLampBlock(BlockBehaviour.Properties.of(Material.STONE) .strength(6f).requiresCorrectToolForDrops() .lightLevel(state -> state.getValue(ZirconLampBlock.LIT) ? 15 : 0)), ModCreativeModeTab.TUTORIAL_TAB); public static final RegistryObject<LiquidBlock> SOAP_WATER_BLOCK = BLOCKS.register("soap_water_block", () -> new LiquidBlock(ModFluids.SOURCE_SOAP_WATER, BlockBehaviour.Properties.copy(Blocks.WATER))); public static final RegistryObject<Block> GEM_INFUSING_STATION = registerBlock("gem_infusing_station", () -> new GemInfusingStationBlock(BlockBehaviour.Properties.of(Material.METAL) .strength(6f).requiresCorrectToolForDrops().noOcclusion()), ModCreativeModeTab.TUTORIAL_TAB); private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block, CreativeModeTab tab) { RegistryObject<T> toReturn = BLOCKS.register(name, block); registerBlockItem(name, toReturn, tab); return toReturn; } private static <T extends Block> RegistryObject<Item> registerBlockItem(String name, RegistryObject<T> block, CreativeModeTab tab) { return ModItems.ITEMS.register(name, () -> new BlockItem(block.get(), new Item.Properties().tab(tab))); } public static void register(IEventBus eventBus) { BLOCKS.register(eventBus); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ppdbs', function (Blueprint $table) { $table->id(); $table->uuid('uuid')->unique(); $table->string('name'); $table->string('email')->unique(); $table->string('nisn')->unique(); $table->string('asal_sekolah'); $table->string('alamat'); $table->string('telpon_siswa'); $table->string('jenis_kelamin'); $table->string('tempat_lahir'); $table->string('tanggal_lahir'); $table->string('nama_ayah')->nullable(); $table->string('nama_ibu')->nullable(); $table->string('telpon_orang_tua')->nullable(); $table->string('tahun_daftar'); $table->string('bukti_pendaftaran'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ppdbs'); } };
import React from 'react'; import {render} from '../../../tests/test-utils'; import {ImplicitAttributeCondition} from '../ImplicitAttributeCondition'; import {AbbreviationType, PROPERTY_NAMES, SimpleSelectProperty} from '../../../models'; import {waitFor} from '@testing-library/react'; import mockedScopes from '../../../tests/fixtures/scopes'; describe('ImplicitAttributeCondition', () => { it('should render implicit attribute localizable and scopable conditions', async () => { mockSimpleSelectCalls({localizable: true, scopable: true}); const property: SimpleSelectProperty = { type: PROPERTY_NAMES.SIMPLE_SELECT, attributeCode: 'brand', process: {type: AbbreviationType.NO}, scope: 'ecommerce', locale: 'en_US', }; const screen = render( <table> <tbody> <ImplicitAttributeCondition attributeCode={property.attributeCode} scope={property.scope} locale={property.locale} /> </tbody> </table> ); await waitFor(() => expect(screen.getByText('Simple select')).toBeInTheDocument()); await waitFor(() => expect(screen.getByPlaceholderText('pim_common.channel')).toBeInTheDocument()); await waitFor(() => expect(screen.getByText('Ecommerce')).toBeInTheDocument()); await waitFor(() => expect(screen.getByPlaceholderText('pim_common.locale')).toBeInTheDocument()); await waitFor(() => expect(screen.getByText('English (United States)')).toBeInTheDocument()); }); it('should render implicit simple select non localizable and non scopable', async () => { mockSimpleSelectCalls(); const property: SimpleSelectProperty = { type: PROPERTY_NAMES.SIMPLE_SELECT, attributeCode: 'brand', process: {type: AbbreviationType.NO}, }; const screen = render( <table> <tbody> <ImplicitAttributeCondition attributeCode={property.attributeCode} scope={property.scope} locale={property.locale} /> </tbody> </table> ); await waitFor(() => expect(screen.getByText('Simple select')).toBeInTheDocument()); expect(screen.queryByPlaceholderText('pim_common.channel')).not.toBeInTheDocument(); expect(screen.queryByPlaceholderText('pim_common.locale')).not.toBeInTheDocument(); }); }); const mockSimpleSelectCalls = ({localizable = false, scopable = false, inError = false, errorStatus = ''} = {}) => { const fetchImplementation = jest.fn().mockImplementation((requestUrl: string, args: {method: string}) => { if (requestUrl === 'akeneo_identifier_generator_get_attribute_options') { return Promise.resolve({ ok: true, json: () => Promise.resolve([ {code: 'option_a', labels: {en_US: 'OptionA'}}, {code: 'option_b', labels: {en_US: 'OptionB'}}, {code: 'option_c', labels: {en_US: 'OptionC'}}, {code: 'option_d', labels: {en_US: 'OptionD'}}, {code: 'option_e', labels: {en_US: 'OptionE'}}, ]), statusText: '', status: 200, } as Response); } else if (requestUrl === 'pim_enrich_channel_rest_index') { return Promise.resolve({ ok: true, json: () => Promise.resolve(mockedScopes), statusText: '', status: 200, } as Response); } else if (requestUrl === 'pim_enrich_attribute_rest_get') { if (inError) { jest.spyOn(console, 'error'); // eslint-disable-next-line no-console (console.error as jest.Mock).mockImplementation(() => null); return Promise.resolve({ ok: false, json: () => Promise.resolve(), statusText: errorStatus, status: Number.parseFloat(errorStatus), } as Response); } else { return Promise.resolve({ ok: true, json: () => Promise.resolve({ code: 'simple_select', labels: {en_US: 'Simple select', fr_FR: 'Select simple'}, localizable, scopable, }), statusText: '', status: 200, } as Response); } } throw new Error(`Unmocked url "${requestUrl}" [${args.method}]`); }); jest.spyOn(global, 'fetch').mockImplementation(fetchImplementation); };