text
stringlengths
184
4.48M
namespace Ellabit.Challenges { public class Challenge072Amazingellabit : IChallenge, IChallengeBlockly, IChallengeTestCode { public string? Header { get; set; } = "Amazing ellabit!"; public string? Code { get; set; } = @" using System; namespace Ellabit { public class Challenge { public string AmazingEllabit(string str) { } } }"; public string? TestCode { get; set; } = @" using System; namespace Ellabit { public class TestChallenge { public (bool pass, string message) Test1() { var tmp = new Challenge(); string sumResult; try { sumResult = tmp.AmazingEllabit(""ellabit is amazing.""); } catch (Exception ex) { return (false, ex.ToString() + "" "" + ex.Message); } return (sumResult == ""ellabit is amazing."", $""returned: {sumResult} expected: ellabit is amazing.""); } public (bool pass, string message) Test2() { var tmp = new Challenge(); string sumResult; try { sumResult = tmp.AmazingEllabit(""Mubashir is amazing.""); } catch (Exception ex) { return (false, ex.ToString() + "" "" + ex.Message); } return (sumResult == ""Mubashir is not amazing."", $""returned: {sumResult} expected: Mubashir is not amazing.""); } public (bool pass, string message) Test3() { var tmp = new Challenge(); string sumResult; try { sumResult = tmp.AmazingEllabit(""Infinity is amazing.""); } catch (Exception ex) { return (false, ex.ToString() + ""\n"" + ex.Message); } return (sumResult == ""Infinity is not amazing."", $""returned: {sumResult} expected: Infinity is not amazing.""); } } }"; public string? Description { get; set; } = @"Create a function that takes a string and changes the word amazing to not amazing. Return the string without any change if the word ellabit is part of the string. <h5>Examples</h5> <code> <p style = ""border:1px solid grey; padding: 10px;"" > AmazingEllabit(""ellabit is amazing."") ➞ ""ellabit is amazing."" AmazingEllabit(""Mubashir is amazing."") ➞ ""Mubashir is not amazing."" AmazingEllabit(""Infinity is amazing."") ➞ ""Infinity is not amazing."" </p> </code> Notes Ellabit is amazing :)"; public List<string> Tests { get; set; } = new string[] { "Test1", "Test2", "Test3" }.ToList(); private Dictionary<string, string> _tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Logic", "If and Else If" }, { "Level", "2" } }; public Dictionary<string, string> Tags { get => _tags; set => _tags = value; } public bool ShowBlockly { get => true; } } }
// 实现数组的响应式 // 对原有的数组方法实现一个更新通知 const orginalProto = Array.prototype; // 备份一个新的数组原型/克隆一份,修改备份 const arrayProto = Object.create(orginalProto); // 1:替换数组原型中呐7个方法 ['push','pop','shift','unshift'].forEach(method => { // 对备份原型上的数组方法进行覆盖 arrayProto[method] = function(){ // 覆盖之前进行原始的数组操作 orginalProto[method].apply(this,arguments) // 通知更新 console.log("数组执行:"+method+' 操作'); } }) // js中监听数据变更需要Object.defineProperty()函数 // 给一个obj定义一个响应式的属性 // 先定义一个defineReactive函数 function defineReactive(obj, key, val) { // 递归 //2 val如果是个对象,就需要递归处理 observe(val) // 利用get/set来对obj进行拦截 Object.defineProperty(obj, key, { get() { // 日志记录 console.log("get", key); // 返回当前对象对应属性的值 return val; }, set(newVal) { if (newVal !== val) { console.log("set", key); val = newVal; // 3新值如果是对象,仍然需要递归遍历处理 observe(newVal) // update() } }, }); } // 实际开发中一个对象可能有多个属性,这时候不能一次次去执行defineReactive() // 需要自动化处理这种情况,遍历obj的所有属性,给每个key都实现响应式 // 遍历响应式处理 function observe(obj) { // typeof 判断如果返回非对象或者是null,那么可以判断obj是基本数据类型 // 不做处理 if (typeof obj !== "object" || obj == null) { return obj; } // 判断传入obj类型,做相应处理 if (Array.isArray(obj)) { // todo,设置下obj的原型 // 覆盖实例原型,替换7个变更操作 obj.__proto__ = arrayProto // 对数组内部元素执行响应化处理 const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { // 如果传入的obj数组中有其他的数组和对象,则需要进行递归处理 observe(obj[i]) } } else { // 2要处理的一定是对象object Object.keys(obj).forEach((key) => defineReactive(obj, key, obj[key])); } } // 4 function set(obj, key, val) { defineReactive(obj, key, val) } //----------------------------test------------------------- //1 简单数据 const obj2 = {} // 测试下响应式拦截函数 defineReactive(obj2,'foo','foo') // obj2.foo //2 复杂数据类型 const obj = { foo: 'foo', bar: 'bar', baz: { n: 1 } }; // defineReactive(obj, "foo", "foo"); observe(obj) // obj.foo; // 3新值是对象的类型,需要进行响应式处理 obj.baz = { n: 10 } // 可以正常拦截复杂数据 obj.baz.n // 4复杂数据类型添加新的属性 // obj.dong = 'dong' // 由于新的属性没有进行响应式处理,所以需要一个set方法 set(obj, 'dong', 'dong') obj.dong const arr = [1,2,3,40] arr.push(5) console.log(arr)
import React, { useState } from "react"; import Navbar from "./Components/Navbar/Navbar"; import { Route, Routes } from "react-router-dom"; import Card from "./Pages/Card/Card"; import PlaceOrder from "./Pages/PlaceOrder/PlaceOrder"; import Home from "./Pages/Home/Home"; import Footer from "./Components/Footer/Footer"; import LogginPopUp from "./Components/LogginPopUp/LogginPopUp"; const App = () => { const [showLogin, setShowLogin] = useState(false); return ( <> {showLogin ? <LogginPopUp setShowLogin={setShowLogin} /> : <></>} <div className="app"> <Navbar setShowLogin={setShowLogin} /> <Routes> <Route path="/" element={<Home />} /> <Route path="/cart" element={<Card />}></Route> <Route path="/order" element={<PlaceOrder />} /> </Routes> </div> <Footer /> </> ); }; export default App;
import React, { createContext, useEffect, useState } from 'react'; import app from '../firebase/firebase.config'; import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, sendEmailVerification, signInWithEmailAndPassword, signOut, getRedirectResult } from 'firebase/auth'; // Initialize Firebase app export const AuthContext = createContext(); const auth = getAuth(app); const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true) const [emailVerificationSent, setEmailVerificationSent] = useState(false); const createUser = (email, password) => { setLoading(true); return createUserWithEmailAndPassword(auth, email, password) }; const handleEmailVerification = (user) => { return sendEmailVerification(user) .then(() => { setEmailVerificationSent(true); }) .catch((error) => { console.log(error); }); }; const signIn = (email, password) => { setLoading(true); return signInWithEmailAndPassword(auth, email, password) } const updateUser = (userInfo) => { return updateProfile(user, userInfo); } const logOut = () => { setLoading(true); return signOut(auth); } // useEffect(() => { // const unsubscribe = onAuthStateChanged(auth, currentUser => { // setUser(currentUser) // setLoading(false); // }); // return () => unsubscribe(); // }, []) useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (currentUser) => { if (currentUser) { getRedirectResult(auth) .then((result) => { if (result.user) { setUser(result.user); } }) .catch((error) => { console.log(error); }); } else { setUser(null); } setLoading(false); }); return () => unsubscribe(); }, []); const authInfo = { createUser, handleEmailVerification, emailVerificationSent, signIn, updateUser, logOut, user, loading }; return ( <AuthContext.Provider value={authInfo}> {children} </AuthContext.Provider> ); }; export default AuthProvider;
/* * ProFTPD - mod_proxy testsuite * Copyright (c) 2013-2022 TJ Saunders <tj@castaglia.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, TJ Saunders and other respective copyright holders * give permission to link this program with OpenSSL, and distribute the * resulting executable, without including the source code for OpenSSL in the * source distribution. */ /* Reverse-proxy API tests */ #include "tests.h" extern xaset_t *server_list; static pool *p = NULL; static const char *test_dir = "/tmp/mod_proxy-test-reverse"; static const char *test_file = "/tmp/mod_proxy-test-reverse/servers.json"; static config_rec *policy_config = NULL; static void create_main_server(void) { server_rec *s; s = pr_parser_server_ctxt_open("127.0.0.1"); s->ServerName = "Test Server"; main_server = s; } static void test_cleanup(pool *cleanup_pool) { (void) unlink(test_file); (void) tests_rmpath(cleanup_pool, test_dir); } static FILE *test_prep(void) { int res; mode_t perms; FILE *fh; perms = 0770; res = mkdir(test_dir, perms); if (res < 0 && errno != EEXIST) { ck_assert_msg(res == 0, "Failed to create tmp directory '%s': %s", test_dir, strerror(errno)); } res = chmod(test_dir, perms); ck_assert_msg(res == 0, "Failed to set perms %04o on directory '%s': %s", perms, test_dir, strerror(errno)); fh = fopen(test_file, "w+"); ck_assert_msg(fh != NULL, "Failed to create tmp file '%s': %s", test_file, strerror(errno)); perms = 0660; res = chmod(test_file, perms); ck_assert_msg(res == 0, "Failed to set perms %04o on file '%s': %s", perms, test_file, strerror(errno)); return fh; } static void set_up(void) { if (p == NULL) { p = permanent_pool = session.pool = make_sub_pool(NULL); main_server = NULL; server_list = NULL; session.c = NULL; session.notes = NULL; } test_cleanup(p); init_config(); init_fs(); init_netaddr(); init_netio(); init_inet(); server_list = xaset_create(p, NULL); pr_parser_prepare(p, &server_list); create_main_server(); proxy_db_init(p); if (getenv("TEST_VERBOSE") != NULL) { pr_trace_set_levels("netio", 1, 20); pr_trace_set_levels("proxy.conn", 1, 20); pr_trace_set_levels("proxy.db", 1, 20); pr_trace_set_levels("proxy.reverse", 1, 20); pr_trace_set_levels("proxy.tls", 1, 20); pr_trace_set_levels("proxy.uri", 1, 20); pr_trace_set_levels("proxy.ftp.ctrl", 1, 20); pr_trace_set_levels("proxy.ftp.sess", 1, 20); } pr_inet_set_default_family(p, AF_INET); } static void tear_down(void) { pr_inet_set_default_family(p, 0); if (getenv("TEST_VERBOSE") != NULL) { pr_trace_set_levels("netio", 0, 0); pr_trace_set_levels("proxy.conn", 0, 0); pr_trace_set_levels("proxy.db", 0, 0); pr_trace_set_levels("proxy.reverse", 0, 0); pr_trace_set_levels("proxy.tls", 0, 0); pr_trace_set_levels("proxy.uri", 0, 0); pr_trace_set_levels("proxy.ftp.ctrl", 0, 0); pr_trace_set_levels("proxy.ftp.sess", 0, 0); } pr_inet_clear(); pr_parser_cleanup(); proxy_db_free(); test_cleanup(p); if (p) { destroy_pool(p); p = permanent_pool = session.pool = NULL; main_server = NULL; server_list = NULL; session.c = NULL; session.notes = NULL; } } START_TEST (reverse_free_test) { int res; res = proxy_reverse_free(NULL); ck_assert_msg(res < 0, "Failed to handle null pool"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); } END_TEST START_TEST (reverse_init_test) { int res, flags = PROXY_DB_OPEN_FL_SKIP_VACUUM; FILE *fh; res = proxy_reverse_init(NULL, NULL, flags); ck_assert_msg(res < 0, "Failed to handle null pool"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); res = proxy_reverse_init(p, NULL, flags); ck_assert_msg(res < 0, "Failed to handle null tables dir"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); fh = test_prep(); fclose(fh); mark_point(); res = proxy_reverse_init(p, test_dir, flags); ck_assert_msg(res == 0, "Failed to init Reverse API resources: %s", strerror(errno)); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_sess_free_test) { int res; mark_point(); res = proxy_reverse_sess_free(p, NULL); ck_assert_msg(res == 0, "Failed to free Reverse API session resources: %s", strerror(errno)); } END_TEST START_TEST (reverse_sess_init_test) { int res, flags = PROXY_DB_OPEN_FL_SKIP_VACUUM; config_rec *c; array_header *backends; const char *uri; const struct proxy_conn *pconn; mark_point(); res = proxy_reverse_sess_init(NULL, NULL, NULL, flags); ck_assert_msg(res < 0, "Failed to handle null pool"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); mark_point(); res = proxy_reverse_sess_init(p, NULL, NULL, flags); ck_assert_msg(res < 0, "Unexpectedly init'd Reverse API session resources"); ck_assert_msg(errno == EPERM, "Expected EPERM (%d), got '%s' (%d)", EPERM, strerror(errno), errno); c = add_config_param("ProxyReverseServers", 2, NULL, NULL); backends = make_array(c->pool, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(c->pool, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; c->argv[0] = backends; c = add_config_param("ProxyReverseServers", 2, NULL, NULL); backends = make_array(c->pool, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:2121"; pconn = proxy_conn_create(c->pool, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; c->argv[0] = backends; mark_point(); res = proxy_reverse_sess_init(NULL, NULL, NULL, flags); ck_assert_msg(res < 0, "Unexpectedly init'd Reverse API session resources"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); mark_point(); res = proxy_reverse_sess_free(p, NULL); ck_assert_msg(res == 0, "Failed to free Reverse API session resources: %s", strerror(errno)); } END_TEST static int test_connect_policy(int policy_id, array_header *src_backends) { int flags = PROXY_DB_OPEN_FL_SKIP_VACUUM; FILE *fh; config_rec *c; array_header *backends; fh = test_prep(); fclose(fh); mark_point(); if (policy_config != NULL) { c = policy_config; } else { policy_config = c = add_config_param("ProxyReverseConnectPolicy", 1, NULL); c->argv[0] = palloc(c->pool, sizeof(int)); } *((int *) c->argv[0]) = policy_id; mark_point(); c = add_config_param("ProxyReverseServers", 2, NULL, NULL); backends = make_array(c->pool, 1, sizeof(struct proxy_conn *)); if (src_backends == NULL) { const char *uri; const struct proxy_conn *pconn; uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(c->pool, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; } else { array_cat(backends, src_backends); } c->argv[0] = backends; mark_point(); return proxy_reverse_init(p, test_dir, flags); } START_TEST (reverse_connect_policy_random_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_RANDOM, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy Random: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_roundrobin_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_ROUND_ROBIN, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy RoundRobin: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_leastconns_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_LEAST_CONNS, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy LeastConns: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_leastresponsetime_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_LEAST_RESPONSE_TIME, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy LeastResponseTime: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_shuffle_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_SHUFFLE, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy Shuffle: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_peruser_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_PER_USER, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy PerUser: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_pergroup_test) { int res; /* Note: This should fail without having the UseReverseProxyAuth ProxyOption * enabled. */ res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_PER_GROUP, NULL); ck_assert_msg(res < 0, "Expected ReverseConnectPolicy PerGroup to fail"); ck_assert_msg(errno == EPERM, "Expected EPERM (%d), got %s (%d)", EPERM, strerror(errno), errno); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST START_TEST (reverse_connect_policy_perhost_test) { int res; res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_PER_HOST, NULL); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy PerHost: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); test_cleanup(p); } END_TEST static void test_handle_user_pass(int policy_id, array_header *src_backends) { int res, successful = FALSE, block_responses = FALSE; int flags = PROXY_DB_OPEN_FL_SKIP_VACUUM; struct proxy_session *proxy_sess; cmd_rec *cmd; FILE *fh; fh = test_prep(); fclose(fh); mark_point(); res = test_connect_policy(PROXY_REVERSE_CONNECT_POLICY_RANDOM, src_backends); ck_assert_msg(res == 0, "Failed to test ReverseConnectPolicy Random: %s", strerror(errno)); proxy_sess = (struct proxy_session *) proxy_session_alloc(p); session.notes = pr_table_alloc(p, 0); pr_table_add(session.notes, "mod_proxy.proxy-session", proxy_sess, sizeof(struct proxy_session)); session.c = pr_inet_create_conn(p, -1, NULL, INPORT_ANY, FALSE); ck_assert_msg(session.c != NULL, "Failed to open session control conn: %s", strerror(errno)); session.c->local_addr = session.c->remote_addr = pr_netaddr_get_addr(p, "127.0.0.1", NULL); ck_assert_msg(session.c->remote_addr != NULL, "Failed to get address: %s", strerror(errno)); mark_point(); res = proxy_reverse_sess_init(p, test_dir, proxy_sess, flags); ck_assert_msg(res == 0, "Failed to init Reverse API session resources: %s", strerror(errno)); cmd = pr_cmd_alloc(p, 2, "USER", "anonymous"); cmd->arg = pstrdup(p, "anonymous"); mark_point(); res = proxy_reverse_handle_user(cmd, proxy_sess, &successful, &block_responses); ck_assert_msg(res == 1, "Failed to handle USER"); cmd = pr_cmd_alloc(p, 2, "PASS", "ftp@nospam.org"); cmd->arg = pstrdup(p, "ftp@nospam.org"); mark_point(); res = proxy_reverse_handle_pass(cmd, proxy_sess, &successful, &block_responses); ck_assert_msg(res < 0, "Handled PASS unexpectedly"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got %s (%d)", EINVAL, strerror(errno), errno); mark_point(); res = proxy_reverse_sess_exit(p); ck_assert_msg(res == 0, "Failed to exit session: %s", strerror(errno)); mark_point(); res = proxy_reverse_free(p); ck_assert_msg(res == 0, "Failed to free Reverse API resources: %s", strerror(errno)); proxy_session_free(p, proxy_sess); test_cleanup(p); } START_TEST (reverse_handle_user_pass_random_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_RANDOM, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_RANDOM, backends); } END_TEST START_TEST (reverse_handle_user_pass_roundrobin_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_ROUND_ROBIN, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_ROUND_ROBIN, backends); } END_TEST START_TEST (reverse_handle_user_pass_leastconns_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_LEAST_CONNS, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_LEAST_CONNS, backends); } END_TEST START_TEST (reverse_handle_user_pass_leastresponsetime_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_LEAST_RESPONSE_TIME, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_LEAST_RESPONSE_TIME, backends); } END_TEST START_TEST (reverse_handle_user_pass_shuffle_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_SHUFFLE, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_SHUFFLE, backends); } END_TEST START_TEST (reverse_handle_user_pass_peruser_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_USER, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_USER, backends); } END_TEST START_TEST (reverse_handle_user_pass_pergroup_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_GROUP, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_GROUP, backends); } END_TEST START_TEST (reverse_handle_user_pass_perhost_test) { const char *uri; const struct proxy_conn *pconn; array_header *backends; /* Skip this test on CI builds, for now. It fails unexpectedly. */ if (getenv("CI") != NULL || getenv("TRAVIS") != NULL) { return; } backends = make_array(p, 1, sizeof(struct proxy_conn *)); uri = "ftp://127.0.0.1:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; uri = "ftp://ftp.microsoft.com:21"; pconn = proxy_conn_create(p, uri, 0); *((const struct proxy_conn **) push_array(backends)) = pconn; test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_HOST, backends); test_handle_user_pass(PROXY_REVERSE_CONNECT_POLICY_PER_HOST, backends); } END_TEST START_TEST (reverse_json_parse_uris_args_test) { array_header *uris; const char *path; uris = proxy_reverse_json_parse_uris(NULL, NULL, 0); ck_assert_msg(uris == NULL, "Failed to handle null arguments"); ck_assert_msg(errno == EINVAL, "Failed to set errno to EINVAL"); uris = proxy_reverse_json_parse_uris(p, NULL, 0); ck_assert_msg(uris == NULL, "Failed to handle null path argument"); ck_assert_msg(errno == EINVAL, "Failed to set errno to EINVAL"); path = "/tmp/test.dat"; uris = proxy_reverse_json_parse_uris(NULL, path, 0); ck_assert_msg(uris == NULL, "Failed to handle null pool argument"); ck_assert_msg(errno == EINVAL, "Failed to set errno to EINVAL"); } END_TEST START_TEST (reverse_json_parse_uris_isreg_test) { array_header *uris; const char *path; int res; test_cleanup(p); path = "servers.json"; uris = proxy_reverse_json_parse_uris(p, path, 0); ck_assert_msg(uris == NULL, "Failed to handle relative path '%s'", path); ck_assert_msg(errno == EINVAL, "Failed to set errno to EINVAL"); path = test_file; uris = proxy_reverse_json_parse_uris(p, path, 0); ck_assert_msg(uris == NULL, "Failed to handle nonexistent file '%s'", path); ck_assert_msg(errno == ENOENT, "Failed to set errno to ENOENT"); res = mkdir(test_dir, 0777); ck_assert_msg(res == 0, "Failed to create tmp directory '%s': %s", test_dir, strerror(errno)); uris = proxy_reverse_json_parse_uris(p, test_dir, 0); ck_assert_msg(uris == NULL, "Failed to handle directory path '%s'", test_dir); ck_assert_msg(errno == EISDIR, "Failed to set errno to EISDIR"); test_cleanup(p); } END_TEST START_TEST (reverse_json_parse_uris_perms_test) { array_header *uris; const char *path; int fd, res; mode_t perms; /* Note: any extra chmods are necessary to workaround any umask in the * environment. Sigh. */ perms = 0777; res = mkdir(test_dir, perms); ck_assert_msg(res == 0, "Failed to create tmp directory '%s': %s", test_dir, strerror(errno)); res = chmod(test_dir, perms); ck_assert_msg(res == 0, "Failed to set perms %04o on directory '%s': %s", perms, test_dir, strerror(errno)); /* First, make a world-writable file. */ perms = 0666; fd = open(test_file, O_WRONLY|O_CREAT, perms); ck_assert_msg(fd >= 0, "Failed to create tmp file '%s': %s", test_file, strerror(errno)); res = fchmod(fd, perms); ck_assert_msg(res == 0, "Failed to set perms %04o on file '%s': %s", perms, test_file, strerror(errno)); path = test_file; uris = proxy_reverse_json_parse_uris(p, path, 0); ck_assert_msg(uris == NULL, "Failed to handle world-writable file '%s'", path); ck_assert_msg(errno == EPERM, "Failed to set errno to EPERM, got %d (%s)", errno, strerror(errno)); /* Now make the file user/group-writable only, but leave the parent * directory world-writable. */ perms = 0660; res = fchmod(fd, perms); ck_assert_msg(res == 0, "Failed to set perms %04o on file '%s': %s", perms, test_file, strerror(errno)); uris = proxy_reverse_json_parse_uris(p, path, 0); ck_assert_msg(uris == NULL, "Failed to handle world-writable directory '%s'", test_file); ck_assert_msg(errno == EPERM, "Failed to set errno to EPERM, got %d (%s)", errno, strerror(errno)); (void) close(fd); test_cleanup(p); } END_TEST START_TEST (reverse_json_parse_uris_empty_test) { array_header *uris; FILE *fh = NULL; int res; test_cleanup(p); fh = test_prep(); /* Write a file with no lines. */ res = fclose(fh); ck_assert_msg(res >= 0, "Failed to write file '%s': %s", test_file, strerror(errno)); mark_point(); uris = proxy_reverse_json_parse_uris(p, test_file, 0); ck_assert_msg(uris != NULL, "Did not receive parsed list as expected"); ck_assert_msg(uris->nelts == 0, "Expected zero elements, found %d", uris->nelts); test_cleanup(p); } END_TEST START_TEST (reverse_json_parse_uris_malformed_test) { array_header *uris; FILE *fh = NULL; int res; test_cleanup(p); fh = test_prep(); fprintf(fh, "[ \"http://127.0.0.1:80\",\n"); fprintf(fh, "\"ftp:/127.0.0.1::21\",\n"); fprintf(fh, "\"ftp://foo.bar.baz:21\" ]\n"); res = fclose(fh); ck_assert_msg(res >= 0, "Failed to write file '%s': %s", test_file, strerror(errno)); mark_point(); uris = proxy_reverse_json_parse_uris(p, test_file, 0); ck_assert_msg(uris != NULL, "Did not receive parsed list as expected"); ck_assert_msg(uris->nelts == 0, "Expected zero elements, found %d", uris->nelts); test_cleanup(p); } END_TEST START_TEST (reverse_json_parse_uris_usable_test) { array_header *uris; FILE *fh = NULL; int res; unsigned int expected; test_cleanup(p); fh = test_prep(); /* Write a file with usable URLs. */ fprintf(fh, "[ \"ftp://127.0.0.1\",\n"); fprintf(fh, "\"ftp://localhost:2121\",\n"); fprintf(fh, "\"ftp://[::1]:21212\" ]\n"); res = fclose(fh); ck_assert_msg(res >= 0, "Failed to write file '%s': %s", test_file, strerror(errno)); mark_point(); uris = proxy_reverse_json_parse_uris(p, test_file, 0); ck_assert_msg(uris != NULL, "Did not receive parsed list as expected"); expected = 3; ck_assert_msg(uris->nelts == expected, "Expected %d elements, found %d", expected, uris->nelts); test_cleanup(p); } END_TEST START_TEST (reverse_connect_get_policy_id_test) { int res; const char *policy; res = proxy_reverse_connect_get_policy_id(NULL); ck_assert_msg(res < 0, "Failed to handle null argument"); ck_assert_msg(errno == EINVAL, "Expected EINVAL (%d), got '%s' (%d)", EINVAL, strerror(errno), errno); policy = "foo"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res < 0, "Failed to handle unsupported policy '%s'", policy); ck_assert_msg(errno == ENOENT, "Expected ENOENT (%d), got '%s' (%d)", ENOENT, strerror(errno), errno); policy = "random2"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res < 0, "Failed to handle unsupported policy '%s'", policy); ck_assert_msg(errno == ENOENT, "Expected ENOENT (%d), got '%s' (%d)", ENOENT, strerror(errno), errno); policy = "random"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_RANDOM, "Failed to handle supported policy '%s'", policy); policy = "roundrobin"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_ROUND_ROBIN, "Failed to handle supported policy '%s'", policy); policy = "shuffle"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_SHUFFLE, "Failed to handle supported policy '%s'", policy); policy = "leastconns"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_LEAST_CONNS, "Failed to handle supported policy '%s'", policy); policy = "peruser"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_PER_USER, "Failed to handle supported policy '%s'", policy); policy = "pergroup"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_PER_GROUP, "Failed to handle supported policy '%s'", policy); policy = "perhost"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_PER_HOST, "Failed to handle supported policy '%s'", policy); policy = "leastresponsetime"; res = proxy_reverse_connect_get_policy_id(policy); ck_assert_msg(res == PROXY_REVERSE_CONNECT_POLICY_LEAST_RESPONSE_TIME, "Failed to handle supported policy '%s'", policy); } END_TEST START_TEST (reverse_use_proxy_auth_test) { int res; res = proxy_reverse_use_proxy_auth(); ck_assert_msg(res == FALSE, "Expected false, got %d", res); } END_TEST START_TEST (reverse_have_authenticated_test) { int res; cmd_rec *cmd = NULL; res = proxy_reverse_have_authenticated(cmd); ck_assert_msg(res == FALSE, "Expected false, got %d", res); proxy_sess_state |= PROXY_SESS_STATE_BACKEND_AUTHENTICATED; res = proxy_reverse_have_authenticated(cmd); ck_assert_msg(res == TRUE, "Expected true, got %d", res); proxy_sess_state &= ~PROXY_SESS_STATE_BACKEND_AUTHENTICATED; } END_TEST Suite *tests_get_reverse_suite(void) { Suite *suite; TCase *testcase; suite = suite_create("reverse"); testcase = tcase_create("base"); tcase_add_checked_fixture(testcase, set_up, tear_down); tcase_add_test(testcase, reverse_free_test); tcase_add_test(testcase, reverse_init_test); tcase_add_test(testcase, reverse_sess_free_test); tcase_add_test(testcase, reverse_sess_init_test); tcase_add_test(testcase, reverse_connect_policy_random_test); tcase_add_test(testcase, reverse_connect_policy_roundrobin_test); tcase_add_test(testcase, reverse_connect_policy_leastconns_test); tcase_add_test(testcase, reverse_connect_policy_leastresponsetime_test); tcase_add_test(testcase, reverse_connect_policy_shuffle_test); tcase_add_test(testcase, reverse_connect_policy_peruser_test); tcase_add_test(testcase, reverse_connect_policy_pergroup_test); tcase_add_test(testcase, reverse_connect_policy_perhost_test); tcase_add_test(testcase, reverse_handle_user_pass_random_test); tcase_add_test(testcase, reverse_handle_user_pass_roundrobin_test); tcase_add_test(testcase, reverse_handle_user_pass_leastconns_test); tcase_add_test(testcase, reverse_handle_user_pass_leastresponsetime_test); tcase_add_test(testcase, reverse_handle_user_pass_shuffle_test); tcase_add_test(testcase, reverse_handle_user_pass_peruser_test); tcase_add_test(testcase, reverse_handle_user_pass_pergroup_test); tcase_add_test(testcase, reverse_handle_user_pass_perhost_test); tcase_add_test(testcase, reverse_json_parse_uris_args_test); tcase_add_test(testcase, reverse_json_parse_uris_isreg_test); tcase_add_test(testcase, reverse_json_parse_uris_perms_test); tcase_add_test(testcase, reverse_json_parse_uris_empty_test); tcase_add_test(testcase, reverse_json_parse_uris_malformed_test); tcase_add_test(testcase, reverse_json_parse_uris_usable_test); tcase_add_test(testcase, reverse_connect_get_policy_id_test); tcase_add_test(testcase, reverse_use_proxy_auth_test); tcase_add_test(testcase, reverse_have_authenticated_test); suite_add_tcase(suite, testcase); return suite; }
// Copyright (c) 2023-2024 Wavelet Lab // SPDX-License-Identifier: MIT #include <check.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <assert.h> #include <stdlib.h> #include "xdsp_utest_common.h" #include "../conv_f32_i16_2.h" #undef DEBUG_PRINT #define STREAM_SIZE (8192 + 16 + 8 + 7) #define STREAM_SIZE_CHECK STREAM_SIZE #define STREAM_SIZE_SPEED 32768 #define CONV_SCALE (1.0f/32767) #define EPS (5E-5) static const unsigned packet_lens[3] = { 2048, 8192, STREAM_SIZE_SPEED }; #define SPEED_MEASURE_ITERS 1000000 static float* in = NULL; static int16_t* out = NULL; static int16_t* out_etalon = NULL; static const char* last_fn_name = NULL; static generic_opts_t max_opt = OPT_GENERIC; static void setup() { posix_memalign((void**)&in, ALIGN_BYTES, sizeof(float) * STREAM_SIZE_SPEED); posix_memalign((void**)&out, ALIGN_BYTES, sizeof(int16_t) * STREAM_SIZE_SPEED); posix_memalign((void**)&out_etalon, ALIGN_BYTES, sizeof(int16_t) * STREAM_SIZE_SPEED); for(unsigned i = 0; i < STREAM_SIZE_SPEED; ++i) { in[i] = ((float)i / STREAM_SIZE_SPEED) - 0.5; } } static void teardown() { free(in); free(out); free(out_etalon); } static int is_equal() { for(unsigned i = 0; i < STREAM_SIZE_CHECK; ++i) { float a = out[i]; float b = out_etalon[i]; a *= CONV_SCALE; b *= CONV_SCALE; float delta = fabs(a-b); if(delta > EPS) { fprintf(stderr, "i = %d : in = %.6f, out = %d, etalon = %d, delta = %.6f\n", i, in[i], out[i], out_etalon[i], delta); return 1; } } return 0; } static conv_function_t get_fn(generic_opts_t o, int log) { const char* fn_name = NULL; conv_function_t fn = conv_get_f32_i16_c(o, &fn_name); //ignore dups if(last_fn_name && !strcmp(last_fn_name, fn_name)) return NULL; if(log) fprintf(stderr, "%-20s\t", fn_name); last_fn_name = fn_name; return fn; } START_TEST(conv_f32_i16_check) { generic_opts_t opt = max_opt; conv_function_t fn = NULL; const void* pin = (const void*)in; void* pout = (void*)out; last_fn_name = NULL; const size_t bzin = STREAM_SIZE_CHECK * sizeof(float); const size_t bzout = STREAM_SIZE_CHECK * sizeof(int16_t); fprintf(stderr,"\n**** Check SIMD implementations ***\n"); //get etalon output data (generic foo) (*get_fn(OPT_GENERIC, 0))(&pin, bzin, &pout, bzout); memcpy(out_etalon, out, bzout); while(opt != OPT_GENERIC) { conv_function_t fn = get_fn(opt--, 1); if(fn) { memset(out, 0, bzout); (*fn)(&pin, bzin, &pout, bzout); int res = is_equal(); res ? fprintf(stderr,"\tFAILED!\n") : fprintf(stderr,"\tOK!\n"); #ifdef DEBUG_PRINT for(int i = 0; res && i < STREAM_SIZE_CHECK; ++i) { fprintf(stderr, "i = %d : in = %.6f, out = %d, etalon = %d\n", i, in[i], out[i], out_etalon[i]); } #endif ck_assert_int_eq( res, 0 ); } } } END_TEST START_TEST(conv_f32_i16_speed) { generic_opts_t opt = max_opt; conv_function_t fn = NULL; const void* pin = (const void*)in; void* pout = (void*)out; last_fn_name = NULL; const size_t bzin = packet_lens[_i] * sizeof(float); const size_t bzout = packet_lens[_i] * sizeof(int16_t); fprintf(stderr, "\n**** Compare SIMD implementations speed ***\n"); fprintf(stderr, "**** packet: %lu bytes, iters: %u ***\n", bzin, SPEED_MEASURE_ITERS); while(opt != OPT_GENERIC) { conv_function_t fn = get_fn(opt--, 1); if(fn) { //warming for(int i = 0; i < 100; ++i) (*fn)(&pin, bzin, &pout, bzout); //measuring uint64_t tk = clock_get_time(); for(int i = 0; i < SPEED_MEASURE_ITERS; ++i) (*fn)(&pin, bzin, &pout, bzout); uint64_t tk1 = clock_get_time() - tk; fprintf(stderr, "\t%" PRIu64 " us elapsed, %" PRIu64 " ns per 1 call, ave speed = %" PRIu64 " calls/s \n", tk1, (uint64_t)(tk1*1000LL/SPEED_MEASURE_ITERS), (uint64_t)(1000000LL*SPEED_MEASURE_ITERS/tk1)); } } } END_TEST Suite * conv_f32_i16_suite(void) { Suite *s; TCase *tc_core; max_opt = cpu_vcap_get(); s = suite_create("conv_f32_i16"); tc_core = tcase_create("XDSP"); tcase_set_timeout(tc_core, 60); tcase_add_unchecked_fixture(tc_core, setup, teardown); tcase_add_test(tc_core, conv_f32_i16_check); tcase_add_loop_test(tc_core, conv_f32_i16_speed, 0, 3); suite_add_tcase(s, tc_core); return s; }
# pkg library(dplyr) library(purrr) # get input input <- readLines("2022/day08-input.txt") |> strsplit(split = "") # modify input input <- as.data.frame(do.call(rbind, input)) |> mutate(across(.cols = everything(), .fns = ~as.numeric(.))) # count dimensions ncols <- ncol(input) nrows <- nrow(input) # calculate number of outside and inside tress outside_trees <- (2*nrows)+((ncols-2)*2) inside_trees <- prod(dim(input)) - outside_trees # set_up position-table for tree lookup row_pos <- 2:(nrows-1) col_pos <- 2:(ncols-1) tree_pos <- tidyr::expand_grid(row_pos, col_pos) # cleanup the environment rm(row_pos, col_pos, ncols, nrows) #' Check tree value by its position and get the values of its surrounding trees #' @description Function to check every tree position and map the trees #' at each of its sides. This function is used as backend for the following #' functions #' #' @param i integer row index (tree position) #' @param j integer col index (tree position) #' @param dat default = input #' #' @return a list with five elements (tar, tar_top, tar_bot, tar_left, tar_right) #' @export #' check_position <- function(i, j, dat = input){ tar = dat[i, j] tar_top = rev(dat[1:(i-1), j]) tar_bot = dat[(i+1):nrow(dat), j] tar_left = rev(as.integer(dat[i, 1:(j-1)])) tar_right = as.integer(dat[i, (j+1):ncol(dat)]) tibble::lst(tar, tar_top, tar_bot, tar_left, tar_right) } #' Check visibility of a tree from all sides by comparing their values #' #' @description Function to check the visibility of tree - #' a tree is visible from a given side, if all( .x < .y), meaning #' all trees on whatever side (top, bottom, left, right) are smaller #' than the given tree #' #' @param i integer row index (tree position) #' @param j integer col index (tree position) #' @param dat default = input #' #' @return #' @export #' #' @examples check_vis <- function(i, j, dat = input){ pos = check_position(i, j, dat = dat) %>% map2(.x = ., .y = .$tar, ~all(.x < .y)) map_dfr(pos[-1], sum) %>% mutate(vis = rowSums( . > 0)) } # check_vis(4,2) ## Part 1 ## # map check_vis() for all tree indices, count number of trees that are visible... visisble_inside_trees <- map2_dfr(tree_pos$row_pos, tree_pos$col_pos, check_vis) %>% filter(vis > 0) %>% nrow() # ...and sum together with the outside trees sum(outside_trees, visisble_inside_trees) # result 1785 ## Part 2 #' Check the visual distance of a tree (scenic score = prod of all views) #' #' @description check_position remains the same, but check_vis needs to be adapted #' to have a number of the visual distance of each tree. #' the visual distance is the distance until you reach a tree that is ≥ than the #' index tree - #' thus by putting the min(which(x)) or - if this is integer(0)//infitnite putting the length of .x #' then calculate the product #' #' #' @param i integer row index (tree position) #' @param j integer col index (tree position) #' #' @return #' @export #' check_vis_distance <- function(i, j, dat = input){ vis_dist = check_position(i, j, dat = dat) %>% map2(.x = ., .y = .$tar, ~ifelse( is.infinite(min(which(.x >= .y))), length(.x), min(which(.x >= .y))) ) # vis_dist[-1] to omit the $tar value (val of the index tree) # calculate the scenic score as product of all distances per tree prod(do.call(rbind, vis_dist[-1])) } # finally, get the hightest visible scenic score possible max(map2_dbl(tree_pos$row_pos, tree_pos$col_pos, check_vis_distance)) #345'168
import { createContext, useCallback, useState } from 'react'; import { localStorageKeys } from '../config/localStorageKeys'; interface AuthProps { children: React.ReactNode, } interface AuthContextProps { isAuthenticated: boolean, signin: (token: string) => void, signout: () => void, } export const AuthContext = createContext({} as AuthContextProps); export default function AuthProvider({ children }: AuthProps) { const [isAuthenticated, setIsAuthenticated] = useState(() => { const userIsLogged = localStorage.getItem(localStorageKeys.token); return !!userIsLogged; }); const signin = useCallback((token: string) => { localStorage.setItem(localStorageKeys.token, token); setIsAuthenticated(true); }, []); const signout = useCallback(() => { localStorage.removeItem(localStorageKeys.token); setIsAuthenticated(false); }, []); return ( <AuthContext.Provider value={{ isAuthenticated, signin, signout, }}> {children} </AuthContext.Provider> ); }
import Address from "../../@shared/domain/value-object/address"; import Id from "../../@shared/domain/value-object/id.value-object"; import InvoiceItem from "../domain/invoice-item.entity"; import Invoice from "../domain/invoice.entity"; import InvoiceGateway from "../gateway/invoice.gateway"; import { InvoiceItemModel } from "./invoice-item.model"; import { InvoiceModel } from "./invoice.model"; export default class InvoiceRepository implements InvoiceGateway { async generate(input: Invoice): Promise<void> { const record = await InvoiceModel.create({ id: input.id.id, name: input.name, document: input.document, street: input.address.street, number: input.address.number, complement: input.address.complement, city: input.address.city, state: input.address.state, zipCode: input.address.zipCode, createdAt: input.createdAt.toISOString(), }); const promises = input.items.map(({ id, name, price }) => InvoiceItemModel.create({ id: id.id, name, price, invoiceId: record.id, }) ); await Promise.all(promises); } async find(id: string): Promise<Invoice> { const invoice = await InvoiceModel.findOne({ where: { id } }); if (!invoice) throw new Error("Invoice not found"); const items = await InvoiceItemModel.findAll({ where: { invoiceId: invoice.id }, }); const address = new Address( invoice.street, invoice.number, invoice.complement, invoice.city, invoice.state, invoice.zipCode ); const invoiceItems = items.map( (item) => new InvoiceItem({ name: item.name, price: item.price, id: new Id(item.id), }) ); return new Invoice({ address, document: invoice.document, items: invoiceItems, name: invoice.name, createdAt: new Date(invoice.createdAt), id: new Id(invoice.id), updatedAt: invoice.updatedAt ? new Date(invoice.updatedAt) : null, }); } }
import React from 'react'; import './App.css'; import Navbar from './components/NavBar'; import { About } from './pages/About' import { DailyExpenses } from './pages/DailyExpenses'; import { MonthlyExpenses } from './pages/MonthlyExpenses'; import { Visualizations } from './pages/Visualizations'; import { Home } from './pages/Home'; import { Route, Routes } from 'react-router-dom'; function App() { return ( <div className="App"> <Navbar></Navbar> <Routes> <Route path="/" element={<Home></Home>}> <Route path="about" element={<About></About>}></Route> <Route path="daily" element={<DailyExpenses></DailyExpenses>}></Route> <Route path="monthly" element={<MonthlyExpenses></MonthlyExpenses>}></Route> <Route path="visualizations" element={<Visualizations></Visualizations>}></Route> </Route> </Routes> </div> ); } export default App;
# Chapter 10 # JavaScript Libraries and Frameworks JavaScript libraries and frameworks provide pre-written code and structures to help developers build web applications more efficiently. They offer various functionalities and follow different philosophies, enabling developers to choose the best fit for their project requirements. This chapter introduces popular JavaScript libraries and frameworks (jQuery, React, Vue, Angular), their advantages and disadvantages, guidelines for choosing the right one for your project, and best practices for using them. ## Introduction to Popular JavaScript Libraries and Frameworks ### jQuery jQuery is a fast and lightweight library that simplifies HTML document traversal, manipulation, event handling, and animation. It also offers a simple interface for making AJAX requests. jQuery has been widely used and has greatly influenced the way developers work with JavaScript. ```javascript // Example of using jQuery for DOM manipulation $("button").click(function () { $("p").hide(); }); ``` ### React React is a popular JavaScript library for building user interfaces, created by Facebook. React focuses on the view layer and emphasizes building reusable components, making it easy to create complex UIs. It uses a virtual DOM for efficient DOM manipulation and provides a unidirectional data flow, resulting in predictable and maintainable applications. ```javascript // Example of using React for creating a simple component import React from "react"; function Welcome(props) { return <h1>Hello, {props.name}</h1>; } ``` ### Vue Vue.js is a progressive framework for building user interfaces. It is designed to be approachable, versatile, and performant. Vue focuses on the view layer, like React, but can be easily integrated with other libraries or existing projects. It also offers an optional syntax called Single File Components, making it easy to manage the component's template, script, and styles in one file. ```javascript // Example of using Vue for creating a simple component new Vue({ el: "#app", data: { message: "Hello Vue!", }, }); ``` ### Angular Angular is a powerful, full-featured framework for building web applications, created by Google. Angular uses TypeScript, a statically-typed superset of JavaScript, and encourages a modular architecture. It provides a wide range of features, such as dependency injection, two-way data binding, and component-based development, making it suitable for large-scale applications. ```typescript // Example of using Angular for creating a simple component import { Component } from "@angular/core"; @Component({ selector: "app-root", template: `<h1>Hello, {{ name }}</h1>`, }) export class AppComponent { name = "Angular"; } ``` ## Advantages and Disadvantages of Using a Library or Framework ### Advantages 1. Increased productivity: Libraries and frameworks provide pre-written code and structures, reducing the time and effort required to develop a web application. 2. Better code organization: Most libraries and frameworks encourage a specific structure or design pattern, resulting in more organized and maintainable code. 3. Improved performance: Many libraries and frameworks optimize performance through features like virtual DOM, caching, and lazy-loading. 4. Community support: Popular libraries and frameworks have active communities that provide resources, plugins, and help with troubleshooting. ### Disadvantages 1. Learning curve: It takes time to learn and become proficient with a new library or framework. 2. Increased complexity: Some frameworks can add complexity to a project, making it harder to understand and maintain. 3. Dependency on external code: Relying on external libraries or frameworks can make your project susceptible to breaking changes or security vulnerabilities. 4. Potential performance issues: Some libraries or frameworks can add significant overhead to your application, resulting in slower load times and reduced performance. ## Choosing the Right Library or Framework for Your Project When selecting the right library or framework for your project, consider the following factors: 1. Project requirements: Assess your project's specific requirements and features. Choose a library or framework that aligns with your needs and goals. 2. Learning curve and familiarity: Evaluate your existing knowledge of the library or framework and its learning curve. If you are already proficient with a specific library or framework, it might be more efficient to continue using it. 3. Size and complexity: Consider the size and complexity of your project. Smaller projects may benefit from lightweight libraries, while larger projects may require more powerful and feature-rich frameworks. 4. Community support and popularity: Popular libraries and frameworks often have better community support and more resources available, making it easier to find help, plugins, and tutorials. 5. Long-term maintenance and updates: Ensure that the library or framework is actively maintained and frequently updated. This helps guarantee that you'll receive bug fixes, security patches, and new features over time. ## Best Practices for Using JavaScript Libraries and Frameworks 1. Keep your dependencies up-to-date: Regularly update your dependencies to ensure you have the latest bug fixes, security patches, and features. 2. Minimize the number of dependencies: Avoid using too many libraries or frameworks, as this can lead to increased complexity and reduced performance. Instead, focus on a few key dependencies that provide the most value to your project. 3. Optimize for performance: Utilize performance optimizations provided by the library or framework, such as code-splitting, lazy-loading, and caching. 4. Follow best practices and conventions: Adhere to the best practices and conventions recommended by the library or framework. This can help improve the maintainability and readability of your code. 5. Leverage community resources: Use community-provided resources, such as documentation, forums, and tutorials, to learn and troubleshoot issues with the library or framework. 6. Write modular and reusable code: Organize your code into modular, reusable components to make it easier to maintain and test. In conclusion, JavaScript libraries and frameworks offer valuable tools for developers to build efficient and maintainable web applications. This chapter introduced popular JavaScript libraries and frameworks (jQuery, React, Vue, Angular), their advantages and disadvantages, and guidelines for choosing the right one for your project. By following the best practices outlined in this chapter and selecting the appropriate library or framework, you can create high-quality, performant, and maintainable web applications. ## Summing up In this chapter, we discussed the importance of JavaScript libraries and frameworks in building efficient and maintainable web applications. We introduced popular JavaScript libraries and frameworks such as jQuery, React, Vue, and Angular, and explored their advantages and disadvantages. Additionally, we provided guidelines for choosing the right library or framework for your project, and outlined best practices for using them. By following these guidelines and leveraging the strengths of these libraries and frameworks, you can create high-quality, performant, and maintainable web applications that meet your project requirements. ## Knowledge Test 1. Create a simple web page that contains a button and a paragraph. Using jQuery, add an event listener to the button that toggles the visibility of the paragraph when clicked. 2. Create a React component that displays a list of users. Each user should have a name, age, and email. You can use sample data to create the list. Render this component in your application. 3. Create a Vue application that allows users to input their name in a text box. As they type, display a greeting message that includes their name, such as "Hello, [name]!". 4. Create an Angular component that displays a simple form with two input fields: one for a user's first name and another for their last name. When the form is submitted, display the user's full name in a heading element. 5. Choose any of the libraries or frameworks introduced in this chapter (jQuery, React, Vue, Angular) and implement code splitting or lazy loading to optimize the performance of a sample application. 6. Choose a library or framework you're less familiar with from this chapter (jQuery, React, Vue, Angular). Spend time going through the official documentation and community resources (forums, tutorials, blog posts) to gain a deeper understanding of its concepts, features, and best practices. Implement a small project using this library or framework to practice your newly-acquired skills. 7. Select two JavaScript libraries or frameworks from this chapter (e.g., React and Vue) and compare their advantages and disadvantages. Consider factors like learning curve, performance, community support, and development patterns. Write a brief report discussing your findings and make a recommendation on which library or framework to use for a specific use case or project type.
package com.example.safediary.utils import android.graphics.Bitmap import androidx.annotation.OptIn import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.FaceDetection import com.google.mlkit.vision.face.FaceDetectorOptions import com.google.mlkit.vision.face.FaceDetectorOptions.LANDMARK_MODE_NONE import com.google.mlkit.vision.face.FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE class FaceAnalyzer(private val callBack: FaceAnalyzerCallback) : ImageAnalysis.Analyzer { private val realTimeOpts = FaceDetectorOptions.Builder() .setPerformanceMode(PERFORMANCE_MODE_ACCURATE) .setLandmarkMode(LANDMARK_MODE_NONE) .setMinFaceSize(0.9f) .build() private val detector = FaceDetection.getClient(realTimeOpts) @OptIn(ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image val bitmap = imageProxy.toBitmap() val originalWidth = bitmap.width val originalHeight = bitmap.height val newWidth = (originalWidth * IMAGE_SIZE_MODIFIER).toInt() val newHeight = (originalHeight * IMAGE_SIZE_MODIFIER).toInt() val left = (originalWidth - newWidth) / IMAGE_POSITION_MODIFIER val top = (originalHeight - newHeight) / IMAGE_POSITION_MODIFIER val croppedBitmap = Bitmap.createBitmap(bitmap, left, top, newWidth, newHeight) mediaImage?.let { val inputImage = InputImage.fromBitmap(croppedBitmap, imageProxy.imageInfo.rotationDegrees) detector.process(inputImage) .addOnSuccessListener { faces -> if (faces.isNotEmpty()) { val fullSizeFaces = faces.filter { it.boundingBox.height() > FACE_SIZE_RESTRICTION && it.boundingBox.width() > FACE_SIZE_RESTRICTION } if (fullSizeFaces.isNotEmpty()) { callBack.processFace(bitmap) } } imageProxy.close() } .addOnFailureListener { callBack.errorFace(it.message.orEmpty()) imageProxy.close() } .addOnCompleteListener { imageProxy.close() } } } companion object { private const val IMAGE_SIZE_MODIFIER = 0.3 private const val IMAGE_POSITION_MODIFIER = 2 private const val FACE_SIZE_RESTRICTION = 125 } } interface FaceAnalyzerCallback { fun processFace(detectedFace: Bitmap) fun errorFace(error: String) }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; /** * * @author Corne */ public class Primes { // // initially assume all integers are prime // boolean[] isPrime = new boolean[N + 1]; // for (int i = 2; i <= N; i++) { // isPrime[i] = true; // } // // // mark non-primes <= N using Sieve of Eratosthenes // for (int i = 2; i*i <= N; i++) { // // // if i is prime, then mark multiples of i as nonprime // // suffices to consider mutiples i, i+1, ..., N/i // if (isPrime[i]) { // for (int j = i; i*j <= N; j++) { // isPrime[i*j] = false; // } // } // } // // // count primes // int primes = 0; // for (int i = 2; i <= N; i++) { // if (isPrime[i]) primes++; // } //using list so we can use get private static final int MAX_ARRAY_SIZE = /*Integer.MAX_VALUE - 5*/ 1000000; private final Boolean[] bPrimes; private final List<Prime> primes; public Primes() { primes = new ArrayList<>(); this.bPrimes = new Boolean[MAX_ARRAY_SIZE]; Arrays.fill(bPrimes, true); bPrimes[0] = false; bPrimes[1] = false; for (int i = 2; i * i < MAX_ARRAY_SIZE; i++) { if (bPrimes[i]) { for (int j = i; i * j < MAX_ARRAY_SIZE; j++) { bPrimes[i * j] = false; } } } for(int i=0; i<bPrimes.length; i++){ primes.add(new Prime(i, bPrimes[i])); } } /** * TODO clean, adding to set is kinda ugly atm. * * @param value * @return */ public static SortedSet<Long> findFactorPrimes(long value) { for (long i = 2; i < value; i++) { if (value % i == 0) { SortedSet<Long> result = findFactorPrimes(value / i); result.add(i); return result; } } TreeSet<Long> treeSet = new TreeSet<>(); treeSet.add(value); return treeSet; } public long getPrime(int index) { return primes.stream().filter(p -> p.isIsPrime()) .collect(Collectors.toCollection(ArrayList::new)).get(index).getValue(); } public List<Integer> getPrimesBelowValue(int value) { return primes.subList(0, value).stream().filter(p -> p.isIsPrime() && p.getValue() < value) .map(p -> p.getValue()) .collect(Collectors.toCollection(ArrayList::new)); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dojo Weather</title> <link rel="stylesheet" href="./style.css"> </head> <body> <!-- Nav Section --> <nav> <h1>Dojo Weather</h1> <ul> <li><a href="#" onclick="displayAlert()">Burbank</a></li> <li><a href="#" onclick="displayAlert()">Chicago</a></li> <li><a href="#" onclick="displayAlert()">Dallas</a></li> </ul> </nav> <!-- MAIN CONTAINER --> <div id="main-container"> <div id="location-head"> <h2>San Jose</h2> <div id="temp"> <p>show temperature in</p> <select id="temp-selector" name="temperature-scale" onchange="convert(this)"> <option>˚C<option> <option>˚F<option> </select> </div> </div> <div id="card-container"> <div class="card"> <h3>Today</h3> <img src="./assets 2/some_rain.png" class="img-weather" alt="some rain"> <p>some rain</p> <div class="temp-section"> <h4 class="red-text high" id="temp1">24˚</h4> <h4 class="blue-text low" id="temp2">18˚</h4> </div> </div> <div class="card"> <h3>Tomorrow</h3> <img src="./assets 2/some_sun.png" class="img-weather" alt="some rain"> <p>some sun</p> <div class="temp-section"> <h4 class="red-text high" id="temp3">27˚</h4> <h4 class="blue-text low" id="temp4">19˚</h4> </div> </div> <div class="card"> <h3>Friday</h3> <img src="./assets 2/some_clouds.png" class="img-weather" alt="some rain"> <p>some clouds</p> <div class="temp-section"> <h4 class="red-text high" id="temp5">21˚</h4> <h4 class="blue-text low" id="temp6">16˚</h4> </div> </div> <div class="card"> <h3>Saturday</h3> <img src="./assets 2/some_sun.png" class="img-weather" alt="some rain"> <p>some sun</p> <div class="temp-section"> <h4 class="red-text high" id="temp7">26˚</h4> <h4 class="blue-text low" id="temp8">21˚</h4> </div> </div> </div> </div> <div id="cookie-container"> <img src="./assets 2/cookie.png" alt="cookie image"> <div id="cookie-text-box"> <div id="cookie-text"> <h4>Stop! Cookie Time</h4> <p>We use cookies (sadly not the edible ones) to peronilze content and ads, tp prvide social media features and to analyse our traffic. <a href="#" id="read-more">Read more...</a></p> </div> <button id="accept-btn" onclick="accept('#cookie-container')">I Accept</button> </div> </div> <script src="script.js"></script> </body> </html>
function myPlot1(t,y, plot_title, varname) %myPlot1 Plots 1 variable versus an independent variable % Expectations: % t = 1x(length) double % y = 1x(length) double % title = string %Explains the plot in a word or two % varname = string %What to call the plotted line in the legend figure plot(t,y) xlim([0 t(end)]) % stop a weird space from appearing on the right side of the plot title(strcat(plot_title)) legend({strcat(varname)}) end
import { render, screen, waitFor} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import Login from '../components/Login'; import { BrowserRouter as Router } from 'react-router-dom'; // Tests for the Login component describe('Login', () => { // Render the Login component will null token it('render login screen with null token', () => { const setToken = jest.fn(); const setEmail = jest.fn(); render( <Router> <Login token={null} setToken={setToken} setEmail={setEmail} /> </Router> ); expect(screen.getByRole('textbox', { name: /email/i })).toBeInTheDocument(); expect(screen.getByLabelText(/Password \*/i)).toBeInTheDocument(); expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument(); }) // Alert if no email or password entered it('display alert if no email or password entered on submit', () => { const setToken = jest.fn(); const setEmail = jest.fn(); const alertMock = jest.spyOn(window,'alert').mockImplementation(); render( <Router> <Login token={null} setToken={setToken} setEmail={setEmail} /> </Router> ); userEvent.click(screen.getByRole('button', { name: 'Login' })); expect(alertMock).toHaveBeenCalledWith('Please enter email'); }); // Alert if no password entered it('display alert if no password entered on submit', () => { const setToken = jest.fn(); const setEmail = jest.fn(); const alertMock = jest.spyOn(window,'alert').mockImplementation(); render( <Router> <Login token={null} setToken={setToken} setEmail={setEmail} /> </Router> ); userEvent.type(screen.getByRole('textbox', { name: /email/i }), 'name@email.com'); userEvent.click(screen.getByRole('button', { name: 'Login' })); expect(alertMock).toHaveBeenCalledWith('Please enter password'); }); // Succesful login attempt it('No error after successful login', async () => { const setToken = jest.fn(); const setEmail = jest.fn(); const token = null; const alertMock = jest.spyOn(window,'alert').mockImplementation(); render( <Router> <Login token={token} setToken={setToken} setEmail={setEmail} /> </Router> ); userEvent.type(screen.getByRole('textbox', { name: /email/i }), 'name@email.com'); userEvent.type(screen.getByLabelText(/Password \*/i), 'password'); userEvent.click(screen.getByRole('button', { name: 'Login' })); expect(alertMock).toHaveBeenCalledTimes(0); }); });
import { AppProps } from 'next/app'; import './styles.css'; import * as FullStory from '@fullstory/browser'; import { UpdateGameModal } from '@worksheets/ui-games'; import { SERVICE_SETTINGS } from '@worksheets/data-access/server-settings'; import { useVersion } from '@worksheets/ui-core'; import { APP_VERSION } from '../util'; import { useSavedPuzzle, useSavedSelections } from '../hooks/useSaveData'; import { useRouter } from 'next/router'; import { ThemeProvider, createTheme } from '@mui/material'; import { MobileMeta } from '@worksheets/ui-games'; import Head from 'next/head'; import { DefaultSeo } from 'next-seo'; import { TWITTER_SEO } from '@worksheets/util/seo'; if (typeof window !== 'undefined') { FullStory.init(SERVICE_SETTINGS.FULLSTORY); } const theme = createTheme({ palette: { primary: { light: '#2A99F4', main: '#1976d2', dark: '#10596e', }, }, }); const openGraph = { type: 'website', url: 'https://word-pack.charity.games/', title: 'Word Pack by Charity Games - Free Online Games for Charity', description: 'Word Pack is a crossword puzzle game that is free to play. Our game works on mobile, tablet, and desktop devices. Play more games on Charity Games.', images: [ { url: 'https://word-pack.charity.games/banner.jpg', width: 2208, height: 1242, alt: 'Word Pack Banner', type: 'image/jpg', }, ], }; function CustomApp({ Component, pageProps }: AppProps) { const { reload } = useRouter(); const { requiresUpdate, update, ignore } = useVersion(APP_VERSION); const puzzle = useSavedPuzzle(); const selections = useSavedSelections(); const handleUpdate = () => { if (puzzle.level > 0) { puzzle.cacheLevel(puzzle.level); selections.clearSelections(); } update(); reload(); }; return ( <> <DefaultSeo title={openGraph.title} description={openGraph.description} canonical={openGraph.url} openGraph={openGraph} twitter={TWITTER_SEO} /> <Head> <MobileMeta /> </Head> <ThemeProvider theme={theme}> <main> <Component {...pageProps} /> </main> <UpdateGameModal open={requiresUpdate} onClose={ignore} onUpdate={handleUpdate} /> </ThemeProvider> </> ); } export default CustomApp;
var fonts = { Roboto: { normal: 'fonts/Roboto-Regular.ttf', bold: 'fonts/Roboto-Medium.ttf', italics: 'fonts/Roboto-Italic.ttf', bolditalics: 'fonts/Roboto-MediumItalic.ttf' } }; var PdfPrinter = require('pdfmake'); var printer = new PdfPrinter(fonts); var fs = require('fs'); // Create a document definition const docDefinition = { content: [ { text: 'My First PDF with PDFMake', fontSize: 16, bold: true }, { text: 'This is a simple example of PDF generation with Node.js and PDFMake.', }, ], } var options = { // ... } // Create a Promise to generate the PDF const generatePDF = () => { return new Promise((resolve, reject) => { var pdfDoc = printer.createPdfKitDocument(docDefinition, options); const stream = pdfDoc.pipe(fs.createWriteStream('myFirstPDF.pdf')); pdfDoc.end(); stream.on('finish', () => { resolve('Async PDF generated successfully!') }) stream.on('error', (error) => { reject(error) }) }) } // Usage generatePDF() .then((message) => { console.log(message) }) .catch((error) => { console.error('Error generating PDF:', error) })
import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class Shell { public static void sort (Comparable[] a) { // Sort a[] into increasing order. int N = a.length; int h = 1; while (h < N/3) h = 3 * h + 1; // 1, 4, 13, 40, 121, ... while (h >= 1) { // h-sort the array. for (int i = h; i < N; i++) { // Insert a[i] among a[i-h], a[i-2*h], a[i-3*h], ... for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) exch(a, j, j-h); } h = h / 3; } } private static boolean less (Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void exch (Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } private static void show (Comparable[] a) { // Print the array on a single line. for (int i = 0; i < a.length; i++) StdOut.print(a[i] + " "); StdOut.println(); } public static boolean isSorted (Comparable[] a) { // Test whether the array entries are in order. for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; return true; } public static void main (String[] args) { // Read strings from standard input, sort them and print. String[] a = StdIn.readAllStrings(); sort(a); assert isSorted(a); show(a); } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js利用栈判断字符串是否是回文</title> <script> /** * 回文是指一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的。比如,单词"dad" */ function Stack(){ this.dataStore = [];//数组实现的栈 this.top = 0; this.push = push; this.pop = pop; this.peek = peek;//返回栈顶的元素 this.clear = clear; this.length = length; } function push(element){ this.dataStore[this.top++] = element; } function peek(){ return this.dataStore[--this.top]; } function clear(){ this.top = 0; } function length(){ return this.top; } function pop(){ return this.dataStore[--this.top]; } //回文判断 function isPalindrome(word){ var s = new Stack(); for(var i=0;i<word.length;i++){ s.push(word[i]); } var rword = ""; while(s.length() >0){ rword+=s.pop(); } if(word == rword){ return true; }else{ return false; } } var word = "hello"; alert(isPalindrome(word)); var word = "dad"; alert(isPalindrome(word)); </script> </head> <body> </body> </html>
#include <Servo.h> Servo trackerServo; int trackerPwm = 0; Servo targetServo; int targetPwm = 1000; // Start from 1000 int stepSize = 3; // Step size for increasing or decreasing PWM int timeDelay = 6; // Delay between each step int stepDirection = 1; // 1 for increasing, -1 for decreasing boolean startTargetServo = false; // Global flag to start/stop the target servo // an array to store the received data const byte numChars = 32; char receivedChars[numChars]; boolean newData = false; int dataNumber = 0; void setup() { trackerServo.attach(0); Serial.begin(115200); Serial.println("<Arduino is ready>"); } void setup1() { // Initialization for the second core targetServo.attach(1); } void loop() { recvWithEndMarker(); readNewNumber(); } void loop1() { if (startTargetServo) { targetPwm = targetPwm + (stepDirection * stepSize); if (targetPwm >= 2000) { targetPwm = 2000; stepDirection = -1; } else if (targetPwm <= 1000) { targetPwm = 1000; stepDirection = 1; } targetServo.writeMicroseconds(targetPwm); delay(timeDelay); } } void recvWithEndMarker() { static byte ndx = 0; char endMarker = '\n'; char rc; if (Serial.available() > 0) { rc = Serial.read(); if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { // terminate the string receivedChars[ndx] = '\0'; ndx = 0; newData = true; } } } void readNewNumber() { if (newData == true) { trackerPwm = atoi(receivedChars); Serial.print("This just in: "); Serial.println(receivedChars); Serial.print("Data as Number: "); Serial.println(trackerPwm); if (trackerPwm >= 1000 && trackerPwm <= 2000) { trackerServo.writeMicroseconds(trackerPwm); Serial.println("PWM set successfully"); // Send a response back } else { Serial.println("Invalid PWM value. Please enter a value between 500 and 2500."); } if (trackerPwm > 0 && trackerPwm <= 50) { timeDelay = trackerPwm; } // Set the global flag based on the received command if (strcmp(receivedChars, "s") == 0) { startTargetServo = true; Serial.println("Starting Target Servo"); } else if (strcmp(receivedChars, "x") == 0) { startTargetServo = false; Serial.println("Stopping Target Servo"); } newData = false; } }
<!DOCTYPE html> <html lang="en"> <head> <title>jQuery</title> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $('h1').css('font-size', '50px'); }); </script> <link rel="stylesheet" href="style.css"> </head> <body> <div id="wrapper"> <div id="1"> <h1>Red Panda's Add Class</h1> <p>Click the header to add class 'red' to this paragraph. It assigns a dotted red border to the div. Look! It has striped like a red panda!</p> </div> <div id="2"> <button id="b2">Slidetoggle</button> <h1>Slidetoggle</h1> <p>Click the button to slidetoggle a hidden image</p> <img src="redpanda.jpg" alt"Baby red pandas, so cute!" class="pic1"> </div> <div id="3"> <button id="b3">Append</button> <h1>Append</h1> <p>Click the button to append a new paragraph!</p> </div> <div id="4"> <button id="b4">Hide</button> <h1>Hide</h1> <p>Click the button to hide the div</p> </div> <div id="5"> <button id="b5">Show</button> <h1>Show</h1> <p>Click the button to show the hidden div</p> </div> <div id="6"> <button id="b6">Toggle</button> <h1>Toggle</h1> <p>Click the button to toggle the first div and remove the border</p> </div> <div id="7"> <button id="b7">Slidedown</button> <h1>Slidedown</h1> <p>Click the button to make the previous div's header hide or slide down</p> </div> <div id="8"> <button id="b8">Slideup</button> <h1>Slideup</h1> <p>Click the button to make the previous div's header slide up or unhide</p> </div> <div id="9"> <h1>Fadein/out</h1> <p>Hover over the dive the button to make an image fade in and out</p> <img src="pounce.jpg" alt="Red panda pouncing" class="pic1"> </div> <div id="10"> <button id="b10">Before</button> <h1>Before</h1> <p>Click the button to add a surprise before this paragraph!</p> </div> <div id="11"> <button id="b11">After</button> <h1>After</h1> <p>Click the button to add a surprise after this paragraph!</p> </div> <div id="12"> <button id="b12">HTML</button> <h1>HTML</h1> <p>Click the button to add some sweet HTML</p> </div> <div id="13"> <button id="b13">Attribute</button> <h1>Attribute</h1> <p>Click this button to change the 'src' attribute of the slidetoggle image!</p> </div> <div id="14"> <button id="b14">Value</button> <h1>Value</h1> <p>Click the button to grab the value from the dropdown list above.</p> <script> function displayVals() { var fav = $( "#single" ).val(); $( "p" ).html( "Favorite Thing: " + fav ); } $( "select" ).change( displayVals ); displayVals(); </script> </div> <div></div> <div></div> </div> <script> $('#1 h1').click(function(){ $('#1').addClass('red'); }) $('#b2').click(function(){ $('#2 img').slideToggle('slow'); }) $('#b3').click(function(){ $('#3 p').append(document.createTextNode(' Please give those baby red pandas some love!')); }) $('#b4').click(function(){ $('#4').hide('slow'); }) $('#b5').click(function(){ $('#4').show('slow'); }) $('#b6').click(function(){ $('#1').toggle(function(){ $('#1').css('border', 'none'); }) }) $('#b7').click(function(){ if ($('#6 h1').is(':hidden')) { $('#6 h1').slideDown( 'slow' ); } else { $('#6 h1').hide( 'p' ); } }) $('#b8').click(function(){ if ($('#7 h1').is(':hidden')) { $('#7 h1').show('slow'); } else { $('#7 h1').slideUp('slow'); } }) $('#9').hover(function(){ if ($('#9 img').is(':hidden')) { $('#9 img').fadeIn('100'); } else { $('#9 img').fadeOut('500'); } }) $('#b10').click(function(){ $('#10 p').before('<img src="sprite.png" alt="Red panda sprite" class="pic1">'); }) $('#b11').click(function(){ $('#11 p').after('<img src="sprite.png" alt="Red panda sprite" class="pic1">'); }) $('#b12').click(function(){ $('#12').html('<p>What is your favorite thing about red pandas?<br><select><option value="cuteness">Cuteness</option><option value="stripes">Stripes</option><option value="everything">EVERYTHING!!!</option>'); }) $('#b13').click(function(){ $('#2 .pic1').attr({ src: 'tree.jpg' }); }) $('#b14').click(function(){ }) </script> </body> </html>
import React, { useContext } from "react"; import { Link, useNavigate } from "react-router-dom"; import { AuthContext } from "../../provider/AuthProvider"; import { useForm } from "react-hook-form" import useAuth from "../../hooks/useAuth"; const Login = () => { const {user, signIn, signInWithGoogle} = useAuth() const navigate = useNavigate() const { register, handleSubmit, reset } = useForm() const onSubmit = (data) => ( signIn(data.email, data.password).then(res=> { navigate("/dashboard") console.log(res.user); }) ) const handleGoogleLogin = () => { signInWithGoogle() .then(() => { navigate("/dashboard"); }) .catch((error) => { console.log(error); }); }; return ( <div> <div className="hero bg-base-200 py-32"> <div className="hero-content"> <div className="card shrink-0 w-full shadow-2xl bg-base-100"> <form className="card-body" onSubmit={handleSubmit(onSubmit)}> <div className="form-control"> <label className="label"> <span className="label-text">Email</span> </label> <input {...register("email")} type="email" placeholder="email" className="input input-bordered" required /> </div> <div className="form-control"> <label className="label"> <span className="label-text">Password</span> </label> <input {...register("password")} type="password" placeholder="password" className="input input-bordered" required /> </div> <div className="form-control mt-6"> <input type="submit" value="Log in" className="btn btn-primary"></input> </div> </form> <p className="text-center">Don't have any account? <Link to={"/signup"}>SignUp</Link></p> <div className="divider mx-8">OR</div> <div className="form-control mx-8 mb-8" onClick={handleGoogleLogin}> <button className="btn"> <img className="w-[37px]" src="https://i.ibb.co/dBTSL19/icons8-google-48.png" /> Login with Google </button> </div> </div> </div> </div> </div> ); }; export default Login;
// 1 enum UserEducationEnum { HIGHER = 'higher', MIDDLE = 'middle', DONT_HAVE = 'dontHave' } type TUser = { name: string, age: number hasJob: boolean, education: UserEducationEnum children: string[] experience: [number?, string?] } const userAlex: TUser = { name: 'Alex', age: 25, hasJob: true, education: UserEducationEnum.HIGHER, children: ['qwer', 'asdf'], experience: [5, 'Google'] } const transformUserData = (user: TUser): string => { const { name, age, hasJob, education, children, experience: [years, job] } = user return ` Name: ${name} Age: ${age} Has job: ${hasJob} Education: ${education} Children: ${!!children.length ? children.join(', ') : '-'} Experience: worked in ${job}, ${years} year(s) ` } console.log(transformUserData(userAlex)) //2 const lastIndex = (str: string, char: string): number | null => { const index = str.lastIndexOf(char); return index === -1 ? null : index; } interface IUser { name: string, age: number, hasJob: boolean, } const getUsername = (user: IUser): string => { const { name } = user return name } //3 type TTransformToOption<T extends object> = { [P in keyof T]?: T[P] } type TPartUser = TTransformToOption<TUser> type IfArray<T extends object, P> = T extends any[] ? T : P type TArray = [number, string] type TObj = { name: string } type Option = IfArray<TArray, TObj> //4 function sealed(constructor: Function) { console.log("sealed decorator"); Object.seal(constructor); Object.seal(constructor.prototype); } interface IVehicle { get: () => string set: (speed: number) => number } @sealed abstract class Car implements IVehicle{ constructor( protected brand: string, protected color: string, protected maxSpeed: number, ) {} get(): string { return this.brand } set(speed: number): number { return this.maxSpeed += speed } } class Audi extends Car{ constructor( readonly type: string, protected color: string, protected maxSpeed: number ) { super('Audi', color, maxSpeed); this.type = type } getFullInfo(): string { return ` Brand: ${this.brand}, Type: ${this.type} Color: ${this.color} Max speed: ${this.maxSpeed} ` } }
import { Link } from '@components/atoms'; import Container from '@components/Container'; import { ArrowForward, KeyboardArrowLeft, KeyboardArrowRight, } from '@mui/icons-material'; import { Box, Button, Checkbox, Divider, FormControlLabel, Paper, Stack, Step, StepLabel, Stepper, Typography, } from '@mui/material'; import { alpha, useTheme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; import { AddDeviceIllustration2 } from '@svg/illustrations'; // import { requestPermission } from '@utils/Firebase/firebaseMessaging'; import { useRouter } from 'next/router'; import { ReactNode, createContext, useState } from 'react'; import { Minimal } from '../../layouts'; import { ConnectionForm, Form } from './components'; export const EnterDeviceContext = createContext({ handleNext: () => {}, }); const steps = ['Add device', 'Connectivity', 'Finish']; const EnterDeviceIdView = (): JSX.Element => { const router = useRouter(); const theme = useTheme(); const isSm = useMediaQuery(theme.breakpoints.down('sm'), { defaultMatches: true, }); const [value, setValue] = useState(0); const [activeStep, setActiveStep] = useState<number>(0); const [skipped, setSkipped] = useState(new Set<number>()); const isStepOptional = (step: number) => step === 1; const isStepSkipped = (step: number) => skipped.has(step); const handleNext = () => { let newSkipped = skipped; if (isStepSkipped(activeStep)) { newSkipped = new Set(newSkipped.values()); newSkipped.delete(activeStep); } setActiveStep((prevActiveStep) => prevActiveStep + 1); setSkipped(newSkipped); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleSkip = () => { if (!isStepOptional(activeStep)) { // You probably want to guard against something like this, // it should never occur unless someone's actively trying to break something. throw new Error("You can't skip a step that isn't optional."); } setActiveStep((prevActiveStep) => prevActiveStep + 1); setSkipped((prevSkipped) => { const newSkipped = new Set(prevSkipped.values()); newSkipped.add(activeStep); return newSkipped; }); }; // const steps = [page1, page2, page3]; const activePage = (page: number) => { switch (page) { case 0: return ( <Box paddingTop={12}> <Box height={1} width={1} maxWidth={500}> <Typography variant="h6" gutterBottom> Let&apos;s setup your device first. </Typography> <Typography variant={'body2'} color={'text.secondary'}> The device ID will help you to control your purchased device from Almond. Kindly enter the 8 digit provided on purchase. </Typography> </Box> <Box paddingY={{ xs: 3, md: 4 }}> <Divider /> </Box> <Box width={1} maxWidth={500}> <Form handleNext={handleNext} /> </Box> </Box> ); case 1: return ( <Box paddingTop={12}> <Box height={1} width={1} maxWidth={500}> <Typography variant="h6" gutterBottom> Checking your connectivity status. </Typography> <Typography variant={'body2'} color={'text.secondary'}> Setup your WIFI configuration for the device. Make sure your device is powered on to complete this step. </Typography> </Box> <Box paddingY={{ xs: 3, md: 4 }}> <Divider /> </Box> <Box height={1} width={1} maxWidth={500} paddingBottom={5}> <ConnectionForm /> </Box> </Box> ); case 2: return ( <Box paddingTop={12}> <Box height={1} width={1} maxWidth={500}> <Typography variant="h6" gutterBottom> Just a minute. How about notifications? </Typography> <Typography variant={'body2'} color={'text.secondary'}> Your device has been setup successfully. Below are some of the default notification settings to receive from your device. </Typography> <Box paddingY={{ xs: 3, md: 4 }}> <Divider /> </Box> <Box> <Box> <FormControlLabel control={<Checkbox color="primary" />} label="Push notifications" // onChange={requestPermission} /> </Box> <Box> <FormControlLabel control={<Checkbox color="primary" />} label="E-mail alerts" /> </Box> <Box> <FormControlLabel control={<Checkbox color="primary" />} label="Text messages" /> </Box> </Box> <Box paddingTop={4}> <Button fullWidth variant="contained" type="submit" color="primary" size="large" > Save </Button> </Box> </Box> </Box> ); default: return ( <> <Box height={1} width={1} maxWidth={300} paddingBottom={1}> <AddDeviceIllustration2 /> </Box> <Box height={1} width={1} maxWidth={500}> <Typography variant={'subtitle2'} color={'text.secondary'}> Setup your WIFI configuration for the device. Make sure your device is powered on to complete this step. </Typography> </Box> <Box paddingY={2}> <Divider /> </Box> </> ); } }; const renderBottomNavigation = (): JSX.Element => ( <Box sx={{ minWidth: 500 }}> <Paper sx={{ position: 'fixed', bottom: 0, left: 0, right: 0, // background: theme.palette.alternate.main, paddingY: 1, borderTop: `1px solid ${alpha(theme.palette.divider, 0.1)}`, paddingX: 0, // borderTop: `1px solid ${alpha(theme.palette.divider, 0.1)}`, }} elevation={0} > <Stack direction="row" justifyContent="space-around" alignItems="center" spacing={2} > <Button variant="text" onClick={handleBack} disabled={activeStep === 0} startIcon={ theme.direction === 'rtl' ? ( <KeyboardArrowRight /> ) : ( <KeyboardArrowLeft /> ) } > Back </Button> <Button variant="text" onClick={handleNext} endIcon={ theme.direction === 'rtl' ? ( <KeyboardArrowLeft /> ) : ( <KeyboardArrowRight /> ) } > {activeStep === steps.length - 1 ? 'Finish' : isStepOptional(activeStep) ? 'Skip' : 'Next'} </Button> </Stack> </Paper> </Box> ); const maxSteps = steps.length; const background = '/img/background_illustration.svg'; return ( <EnterDeviceContext.Provider value={{ handleNext }}> <Minimal> <Container maxWidth={{ sm: 720, md: 960 }} sx={{ backgroundImage: `url(${background})`, backgroundPositionX: 'center', backgroundRepeat: 'no-repeat', }} > <Stack direction={'column'} justifyContent="space-around" alignItems="center" spacing={2} > <Box // height={1} width={1} // maxWidth={700} // paddingBottom={{ xs: 0, md: 6 }} > <Stepper activeStep={activeStep} alternativeLabel={isSm}> {steps.map((label, index) => { const stepProps: { completed?: boolean } = {}; const labelProps: { optional?: ReactNode; } = {}; // if (isStepOptional(index)) { // labelProps.optional = ( // <Typography variant="caption">(Optional)</Typography> // ); // } if (isStepSkipped(index)) { stepProps.completed = false; } return ( <Step key={label} {...stepProps}> <StepLabel {...labelProps}>{label}</StepLabel> </Step> ); })} </Stepper> </Box> {activeStep === steps.length ? ( <Stack direction={'column'} justifyContent="space-evenly" alignItems="center" spacing={3} > <Box height={400}> <AddDeviceIllustration2 /> </Box> <Typography variant="h6" gutterBottom> Hooray!! You&apos;re all set! </Typography> <Box> <Button component={Link} href="/dashboard" fullWidth variant="contained" color="primary" size="large" endIcon={<ArrowForward />} > Go to dashboard </Button> </Box> </Stack> ) : ( <>{activePage(activeStep)}</> )} </Stack> {renderBottomNavigation()} </Container> </Minimal> </EnterDeviceContext.Provider> ); }; export default EnterDeviceIdView;
import React, { useEffect, useRef, useState } from "react"; import { Table, Button, Modal, Form, Input, Select, InputNumber, Rate, DatePicker, Row, Col, } from "antd"; import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, } from "@ant-design/icons"; import { dishes, restaurants } from "../../data/fakeData"; import "../../styles/styles.css"; import moment from "moment"; import OrderAPI from "../../API/OrderAPI"; const { Option } = Select; const { RangePicker } = DatePicker; const OrderAllManagement = () => { const [orderData, setOrderData] = useState([]); const [isModalVisible, setIsModalVisible] = useState(false); const [rowSelected, setRowSelected] = useState(""); const [dates, setDates] = useState([]); const getAllOrders = async () => { const res = OrderAPI.Get_All(); return res; }; useEffect(() => { const fetchData = async () => { try { const data = await getAllOrders(); setOrderData(data); } catch (error) { console.log("err", error); } }; fetchData(); }, [isModalVisible]); const showModal = () => { setIsModalVisible(true); }; const handleDeleteOrder = async () => { const res = await OrderAPI.Delete_Admin(rowSelected); if (res.status === "SUCCESS") { handleCancel(); } }; const handleCancel = () => { setIsModalVisible(false); setRowSelected(""); }; const handleDateChange = (dates) => { setDates(dates); }; const handleSearchByDate = () => { if (dates.length === 2) { const [start, end] = dates; const filtered = orderData.filter((dish) => { const createdAt = moment(dish.created_at); return createdAt.isBetween(start, end, "days", "[]"); }); setOrderData(filtered); } }; const [searchText, setSearchText] = useState(""); const [searchedColumn, setSearchedColumn] = useState(""); const searchInput = useRef(null); const handleSearch = (selectedKeys, confirm, dataIndex) => { confirm(); setSearchText(selectedKeys[0]); setSearchedColumn(dataIndex); }; const handleReset = (clearFilters) => { clearFilters(); setSearchText(""); }; const getColumnSearchProps = (dataIndex) => ({ filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, }) => ( <div style={{ padding: 8, }} onKeyDown={(e) => e.stopPropagation()} > <input ref={searchInput} placeholder={`Search ${dataIndex}`} value={selectedKeys[0]} onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : []) } onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)} style={{ marginBottom: 8, display: "block", }} /> <Button type="primary" onClick={() => handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined />} size="small" style={{ width: 90, }} > Search </Button> <Button onClick={() => clearFilters && handleReset(clearFilters)} size="small" style={{ width: 90, }} > Reset </Button> </div> ), filterIcon: (filtered) => ( <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined, }} /> ), onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()), onFilterDropdownOpenChange: (visible) => { if (visible) { setTimeout(() => searchInput.current?.select(), 100); } }, }); const columns = [ { title: "Quán Ăn", dataIndex: "restaurant_name", key: "restaurant_name", sorter: (a, b) => a.restaurant_name.length - b.restaurant_name.length, ...getColumnSearchProps("restaurant_name"), }, { title: "Tên khách hàng", dataIndex: "name", key: "name", sorter: (a, b) => a.name.length - b.name.length, ...getColumnSearchProps("name"),}, { title: "Số điện thoại", dataIndex: "phone", sorter: (a, b) => a.phone - b.phone, ...getColumnSearchProps("phone"), }, { title: "Địa chỉ", dataIndex: "address", ...getColumnSearchProps("address"), }, { title: "Món ăn", dataIndex: "dishes", sorter: (a, b) => (a.dishes || []).length - (b.dishes || []).length, ...getColumnSearchProps("dishes"), render: (dishes) => ( <div> {Array.isArray(dishes) && dishes.length > 0 ? ( dishes.map((dish, index) => ( <div key={index} style={{ marginBottom: "5px" }}> <p> <strong>Tên món:</strong> {dish.name} </p> <p> <strong>Giá:</strong> {dish.price} </p> <p> <strong>Số lượng:</strong> {dish.quantity} </p> <br></br> </div> )) ) : ( <p>Không có món nào</p> )} </div> ), }, { title: "Tiền", dataIndex: "money", sorter: (a, b) => (a.money || []).length - (b.money || []).length, ...getColumnSearchProps("dishes"), render: (money) => ( <div> {Array.isArray(money) && money.length > 0 ? ( money.map((item, index) => ( <div key={index} style={{ marginBottom: "5px" }}> <p> <strong>Giá tiền:</strong> {item.price} </p> <p> <strong>Phí ship:</strong> {item.ship} </p> <p> <strong>Giảm giá:</strong> {item.discount} </p> <p> <strong>Tổng tiền:</strong> {item.total_amount} </p> <br></br> </div> )) ) : ( <p>Trống</p> )} </div> ), }, { title: "Ghi chú", dataIndex: "option", ...getColumnSearchProps("option"), }, { title: "Hành động", key: "actions", render: (text, record) => ( <div className="action-buttons"> <Button className="pink-button" icon={<DeleteOutlined />} onClick={() => handleDeleteOrder(rowSelected)} > Xóa </Button> </div> ), }, ]; return ( <div className="owner-container"> <Row className="button-container" gutter={[16, 16]}> <Col> <DatePicker placeholder="Từ ngày" onChange={(date) => handleDateChange([date, dates[1]])} /> </Col> <Col> <DatePicker placeholder="Đến ngày" onChange={(date) => handleDateChange([dates[0], date])} /> </Col> <Col> <Button type="primary" icon={<SearchOutlined />} onClick={handleSearchByDate} > Tìm kiếm </Button> </Col> </Row> <Table dataSource={orderData} columns={columns} rowKey="id" onRow={(record, rowIndex) => { return { onClick: (event) => { setRowSelected(record.id); }, }; }} /> </div> ); }; export default OrderAllManagement;
{% extends 'base.html' %} {% block content %} {% load static %} <section class="contain mb-10"> <div class="flex flex-col gap-4 justify-center items-center mt-10 mb-10"> <img src="{% static 'media/calculator-logo.svg' %}" alt="CaloRight Logo" class="w-40 -mr-8"> <h1 class="text-4xl lg:text-5xl text-green text-center" id="anchor">Calorie <br> Calculator</h1> <h2 style="color: #508278;" class="max-w-lg text-center">Use the calorie calculator to estimate the number of daily calories your body needs to maintain your current weight.</h2> </div> </section> <section class="contain mb-20"> <div class="box-content max-w-[550px] m-auto rounded-full flex justify-center text-center align-center flex-col p-7 text-white mb-4" style="background: #508278;"> <p class="lg:text-3xl text-xl font-bold" id="result">Suggested Calorie <small>(per day)</small></p> </div> <div class="flex items-center justify-center "> <div class="mx-auto w-full max-w-[550px] p-12 border-4 border-green-300 rounded"> <form id="calculate_form"> <div class="mb-5"> <label for="age" class="mb-3 block text-base font-medium text-white"> Age <small> (in years)</small> </label> <input type="number" name="age" id="age" placeholder="Enter your Age" class="w-full rounded bg-transparent border border-white/10 py-3 px-6 text-base font-medium text-white outline-none focus:outline-none focus:border-green-300 focus:ring-1 focus:ring-green-500" required /> </div> <div class="mb-5"> <label for="height" class="mb-3 block text-base font-medium text-white"> Height <small> (in cm)</small> </label> <input type="number" name="height" id="height" placeholder="Enter your Height" class="w-full rounded bg-transparent border border-white/10 py-3 px-6 text-base font-medium text-white outline-none focus:outline-none focus:border-green-300 focus:ring-1 focus:ring-green-500" required /> </div> <div class="mb-5"> <label for="weight" class="mb-3 block text-base font-medium text-white"> Weight <small> (in kg)</small> </label> <input type="number" name="weight" id="weight" placeholder="Enter your weight" class="w-full rounded bg-transparent border border-white/10 py-3 px-6 text-base font-medium text-white outline-none focus:outline-none focus:border-green-300 focus:ring-1 focus:ring-green-500" required /> </div> <div class="flex gap-4 mb-5"> <div class="form-check form-check-inline"> <input class="form-check-input form-check-input appearance-none rounded-full h-4 w-4 border border-gray-300 bg-white checked:bg-green-300 checked:border-green-300 focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="radio" checked name="sex" id="sex_male" value="male"> <label class="form-check-label inline-block text-white" for="sex_male">Male</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input form-check-input appearance-none rounded-full h-4 w-4 border border-gray-300 bg-white checked:bg-green-300 checked:border-green-300 focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="radio" name="sex" id="sex_female" value="female"> <label class="form-check-label inline-block text-white" for="sex_female">Female</label> </div> </div> <div class="flex w-full"> <div class="mb-3 w-full"> <label class="form-check-label inline-block text-white mb-4" for="level">Activity Level</label> <select class="form-select form-select-lg mb-3 block w-full px-4 py-4 text-base font-normal text-white bg-transparent border border-solid border-white/10 rounded transition ease-in-out m-0 outline-none focus:outline-none focus:border-green-300 focus:ring-1 focus:ring-green-500" aria-label=" .form-select-lg example" id="level" name="level"> <option value="1.2" selected>Sedentary</option> <option value="1.375">Lightly active</option> <option value="1.55">Moderately active</option> <option value="1.725">Very active</option> <option value="1.9">Extra active</option> </select> </div> </div> <div> <button type="submit" class="w-full hover:shadow-form bg-green-300 rounded bg-green text-black uppercase py-3 px-8 text-base font-semibold outline-none"> Calculate </button> </div> </form> </div> </div> </section> <section class="contain mb-20"> <h1 class="text-2xl lg:text-3xl text-green text-center">Activity Level Information:</h1> <div class="flex flex-col md:flex-row flex-wrap gap-4 justify-center mt-8"> <div class="w-full md:w-1/3 p-4 border border-white/10 flex flex-col justify-center"> <h2 class="font-bold">Sedentary</h2> <p>Never or rarely include physical activity in your day.</p> </div> <div class="w-full md:w-1/3 p-4 border border-white/10 flex flex-col justify-center"> <h2 class="font-bold">Lightly active</h2> <p>Light exercise/sports 1-3 days/week</p> </div> <div class="w-full md:w-1/3 p-4 border border-white/10 flex flex-col justify-center"> <h2 class="font-bold">Moderately active </h2> <p>Moderate exercise/sports 3-5 days/week</p> </div> <div class="w-full md:w-1/3 p-4 border border-white/10 flex flex-col justify-center"> <h2 class="font-bold">Very active </h2> <p>Hard exercise/sports 6-7 days a week</p> </div> </div> </section> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script> <script> jQuery(document).ready(function () { $('#calculate_form').submit(function (e) { e.preventDefault(); // Get all the forms elements and their values in one step var age = $("#age").val(); var height = $("#height").val(); var weight = $("#weight").val(); var sex = $("input[name='sex']:checked").val(); var level = $("#level option:selected").val(); console.log(age, height, weight, sex, level); if (sex === 'male') { var bmr = 66.5 + (13.75 * weight) + (5.003 * height) - (6.75 * age); computed = bmr * level; $("#result").text(computed.toFixed(2) + " Calories/day"); location.hash = "anchor"; } else if (sex === 'female') { var bmr = 655.1 + (9.563 * weight) + (1.850 * height) - (4.676 * age); computed = bmr * level; $("#result").text(computed.toFixed(2) + " Calories/day"); location.hash = "anchor"; } else { $("#result").text('There is something wrong...'); location.hash = "anchor"; } }); }); </script> {% endblock content %}
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class () extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('statistics', function (Blueprint $table) { $table ->id()->startingValue(0)->primary(); $table ->string("user_id"); $table->foreign("user_id")->references("id")->on("users"); $table ->integer("step_count"); $table ->integer("stair_step_count"); $table ->float("heart_rate"); $table ->float("distance"); $table ->date("datetime"); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('statistics'); } };
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-autowire="byName"> <context:component-scan base-package="be.fabrice.circular"></context:component-scan> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.p6spy.engine.spy.P6SpyDriver" /> <property name="username" value="h2" /> <property name="url" value="jdbc:p6spy:h2:mem:test-bidirectionnel;MVCC=TRUE" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true hibernate.hbm2ddl.auto=create-drop </value> </property> <property name="packagesToScan" value="be.fabrice.circular" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
using Common; using ScintillaNET; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Xml.Linq; using VisionCore; using static ScintillaNET.Style; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace Plugin.VBScript { /// <summary> /// ModuleFrm.xaml 的交互逻辑 /// </summary> public partial class ModuleFrm : PluginFrmBase { private ModuleObj frm_ModuleObj; private string m_AutoStr;//自动提示的关键字 private Dictionary<string, ScriptMethodInfo> methodDic = new Dictionary<string, ScriptMethodInfo>();//脚本方法字典, public ScriptSupport m_TempScriptSupport = new ScriptSupport(); public ModuleFrm() { InitializeComponent(); this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight - 16; this.MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth; this.Loaded += ModuleFrm_Loaded; } private void ModuleFrm_Loaded(object sender, RoutedEventArgs e) { //加载参数 frm_ModuleObj = (ModuleObj)m_ModuleObjBase; //窗体名称 Title.HeadName = frm_ModuleObj.ModuleParam.ModuleName; //模块当前ID CurrentModelID = frm_ModuleObj.ModuleParam.ModuleName; m_MyEditer.Text = frm_ModuleObj.InCode; //初始化控件 InitScintilla(); InitTxt(); } private void InitTxt() { string str = "\"";//单引号 string str1 = "\"," + str;// ", #region VB基本语法 //数据声明 RichtxtboxInput(System.Windows.Media.Brushes.Green, "VB基本语法"); //数据声明 RichtxtboxInput(System.Windows.Media.Brushes.Red, "1、数据声明"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim int As Integer = 0"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim str As String = \"\""); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim flag As Boolean = False"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim dbl As Double = 0.0"); //数组声明 RichtxtboxInput(System.Windows.Media.Brushes.Red, "2、数组声明"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim arrayl(3) As Integer '3是个数"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim array2 As Integer() = {2, 4, 8}"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim list As New List(Of String)"); //判断 RichtxtboxInput(System.Windows.Media.Brushes.Red, "3、判断"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "If True Then\r\n'do something\r\nEnd If"); //循环 RichtxtboxInput(System.Windows.Media.Brushes.Red, "4、循环"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "For index As Integer = 1 To 10\r\n'do something\r\nNext"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "While True\r\n'do something\r\nEnd While"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "For Each i As Integer In arrayl\r\n\r\nNext"); //分割字符 RichtxtboxInput(System.Windows.Media.Brushes.Red, "5、分割字符"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Dim arr As String() = \"sa;ba;ca\".Split(\";\")"); #endregion #region 其他函数 //数据声明 RichtxtboxInput(System.Windows.Media.Brushes.Green, "其他函数"); //打印日志 RichtxtboxInput(System.Windows.Media.Brushes.Red, "1、打印日志"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "MessageBox(string)"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "Show(" + str + "string" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "2、打印Log日志"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "LogInfo(" + str + "打印内容" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "3、获取系统时间"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "GenDateTime(" + str + "格式" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "4、图像显示内容"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "ShowHwindowText(" + str + "流程名称" + str1 + "模块名称" + str1 + "描述" + str1 + "显示内容" + str1 + "颜色" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "5、根据变量名称,获取全局变量的数据"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "GetGlobalValue(" + str + "全局变量名称" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "6、根据变量名称,设置变量值"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "SetGlobalValue(" + str + "全局变量名称" + str1 + "输入值" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "7、根据流程名称,获取模块的数据"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "GetModuleValue(" + str + "流程名称" + str1 + "模块名称" + str1 + "变量名称" + str + ")"); RichtxtboxInput(System.Windows.Media.Brushes.Red, "8、根据流程名称,修改模块的数据"); RichtxtboxInput(System.Windows.Media.Brushes.Blue, "SetModuleValue(" + str + "流程名称" + str1 + "模块名称" + str1 + "变量名称" + str1 + "值" + str + ")"); #endregion } FlowDocument Doc = new FlowDocument(); private void RichtxtboxInput(System.Windows.Media.Brush brush, string txt) { Run item = new Run(txt); Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(item); paragraph.LineHeight = 1.0; paragraph.Foreground = brush; this.Txt_Tip.Document.Blocks.Add(paragraph); } #region sci控件 /// <summary> /// 初始化染色控件 /// </summary> private void InitScintilla() { // 字体包裹模式 m_MyEditer.WrapMode = WrapMode.None; //高亮显示 InitSyntaxColoring(m_MyEditer); //自定义关键字代码提示功能 m_MyEditer.AutoCIgnoreCase = true;//代码提示的时候,不区分大小写 AutoComplete(); // 这两种操作会导致乱码 m_MyEditer.ClearCmdKey(Keys.Control | Keys.S); m_MyEditer.ClearCmdKey(Keys.Control | Keys.F); m_MyEditer.AutoCCompleted += m_MyEditer_AutoCCompleted; } //自动补全时出现 private void m_MyEditer_AutoCCompleted(object sender, AutoCSelectionEventArgs e) { string tip = ShowTipByWord(); //tip提示 if (!string.IsNullOrWhiteSpace(tip)) { m_MyEditer.CallTipShow(m_MyEditer.CurrentPosition, tip); } } private void InitTipSyntaxColoring(Scintilla scintilla) { // 设置默认格式 scintilla.StyleResetDefault(); scintilla.Styles[ScintillaNET.Style.Default].Font = "Consolas"; scintilla.Styles[ScintillaNET.Style.Default].Size = 9; //scintilla.Styles[ScintillaNET.Style.Default].BackColor = System.Drawing.SystemColors.Control; //背景色 scintilla.Styles[ScintillaNET.Style.Default].ForeColor = System.Drawing.Color.Black; scintilla.Styles[ScintillaNET.Style.Default].BackColor = System.Drawing.Color.Pink; scintilla.ScrollWidth = 100;//设置水平滚动条为100 这样水平就不会默认显示滚动条 //普通代码的颜色 scintilla.Styles[ScintillaNET.Style.Vb.Comment].ForeColor = ColorTranslator.FromHtml("#008000"); scintilla.Styles[ScintillaNET.Style.Vb.Number].ForeColor = ColorTranslator.FromHtml("#FF6532"); scintilla.Styles[ScintillaNET.Style.Vb.String].ForeColor = ColorTranslator.FromHtml("#A31515"); scintilla.Styles[ScintillaNET.Style.Vb.Preprocessor].ForeColor = IntToColor(0x8AAFEE); //操作符 scintilla.Styles[ScintillaNET.Style.Vb.Operator].ForeColor = ColorTranslator.FromHtml("#A31515"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword].ForeColor = ColorTranslator.FromHtml("#0000FF"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword2].ForeColor = ColorTranslator.FromHtml("#5CBAC7"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword3].ForeColor = System.Drawing.Color.Red;// ColorTranslator.FromHtml("#0000FF"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword4].ForeColor = ColorTranslator.FromHtml("#0000FF"); //每个关键字的都有自己单独的背景色 ,没有找到统一设置背景色的方法!!!!故如此使用 foreach (ScintillaNET.Style item in scintilla.Styles) { if (item.BackColor == System.Drawing.Color.White) { item.BackColor = System.Drawing.SystemColors.Control; } } scintilla.Lexer = Lexer.Vb; // 可以设置两种颜色的关键字 输入只支持小写 //对应ScintillaNET.Style.Vb.Keyword scintilla.SetKeywords(0, ScriptTemplate.VBString().ToLower()); // //对应ScintillaNET.Style.Vb.Keyword2 string s2 = GetMethodsString(); scintilla.SetKeywords(1, s2.ToLower()); //行号字体颜色 scintilla.Styles[ScintillaNET.Style.LineNumber].ForeColor = ColorTranslator.FromHtml("#8DA3C1"); //行号相关设置 var nums = scintilla.Margins[1]; nums.Width = 30; nums.Type = MarginType.Number; nums.Sensitive = true; nums.Mask = 0; } //设置语法高亮规则 private void InitSyntaxColoring(Scintilla scintilla) { // 设置默认格式 scintilla.StyleResetDefault(); scintilla.Styles[ScintillaNET.Style.Default].Font = "Consolas"; scintilla.Styles[ScintillaNET.Style.Default].Size = 10; //前景色 scintilla.Styles[ScintillaNET.Style.Default].ForeColor = System.Drawing.Color.Black; //背景色 //scintilla.Styles[ScintillaNET.Style.Default].BackColor = System.Drawing.Color.Black; scintilla.StyleClearAll(); scintilla.ScrollWidth = 100;//设置水平滚动条为100 这样水平就不会默认显示滚动条 //普通代码的颜色 scintilla.Styles[ScintillaNET.Style.Vb.Comment].ForeColor = ColorTranslator.FromHtml("#008000"); scintilla.Styles[ScintillaNET.Style.Vb.Number].ForeColor = ColorTranslator.FromHtml("#FF6532"); scintilla.Styles[ScintillaNET.Style.Vb.String].ForeColor = ColorTranslator.FromHtml("#A31515"); scintilla.Styles[ScintillaNET.Style.Vb.Preprocessor].ForeColor = IntToColor(0x8AAFEE); //操作符 scintilla.Styles[ScintillaNET.Style.Vb.Operator].ForeColor = ColorTranslator.FromHtml("#A31515"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword].ForeColor = ColorTranslator.FromHtml("#0000FF"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword2].ForeColor = ColorTranslator.FromHtml("#5CBAC7"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword3].ForeColor = System.Drawing.Color.Red;// ColorTranslator.FromHtml("#0000FF"); scintilla.Styles[ScintillaNET.Style.Vb.Keyword4].ForeColor = ColorTranslator.FromHtml("#0000FF"); scintilla.Lexer = Lexer.Vb; // 可以设置两种颜色的关键字 输入只支持小写 //对应ScintillaNET.Style.Vb.Keyword scintilla.SetKeywords(0, ScriptTemplate.VBString().ToLower()); // //对应ScintillaNET.Style.Vb.Keyword2 string s2 = GetMethodsString(); scintilla.SetKeywords(1, s2.ToLower()); //行号字体颜色 scintilla.Styles[ScintillaNET.Style.LineNumber].ForeColor = ColorTranslator.FromHtml("#8DA3C1"); //行号相关设置 var nums = scintilla.Margins[1]; nums.Width = 30; nums.Type = MarginType.Number; nums.Sensitive = true; nums.Mask = 0; // TextArea.MarginClick += TextArea_MarginClick; } //代码提示功能 public void AutoComplete() { //绑定输入事件 m_MyEditer.CharAdded += Scintilla_CharAdded; string s = GetMethodsString(); string str = ScriptTemplate.VBString() + " " + s; //获取 //分割字符串成list List<string> autoStrList = str.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList(); //对list排序重新转换为string m_AutoStr = string.Join(" ", autoStrList.OrderBy(x => x.ToUpper())); } //输入结束事件 private void Scintilla_CharAdded(object sender, CharAddedEventArgs e) { // Find the word start var currentPos = m_MyEditer.CurrentPosition; var wordStartPos = m_MyEditer.WordStartPosition(currentPos, true); // Display the autocompletion list var lenEntered = currentPos - wordStartPos; if (lenEntered > 0) { if (!m_MyEditer.AutoCActive) { //此处必须是按照字母排序才能显示出来 m_MyEditer.AutoCShow(lenEntered, m_AutoStr); } } // ShowTipByWord(); } //转换color public static System.Drawing.Color IntToColor(int rgb) { return System.Drawing.Color.FromArgb(255, (byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); } /// <summary> /// 根据word 在tip窗口显示提示 /// </summary> private string ShowTipByWord() { // Find the word start var currentPos = m_MyEditer.CurrentPosition; var wordStartPos = m_MyEditer.WordStartPosition(currentPos, true); var wordEndPos = m_MyEditer.WordEndPosition(currentPos, true); string word = m_MyEditer.GetTextRange(wordStartPos, wordEndPos - wordStartPos); string tip = ""; if (!string.IsNullOrWhiteSpace(word)) { if (methodDic.ContainsKey(word)) { tip = methodDic[word].Description; tb_Compile.Text = tip; } } return tip;//返回提示信息 } //获取当前程序集指定方法 public string GetMethodsString() { List<string> strList = new List<string>(); List<Type> typeList = new List<Type>(); typeList.Add(typeof(Object)); typeList.Add(typeof(Math)); typeList.Add(typeof(string)); typeList.Add(typeof(System.Collections.Generic.List<double>)); typeList.Add(typeof(Enumerable)); typeList.Add(typeof(System.Windows.MessageBox)); // typeList.Add(typeof(ScriptMethods)); foreach (Type item in typeList) { if (item.IsEnum == true) { string[] rolearry = Enum.GetNames(item); strList.AddRange(rolearry); strList.Add(item.Name); } else { //添加type的方法 MethodInfo[] methods = item.GetMethods(); foreach (MethodInfo m in methods) { strList.Add(m.ToString().Split(' ')[1].Split('(')[0].Replace("set_", "").Replace("get_", "").Split('[')[0]); } strList.Add(item.Name); } } //自定义提示 strList.Add("List(OfInteger)"); strList.Add("List(OfDouble)"); strList.Add("List(OfBoolean)"); strList.Add("List(OfString)"); return string.Join(" ", strList.Distinct().ToList().OrderBy(x => x.ToUpper())); ; } #endregion /// <summary> /// 编译 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Compile_Click(object sender, RoutedEventArgs e) { try { Compile(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); Log.Error(ex.ToString()); } } /// <summary> /// 执行模块 /// </summary> public override void ExModule() { try { //删除本ID的变量 int proIndex = SysProcessPro.g_ProjectList.FindIndex(c => c.ProjectInfo.m_ProjectID == frm_ModuleObj.ModuleParam.ProjectID); if (proIndex > -1) { SysProcessPro.g_ProjectList[proIndex].m_Var_List.RemoveAll(c => c.m_DataTip.Contains(frm_ModuleObj.ModuleParam.ModuleName)); } Compile(); m_TempScriptSupport.CodeRun(); //frm_ModuleObj.InCode = m_MyEditer.Text; //frm_ModuleObj.ScriptSupport = m_TempScriptSupport; //frm_ModuleObj.ExeModule(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); Log.Error(ex.ToString()); } } /// <summary> /// 保存参数 /// </summary> public override void SaveModuleParam() { base.SaveModuleParam(); frm_ModuleObj.InCode = m_MyEditer.Text; frm_ModuleObj.ScriptSupport = m_TempScriptSupport; this.Close(); } /// <summary> /// 编译 /// </summary> public void Compile() { m_TempScriptSupport.Source = ScriptTemplate.GetScriptCode(frm_ModuleObj.ModuleParam.ProjectID, frm_ModuleObj.ModuleParam.ModuleName, m_MyEditer.Text); if (m_TempScriptSupport.Compile()) { tb_Compile.Text = "编译成功"; } else { tb_Compile.TextWrapping = TextWrapping.Wrap; tb_Compile.Text = m_TempScriptSupport.ErrorText; } } /// <summary> /// 窗体关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Title_CloseWindow(object sender, RoutedEventArgs e) { CancelModuleParam(); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gerenciamento de Usuários</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h2 { margin-bottom: 10px; } form { margin-bottom: 20px; } table { width: 100%; border-collapse: collapse; margin-top: 10px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <!-- Formulário para cadastrar usuários --> <div> <h2>Cadastrar Usuário</h2> <form id="usuarioForm"> <label for="nomeUsuario">Nome:</label> <input type="text" id="nomeUsuario" required> <label for="emailUsuario">E-mail:</label> <input type="email" id="emailUsuario" required> <label for="senhaUsuario">Senha:</label> <input type="password" id="senhaUsuario" required> <button type="button" onclick="cadastrarUsuario()">Cadastrar</button> </form> </div> <!-- Lista de usuários --> <div> <h2>Lista de Usuários</h2> <table> <thead> <tr> <th>Nome</th> <th>E-mail</th> <!-- Adicione outras colunas conforme necessário --> </tr> </thead> <tbody id="usuariosList"></tbody> </table> </div> <script> // Função para cadastrar um usuário function cadastrarUsuario() { const usuarioForm = document.getElementById('usuarioForm'); const nomeUsuario = document.getElementById('nomeUsuario').value; const emailUsuario = document.getElementById('emailUsuario').value; const senhaUsuario = document.getElementById('senhaUsuario').value; // Monta os dados do usuário para enviar no corpo da requisição const usuarioData = { nome: nomeUsuario, email: emailUsuario, senha: senhaUsuario }; // Envia a requisição para o endpoint de Usuários (http://localhost:8080/usuarios) fetch('http://localhost:8080/usuarios', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(usuarioData), }) .then(response => response.json()) .then(data => { console.log('Usuário cadastrado com sucesso:', data); // Atualiza a lista de usuários após o cadastro atualizarListaUsuarios(); }) .catch(error => { console.error('Erro ao cadastrar usuário:', error); // Lógica para lidar com erros, exibir mensagem, etc. }); } // Função para obter e exibir a lista de usuários function atualizarListaUsuarios() { // Envia uma requisição para o endpoint de Usuários (http://localhost:8080/usuarios) para obter a lista de usuários fetch('http://localhost:8080/usuarios') .then(response => response.json()) .then(data => { // Atualiza a tabela com os dados obtidos const usuariosList = document.getElementById('usuariosList'); usuariosList.innerHTML = ''; // Limpa a lista antes de atualizar // Adiciona as linhas com os dados dos usuários data.forEach(usuario => { const newRow = usuariosList.insertRow(); const cell1 = newRow.insertCell(0); const cell2 = newRow.insertCell(1); cell1.innerHTML = usuario.nome; cell2.innerHTML = usuario.email; // Adicione outras colunas conforme necessário }); }) .catch(error => { console.error('Erro ao obter lista de usuários:', error); // Lógica para lidar com erros, exibir mensagem, etc. }); } // Chama a função para inicializar a lista de usuários atualizarListaUsuarios(); </script> </body> </html>
import Box from "@mui/material/Box"; import Alert from "@mui/material/Alert"; import IconButton from "@mui/material/IconButton"; import Collapse from "@mui/material/Collapse"; import CloseIcon from "@mui/icons-material/Close"; import WordContext from "../context/word"; import { useContext } from "react"; export default function TransitionAlerts() { const { alertOpen } = useContext(WordContext); const { setAlertOpen } = useContext(WordContext); const { alertValue } = useContext(WordContext); return ( <Box sx={{ width: "50%" }}> <Collapse in={alertOpen}> <Alert severity="error" action={ <IconButton aria-label="close" color="inherit" size="small" onClick={() => { setAlertOpen(false); }}> <CloseIcon fontSize="inherit" /> </IconButton> }> <strong>BEEP! </strong> {alertValue} </Alert> </Collapse> </Box> ); }
import { Fragment, useRef, useState } from 'react'; import Lottie from 'react-lottie-player'; import highestNoteExplosionAnimation from './../../assets/highest-note-explosion.json'; import highestNoteAnimation from './../../assets/highest-note.json'; import userHintAnimation from './../../assets/user-hint.json'; import * as S from './styles'; export default function Notes() { const yayAudioRef = useRef<HTMLAudioElement>(null); const [showAnimation, setShowAnimation] = useState(false); const handleNote = (selectedNote: string) => { const highestNote = String(5); if (selectedNote === highestNote) { setShowAnimation(true); yayAudioRef.current?.play(); } else { setShowAnimation(false); } }; return ( <S.Wrapper> <audio ref={yayAudioRef}> <source src="/sounds/yay.mp3" type="audio/mpeg" /> <p>Your browser does not support the audio element.</p> </audio> <S.Notes> <p>What rating would you give to this page?</p> <S.RadioGroupRoot aria-label="View density" onValueChange={handleNote}> {[...Array(5)].map((item, i) => ( <Fragment key={i}> <S.RadioGroupItem key={item} value={String(i + 1)} id={String(i + 1)} > <S.Label htmlFor={String(i + 1)}>{i + 1}</S.Label> {i === 4 && showAnimation && ( <S.HighestNote> <div className="overflow"> <Lottie animationData={highestNoteAnimation} className="unicorn animation" loop play /> </div> <Lottie animationData={highestNoteExplosionAnimation} className="explosion animation" loop={false} play /> </S.HighestNote> )} </S.RadioGroupItem> </Fragment> ))} </S.RadioGroupRoot> <S.NoteHint> <div className="user-hint"> <Lottie animationData={userHintAnimation} className="user-hint-animation" loop play /> </div> <div className="text"> <strong>Just a hint</strong> <p>I would recommend you to choose the highest note 😏</p> </div> </S.NoteHint> </S.Notes> </S.Wrapper> ); }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="jquery-1.11.3.js"></script> <style> #d1{ color:red; } .c1{ background:green; } .c2{ text-align:center; } </style> <script> window.onload = function (){ //1.操作 id class 属性对于选择器选择样式 $("h1:first").attr("id","d1").attr("class","c1 c2"); //2.直接操作class属性 //增加类名 $("div").addClass("c1 c2"); //删除类名 $("div").removeClass("c1"); //toggleClass()借组用户行为来切换类名,没有添加,有则删除 btn.onclick = function (){ $("div").toggleClass("c1"); } //3.直接操作行内模式.CSS $("div").css("width","200px"); //通过传入js对象来操作行内模式 $("div").css({ "width":"500px", "height":"300px", "background":"purple", "font-size":"34px", "margin":"0 auto", "line-height":"300px"}) } </script> </head> <body> <h1>古人云:风起 云走 雨欲来</h1> <h1>今人说:风起 云走 雨雨来</h1> <div>风雨欲来</div> <button id="btn">切换</button> </body> </html>
# -*- coding: utf-8 -*- # Copyright 2020-TODAY Miguel Pardo <ing.miguel.pardo@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models import datetime def get_months(): months_choices = [] for i in range(1, 13): months_choices.append((i, datetime.date(2019, i, 1).strftime('%B'))) return months_choices class TypeSettlement(models.Model): _name = 'type.settlement' _description = 'Type Settlement' name = fields.Char(string="Name") active = fields.Boolean('Active', default=True) start_day = fields.Integer(string="Start Day") end_day = fields.Integer(string="End Day") start_month = fields.Selection([('1', 'January'), ('2', 'February'), ('3', 'March'), ('4', 'April'), ('5', 'May'), ('6', 'June'), ('7', 'July'), ('8', 'August'), ('9', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December')], string="Start Month", required=False) pay_type = fields.Selection(string="Type", selection=[('annual', 'Annual'), ('biannual', 'Biannual')], required=False) end_month = fields.Selection([('1', 'January'), ('2', 'February'), ('3', 'March'), ('4', 'April'), ('5', 'May'), ('6', 'June'), ('7', 'July'), ('8', 'August'), ('9', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December')], string="End Month", required=False) days_assign = fields.Integer(string="Days", required=False) assign_month_ids = fields.One2many(comodel_name="assign.month", inverse_name="type_settlement_id", string="Assign Month", required=False)
package com.capstone.realmen.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.security.SecurityScheme.Type; @Configuration public class SwaggerConfig { @Bean public SecurityScheme createAPIKeyScheme() { SecurityScheme scheme = new SecurityScheme(); scheme.type(Type.HTTP).bearerFormat("JWT").scheme("bearer"); return scheme; } @Bean public OpenAPI openAPI() { OpenAPI openAPI = new OpenAPI(); SecurityRequirement securityRequirement = new SecurityRequirement(); Components components = new Components(); Info info = new Info(); securityRequirement.addList("Bearer Authentication"); components.addSecuritySchemes("Bearer Authentication", this.createAPIKeyScheme()); info.title("Real Man API").description("Barber shop management API").version("1.0"); openAPI.addSecurityItem(securityRequirement).components(components).info(info); return openAPI; } // @Bean // public GroupedOpenApi webApi() { // return GroupedOpenApi.builder() // .group("Web") // .pathsToExclude("*/web/**") // .pathsToMatch("*/web/**") // .build(); // } // @Bean // public GroupedOpenApi mobileApi() { // return GroupedOpenApi.builder() // .group("Mobile") // .pathsToExclude("/mobile/**") // .pathsToMatch("/mobile/**") // .build(); // } }
import { DataTypes, Model } from 'sequelize'; import db from '.'; import TeamModel from './Team'; export interface MatchAttributes { id: number, homeTeamId: number, homeTeamGoals: number, awayTeamId: number, awayTeamGoals: number, inProgress: boolean, homeTeam?: { teamName: string }, awayTeam?: { teamName: string }, } export type MatchCreationalAttributes = Omit<MatchAttributes, 'id'>; class MatchModel extends Model<MatchAttributes, MatchCreationalAttributes> implements MatchAttributes { declare id: number; declare homeTeamId: number; declare homeTeamGoals: number; declare awayTeamId: number; declare awayTeamGoals: number; declare inProgress: boolean; } MatchModel.init({ id: { allowNull: false, autoIncrement: true, primaryKey: true, type: DataTypes.INTEGER, }, homeTeamId: { type: DataTypes.INTEGER, references: { model: 'teams', key: 'id', }, }, homeTeamGoals: { type: DataTypes.INTEGER, }, awayTeamId: { type: DataTypes.INTEGER, references: { model: 'teams', key: 'id', }, }, awayTeamGoals: { type: DataTypes.INTEGER, }, inProgress: { type: DataTypes.BOOLEAN, }, }, { underscored: true, sequelize: db, tableName: 'matches', timestamps: false, }); MatchModel.belongsTo(TeamModel, { foreignKey: 'homeTeamId', as: 'homeTeam' }); MatchModel.belongsTo(TeamModel, { foreignKey: 'awayTeamId', as: 'awayTeam' }); TeamModel.hasMany(MatchModel, { foreignKey: 'homeTeamId', as: 'homeTeam' }); TeamModel.hasMany(MatchModel, { foreignKey: 'awayTeamId', as: 'awayTeam' }); export default MatchModel;
import './ProductPage.css' import ProductBox from '../components/ProductBox' import { useContext, useEffect, useRef } from 'react' import { CartContext } from '../context/cartContext' import {useState} from 'react' import Success from '../components/Success' import { ProductContext } from '../context/productContext' import { DesignContext } from '../context/designContext' import { useParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom' import Quantity from '../components/Quantity' import axios from 'axios' import MobileSelection from './MobileSelection' import { useNavigate } from 'react-router-dom' function ProductPage({url}){ const Products=useContext(ProductContext) const Designs=useContext(DesignContext) const Cart=useContext(CartContext) const [added,setAdded]=useState(false) const {id}=useParams() const [product,setProduct]=useState() const [design,setDesign]=useState() const [price,setPrice]=useState({sellingPrice:'',mrp:''}) const [searchParams,setSearchParams]=useSearchParams() const parentMaterial=useRef() const colorBtn=useRef() const [quantity,setQuantity]=useState(1) const [material,setMaterial]=useState('Hard Case') const [cartCopy,setCartCopy]=useState(false) let loadSimilarProducts const [priceContainer,setPriceContainer]=useState() const [showWarning,setShowWarning]=useState(false) const [size,setSize]=useState() const [mobile,setMobile]=useState({ brand:"", model:"" }) const [colorIndex,setColorIndex]=useState(0) const hardContainer=useRef() const navigate=useNavigate() const calculateClothPrice=async(product)=>{ const Price=await axios.get(`${url}api/prices`) const price=Price.data.data.doc[0].clothingPrice[0] if(product.clothType.id === 'CT01'){ setPrice(()=>{ return { sellingPrice:price?.tshirtPrice.sellingPrice, mrp:price.tshirtPrice.mrp } }) }else if(product.clothType.id==='CT02'){ setPrice(()=>{ return { sellingPrice:price?.oversizedPrice.sellingPrice, mrp:price.oversizedPrice.mrp } }) }else if(product.clothType.id==='CT03'){ setPrice(()=>{ return { sellingPrice:price?.hoodiePrice.sellingPrice, mrp:price.hoodiePrice.mrp } }) } } useEffect(()=>{ if(id.charAt(0) === 'C'){ const Product=axios.get(`${url}api/clothings/${id}`).then(res=>{ setProduct(()=>{ console.log("Clothings",res.data.data.doc) return {productCloth:true,...res.data.data.doc}}) setColorIndex(res.data.data.doc.colors.findIndex(ele=>ele===searchParams.get('color'))) calculateClothPrice(res.data.data.doc) }) }else{ const Product=axios.get(`${url}api/covers/${id}`).then(res=>{ console.log("Covers",res.data.data.doc) setProduct(res.data.data.doc) const Price=axios.get(`${url}api/prices`).then(res=>{ setPriceContainer(res.data.data.doc[0].casePrice[0]) setPrice(res.data.data.doc[0].casePrice[0].hardCasePrice) }) }) } // const brandId=searchParams.get("brand") // const modelId=decodeURI(searchParams.get("model")) // Products.Products.forEach((product)=>{ // if(product.id === brandId){ // product.model.forEach((element)=>{ // if(element.modelId === modelId){ // console.log("Success",element) // const productDetails={ // brand:{ // brandName:product.brand, // brandId:product.id, // seller:product.seller // }, // model:{ // modelName:element.modelName, // materialG:element.materialG, // image:element.image, // modelId:element.modelId // } // } // setProduct(productDetails) // setPrice(Products.Prices.hardCasePrice) // return // } // }) // } // // if(product.brand.toLowerCase()===brand.toLowerCase() && product.model.toLowerCase() === model.toLowerCase()){ // // console.log("product",product) // // setProduct(product) // // return // // } // }) // setDesign(()=>Designs.Designs.find((design)=>design.id === id)) },[]) const handleAddCart=()=>{ let cartId let cartProduct if(product.productCloth){ if(!size){ setShowWarning(true) return } const imageIndex=product.colors.findIndex(ele=>ele===searchParams.get('color')) cartProduct={ category:product.category.id, clothType:product.clothType.name, color:searchParams.get('color'), productId:product.id, image:product.image[imageIndex], productName:product.name, seller:product.seller, size:size, productCloth:true } cartId=product.category.id+product.id+size+cartProduct.color }else{ if(!mobile.model){ setShowWarning(true) return } cartProduct={ category:product.category.id, productId:product.id, image:product.image, productName:product.name, seller:product.seller, brand:mobile.brand, model:mobile.model, material:material, productCloth:false } cartId=product.category.id+product.id+cartProduct.model+cartProduct.material } for(let element in Cart.cart){ if(Cart.cart[element].id === cartId){ setCartCopy(true) setAdded(true) setTimeout(()=>{ setAdded(false) },2000) return } } Cart.addToCart(cartId,quantity,price,cartProduct) setAdded(true) setTimeout(()=>{ setAdded(false) },2000) } const handleMateral=(event)=>{ event.stopPropagation() if (event.currentTarget.classList.contains('active-material')) return const test=parentMaterial.current.childNodes test.forEach((ele)=>{ ele.classList.remove('active-material') }) event.currentTarget.classList.add('active-material') if (event.currentTarget.dataset.materialType === 'glass'){ setPrice(priceContainer.glassCasePrice) setMaterial('Glass Case') } else{ setPrice(priceContainer.hardCasePrice) setMaterial("Hard Case") } } loadSimilarProducts=()=>{ // const Content=[] // if(!product) return // for(let i=0;i<4;i++){ // Content.push(<ProductBox style='similar-width' name={Designs.Designs[i].name} designId={Designs.Designs[i].id} brand={product.brand} model={product.model} price={Products.Prices}/>) // } // return Content } const qtyChange=(qty)=>{ setQuantity(qty) } const handleColorSelect=(e)=>{ setSearchParams({color:e.target.title}) setColorIndex(product.colors.findIndex(ele=>ele===e.target.title)) } const handleSizeSelect=(e)=>{ if (showWarning) setShowWarning(false) document.querySelectorAll('.size-div').forEach(ele=>{ ele.classList.remove('size-active') }) e.target.classList.add('size-active') setSize(e.target.innerText) } const mobileDetails=(brand,model)=>{ setMobile({brand,model}) if (showWarning) setShowWarning(false) } useEffect(()=>{ if(!mobile.model.materialG){ setMaterial("Hard Case") setPrice(priceContainer?.hardCasePrice) hardContainer.current?.classList.add('active-material') } },[mobile,hardContainer]) const handleBuy=()=>{ if(product.category.id==="CAT02") navigate(`/checkout/${product.category.id}-${product.id}-${colorIndex}-${size}-${quantity}?cart=false`) else navigate(`/checkout/${product.category.id}-${product.id}?cart=false`) } return( <div className='product-page'> <div className='product-container0'> <div className='image-container0'> <img className='product-image0' src={`/images/Clothing/${product?.image[colorIndex]}`} alt=""/> </div> <div className='product-details0'> <h1 className='product-name0'>{product ? (searchParams.get("color") && searchParams.get("color")[0].toUpperCase()+ searchParams.get("color").slice(1) +" "+ product.name) || product.name : "Loading"}</h1> <div className='price-container0'> <div className='encloser'> <span className='mrp0'>₹{price ? price.mrp : ""}</span> </div> <div className='encloser'> <span className='selling-price0'>₹{price ? price.sellingPrice : ""}</span> </div> <div className='discount-container'><p className='discount'>{price && 100-Math.ceil((price.sellingPrice/price.mrp)*100)}% OFF</p></div> </div> {!product?.productCloth && <div className='cover-features-container'> <MobileSelection mobileDetails={mobileDetails} url={url}/> {showWarning && <h3 className='warning'>Please select your mobile device!</h3>} </div> } {mobile?.model && <div className='material-container-product-page' ref={parentMaterial}> <div className='material-box-product-page active-material' ref={hardContainer} data-material-type="hard" onClick={handleMateral}> <h2 className='material-product-page '> Hard Case </h2> </div> {mobile?.model?.materialG && <div className='material-box-product-page' data-material-type="glass" onClick={handleMateral}> <h2 className='material-product-page'> Glass Case </h2> </div> } </div>} {product?.productCloth && <div className='cloth-features-container'> <div className='color-container'> <h2 className='color-heading font-bold text-gray-600'>Available Colors</h2> <div className='color-sub-container'> {product?.colors.map((color)=>{ return <div className={`color-border ${searchParams.get("color") === color ? 'color-active' : ""}`} ref={colorBtn}><div onClick={handleColorSelect} className='color-fill ' title={color} style={{backgroundColor:color}} ></div></div> })} </div> </div> <div className='size-container'> <h2 className='color-heading font-bold text-gray-600'>Sizes</h2> <div className='size-sub-container'> {product?.clothType.size.map((size)=>{ return <div className='size-div' onClick={handleSizeSelect}>{size}</div> }) } </div> {showWarning && <h3 className='warning'>Please select your size!</h3>} </div> </div>} <ul className='features-list'> <li className='feature'><p className='feature-desc'>Free Cash On Delivery</p></li> <li className='feature'><p className='feature-desc'>Free Shipping</p></li> <li className='feature'><p className='feature-desc'>The product will get shipped within <span>48 Hours</span>.</p></li> </ul> <Quantity qty={quantity} qtyChange={qtyChange}/> <div className='main-btn-container'> <button className='add-cart-btn' onClick={handleAddCart}><span><i class="fa-solid fa-cart-shopping"></i></span> ADD TO CART</button> <button className='buy-btn' onClick={handleBuy}><i class="fa-solid fa-bag-shopping"></i> BUY NOW</button> </div> </div> </div> {/* <div className='product-description'> <p className='product-description'> <span className='desc'>Material: 100% Cotton</span> <span className='desc'>Fabric: 180GSM Biowash</span> <span className='desc'>100% Ring Spun Super Combed Cotton</span> <span className='desc'>Tolerance: + / - 0.5 inch</span> <span className='desc'>Single Jersey Knit</span> <span className='desc'>Only Heather Colors are 90% Cotton 10% Polyester</span> <span className='desc'>Bio Washed / Color Fastness Guaranteed</span> <span className='desc'>Digital Printing</span> </p> </div> */} <div className='similar-product-container'> <div className='heading-container'><h1 className='heading'>Similar Products</h1></div> <div className='similar-products'> <div className='s-product-container'> {loadSimilarProducts()} </div> </div> </div> <div className='review-container'> </div> {added && <Success message={cartCopy ? "Product is already present in your cart" : "Product is Added to your Cart!" }/>} </div> ) } export default ProductPage
# Background Runner Test App This is a sample Capacitor app designed to demonstrate the background task capabilities of the [Capacitor Background Runner](https://github.com/ionic-team/capacitor-background-runner) plugin. The app will fetch the following data every 15 minutes (or when available depending on OS): - Weather from the device's current location (using the OpenWeather API) - The latest news from Apple/Google developer news feeds To demonstrate the use of background updates, these updates are performed entirely in the background. ## Setup 1. Fork and clone this repo. 2. Install the dependencies. ```bash npm install ``` 3. In order to get weather data updates, you'll need a free API key for the [OpenWeatherMap Weather API](https://openweathermap.org/api). Copy the example `.env.example` file to a new file called `.env` and set `OPENWEATHERMAP_API_KEY` equal to the value of your key. 4. Build the app ```bash npm run build npx cap sync ``` #### iOS Keep in mind that iOS will ultamately decide when and how often your background task will run. Read [here](https://capacitorjs.com/docs/apis/background-runner#ios-1) for more information. #### Android Unfortunately, various Android device manufacturers have employed various aggressive battery optimization software that may interfere with or outright break the functionality of background tasks on Android. This app has been tested thoroughly with these optimizations turned **OFF** on the following devices: - Samsung (A41, S9, S21) - [More info & How to disable](https://dontkillmyapp.com/samsung) - Xiaomi (Mi A2 Lite) - [More info & How to disable](https://dontkillmyapp.com/xiaomi) - Huawei (P20 Lite) - [More info & How to disable](https://dontkillmyapp.com/huawei)
# Deployment and orchestration ## Overview Containerization provides an opportunity to move and scale applications to clouds and data centers. Containers effectively guarantee that those applications run the same way anywhere, allowing us to quickly and easily take advantage of all these environments. Additionally, as we scale our applications up, we need some tooling to help - automate the maintenance of those applications, - enable the replacement of failed containers automatically, - and manage the roll-out of updates and reconfigurations of those containers during their lifecycle. What is `orchestrators`? Tools to `manage`, `scale`, and `maintain` containerized applications are called `orchestrators`. **Two of the most popular orchestration tools are** 1. Kubernetes 2. Docker Swarm. **Turn on Kubernetes** Docker Desktop sets up Kubernetes for you quickly and easily. **Enable Docker Swarm** Docker Desktop runs primarily on Docker Engine, which has everything you need to run a Swarm built in Open a terminal, and initialize Docker Swarm mode: ## Deploy to Kubernetes Now that we've demonstrated that the individual components of our application run as stand-alone containers, it's time to arrange for them to be managed by an orchestrator like Kubernetes. Kubernetes provides many tools for - scaling - networking - securing - maintaining your containerized applications, above and beyond the abilities of containers themselves. In order to validate that our containerized application works well on Kubernetes, we'll use Docker Desktop's built in Kubernetes environment right on our development machine to deploy our application, before handing it off to run on a full Kubernetes cluster in production. The Kubernetes environment created by Docker Desktop is fully featured, meaning it has all the Kubernetes features your app will enjoy on a real cluster, accessible from the convenience of your development machine. **Describing apps using Kubernetes YAML** All containers in Kubernetes are scheduled as pods, which are groups of co-located containers that share some resources. Furthermore, in a realistic application we almost never create individual pods. Instead, most of our workloads are scheduled as deployments, which are scalable groups of pods maintained automatically by Kubernetes. Lastly, all Kubernetes objects can and should be described in manifests called Kubernetes YAML files. These YAML files describe all the components and configurations of your Kubernetes app, and can be used to easily create and destroy your app in any Kubernetes environment `bb.yaml` ``` # The apiVersion, which indicates the Kubernetes API that parses this object apiVersion: apps/v1 # The kind indicating what sort of object this is kind: Deployment # Some metadata applying things like names to your objects metadata: name: bb-demo namespace: default # The spec specifying all the parameters and configurations of your object. spec: replicas: 1 selector: matchLabels: bb: web template: metadata: labels: bb: web spec: containers: - name: bb-site image: getting-started imagePullPolicy: Never --- apiVersion: v1 kind: Service metadata: name: bb-entrypoint namespace: default spec: type: NodePort selector: bb: web ports: - port: 3000 targetPort: 3000 nodePort: 30001 ``` > `$ kubectl apply -f bb.yaml` > `$ kubectl get deployments` > `$ kubectl get services` > `$ kubectl delete -f bb.yaml` In addition to deploying to Kubernetes, we have also described our application as a Kubernetes YAML file. This simple text file contains everything we need to create our application in a running state. We can check it into version control and share it with our colleagues, allowing us to distribute our applications to other clusters (like the testing and production clusters that probably come after our development environments) easily. ## Deploy to Swarm > *** **Note**: Swarm mode is an advanced feature for managing a cluster of Docker daemons. Use Swarm mode if you intend to use Swarm as a production runtime environment. If you're not planning on deploying with Swarm, use Docker Compose instead. If you're developing for a Kubernetes deployment, consider using the integrated Kubernetes feature in Docker Desktop. ***Introduction*** Now that we've demonstrated that the individual components of our application run as stand-alone containers and shown how to deploy it using Kubernetes, let's look at how to arrange for them to be managed by Docker Swarm. Swarm provides many tools for scaling, networking, securing and maintaining your containerized applications, above and beyond the abilities of containers themselves. In order to validate that our containerized application works well on Swarm, we'll use Docker Desktop's built in Swarm environment right on our development machine to deploy our application, before handing it off to run on a full Swarm cluster in production. The Swarm environment created by Docker Desktop is fully featured, meaning it has all the Swarm features your app will enjoy on a real cluster, accessible from the convenience of your development machine. **Describe apps using stack files** Swarm never creates individual containers like we did in the previous step of this tutorial. Instead, - all Swarm workloads are scheduled as services, which are scalable groups of containers with added networking features maintained automatically by Swarm. - Furthermore, all Swarm objects can and should be described in manifests called stack files. - These YAML files describe all the components and configurations of your Swarm app, and can be used to easily create and destroy your app in any Swarm environment. `bb-stack.yaml` ``` version: '3.7' services: bb-app: image: getting-started ports: - "8080:8080" ``` > Kubernetes Services and Swarm Services are very different > Despite the similar name, the two orchestrators mean very different things by the term 'service'. In Swarm, a service provides both scheduling and networking facilities, creating containers and providing tools for routing traffic to them. In Kubernetes, scheduling and networking are handled separately, deployments (or other controllers) handle the scheduling of containers as pods, while services are responsible only for adding networking features to those pods. ## Cloud integrations 1. **Docker and ECS(Amazon Elastic Container Service )** --- ***Overview*** The Docker Compose CLI lets developers use native Docker commands to run applications in Amazon Elastic Container Service (ECS) when building cloud-native applications. The integration between Docker and Amazon ECS allows developers to use the Docker Compose CLI to - Set up an AWS context in one Docker command, allowing you to switch from a local context to a cloud context and run applications quickly and easily. - Simplify multi-container application development on Amazon ECS using Compose files
/* eslint-disable jsx-a11y/anchor-is-valid */ import React, { useState, useEffect } from "react"; import { Form, Input, InputNumber, Table, Typography, ConfigProvider, Empty, Button, } from "antd"; import { Reviews } from "../../types"; import { cliapbord, tokenService, getDate } from "../../utils"; import { ButtonCopy } from "../Button/ButtonCopy"; import { useLocalState } from "../context/hooks"; import { usePerson } from "../hooks/usePerson"; import { useUpdateReview } from "../hooks/useUpdateReview"; import { StatusSelect } from "../components/StatusSelect"; import { StatusComponent } from "../components/StatusComponent"; import { useDeleteReview } from "../hooks/useDeleteReview"; import { UploadCVS } from "../components/UploadCVS"; import { SaveOutlined, DeleteOutlined, CloseOutlined, EditOutlined, } from "@ant-design/icons"; import { ModalCreateReview } from "../components/Modal"; type Props = { reviews: ReviewsTableItem[] | undefined; isLoading: boolean; onUpdate: (project: string) => void; projectId: string; }; type ReviewsTableItem = Reviews & { key: string; }; interface EditableCellProps extends React.HTMLAttributes<HTMLElement> { editing: boolean; dataIndex: string; title: any; inputType: "number" | "text"; record: ReviewsTableItem; index: number; children: React.ReactNode; } const EditableCell: React.FC<EditableCellProps> = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { const inputNode = inputType === "number" ? <InputNumber /> : <Input />; return ( <td {...restProps}> {editing ? ( <Form.Item name={dataIndex} style={{ margin: 0 }}> {inputNode} </Form.Item> ) : ( children )} </td> ); }; export const TableProjectChangeable = ({ reviews, isLoading, projectId, onUpdate, }: Props) => { const [form] = Form.useForm(); const tgFormField = Form.useWatch("tg", form); const [editingKey, setEditingKey] = useState(""); const [dataSource, setDataSource] = useState(reviews); const state = useLocalState(); const { personInfo } = state; usePerson(); const { handleUpdateReview } = useUpdateReview(); const { handleDeleteReview } = useDeleteReview(); const isEditing = (record: ReviewsTableItem) => record.key === editingKey; const edit = (record: Partial<ReviewsTableItem> & { key: React.Key }) => { form.setFieldsValue({ ...record }); setEditingKey(record.key); }; const cancel = () => { setEditingKey(""); form.resetFields(); }; const save = async (key: React.Key) => { try { const row = (await form.validateFields()) as ReviewsTableItem; // @ts-ignore TODO:доделать! const newData = [...reviews]; const index = newData.findIndex((item) => key === item.key); row.id = newData[index].id; console.log("row_save", row, index, newData[index]); handleUpdateReview(row).then(() => { onUpdate(projectId); }); if (index > -1) { const item = newData[index]; newData.splice(index, 1, { ...item, ...row, }); setEditingKey(""); } else { newData.push(row); setEditingKey(""); } } catch (errInfo) { console.log("Validate Failed:", errInfo); } }; const onDelete = async (key: React.Key) => { try { const row = (await form.validateFields()) as ReviewsTableItem; // @ts-ignore TODO:доделать! const newData = [...reviews]; const index = newData.findIndex((item) => key === item.key); row.id = newData[index].id; console.log("row_save", row, index, newData[index]); handleDeleteReview({ id: row.id }).then(() => { onUpdate(projectId); }); if (index > -1) { const item = newData[index]; newData.splice(index, 1, { ...item, ...row, }); setEditingKey(""); } else { newData.push(row); setEditingKey(""); } } catch (errInfo) { console.log("Validate Failed:", errInfo); } }; const onSelectStatus = (value: string, key: React.Key) => { // @ts-ignore TODO:доделать! const newData = [...reviews]; const index = newData.findIndex((item) => key === item.key); if (index > -1) { const inWorkDate = Math.floor(new Date().valueOf() / 1000); form.setFieldsValue({ status: value }); if (value === "moderate") { form.setFieldsValue({ in_work: true }); form.setFieldsValue({ date: inWorkDate }); form.setFieldsValue({ host: personInfo?.first_name }); } } }; const role = tokenService.getRole(); const isAdmin = role === "ADMIN" || role === "SUPERVISOR"; const sendReviewToWork = (key: React.Key) => { // @ts-ignore TODO:доделать! const newData = [...reviews]; const index = newData.findIndex((item) => key === item.key); if (index > -1) { const inWorkDate = Math.floor(new Date().valueOf() / 1000); //togle form.setFieldsValue({ in_work: true }); form.setFieldsValue({ date: inWorkDate }); form.setFieldsValue({ host: personInfo?.first_name }); form.setFieldsValue({ status: "moderate" }); } }; const columns = [ { title: "№", dataIndex: "key", width: "6%", render: (record: string) => { return <div>{Number(record) + 1}</div>; }, }, { title: "Ссылка на отзыв", dataIndex: "link", width: "20%", editable: isAdmin, render: (text: string) => ( <div style={{ display: "inline" }}> <a onClick={() => window.open(text, "_blank")}>{text}</a> <ButtonCopy onClick={() => cliapbord(text)} style={{marginLeft:10}}/> </div> ), }, { title: "Текст отзыва", dataIndex: "text", width: "20%", editable: isAdmin, render: (text: string) => ( // eslint-disable-next-line jsx-a11y/anchor-is-valid <div> <span>{text}</span> <ButtonCopy onClick={() => cliapbord(text)} style={{marginLeft:10}}/> </div> ), }, { title: "Статус отзыва", dataIndex: "status", width: "15%", ellipsis: true, render: (status: string, record: ReviewsTableItem) => { const editable = isEditing(record); return ( <> {editable && isAdmin ? ( <StatusSelect defaultValue={status} onSelect={(e) => onSelectStatus(e, record.key)} /> ) : ( <StatusComponent status={status} /> )} </> ); }, }, { title: "Дата размещения", dataIndex: "date", width: "10%", render: (record: string | number) => { return ( <>{typeof record === "number" ? getDate({ date: record }) : record}</> ); }, }, { title: "Кто отдал отзыв", dataIndex: "host", width: "12%", }, { title: "Ник в телеграм", dataIndex: "tg", width: "12%", editable: true, }, { title: "", dataIndex: "operation", width: "15%", render: (_: any, record: ReviewsTableItem) => { const editable = isEditing(record); return editable ? ( <div style={{ display: "flex", flexDirection: "column" }}> <Typography.Link onClick={() => save(record.key)} disabled={role === "HOST" && !tgFormField} style={{ color: "green" }} > <SaveOutlined style={{ marginRight: 4 }} /> Save </Typography.Link> <Typography.Link onClick={cancel}> <CloseOutlined style={{ marginRight: 4 }} /> Cancel </Typography.Link> {isAdmin && ( <Typography.Link style={{ color: "red" }} onClick={() => onDelete(record.key)} > <DeleteOutlined style={{ marginRight: 4 }} /> Delete </Typography.Link> )} </div> ) : ( <Typography.Link disabled={ editingKey !== "" || (role === "HOST" && record.status !== "wait") } onClick={() => { edit(record); if (role === "HOST") { sendReviewToWork(record.key); } }} > <EditOutlined style={{ marginRight: 4 }} /> Edit </Typography.Link> ); }, }, ]; const mergedColumns = columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record: ReviewsTableItem) => ({ record, inputType: col.dataIndex === "text", dataIndex: col.dataIndex, title: col.title, editing: isEditing(record), }), }; }); useEffect(() => { setDataSource(reviews); }, [reviews]); const [isModalOpen, setIsModalOpen] = useState(false); const showModal = () => { setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); }; return ( <> <Form form={form} component={false}> <ConfigProvider renderEmpty={() => ( <Empty description="Отзывы в процессе написания, скоро они будут готовы" /> )} > {isAdmin && ( <div style={{ display: "flex", marginBottom: 16, width: 300, gridGap: "8px", }} > <Button onClick={showModal} type="primary" style={{background:'black'}}> Добавить запись </Button> <UploadCVS onUpdate={onUpdate} projectId={projectId} /> </div> )} {isModalOpen && ( <ModalCreateReview onClose={closeModal} projectId={projectId} onUpdate={onUpdate} /> )} <Table components={{ body: { cell: EditableCell, }, }} bordered dataSource={dataSource} columns={mergedColumns} pagination={false} loading={isLoading} tableLayout={"fixed"} scroll={{ x: 1000 }} /> </ConfigProvider> <Form.Item name={"in_work"} hidden> <Input /> </Form.Item> <Form.Item name={"status"} hidden> <Input /> </Form.Item> <Form.Item name={"date"} hidden> <Input /> </Form.Item> <Form.Item name={"host"} hidden> <Input /> </Form.Item> <Form.Item name={"tg"} hidden> <Input /> </Form.Item> </Form> </> ); };
from importlib.util import find_spec import os import sys required_packages = [ "mdtraj", "scipy", "sklearn", "matplotlib", "numpy", "p_tqdm", ] missing_packages = [] for package in required_packages: spec = find_spec(package) if spec is None: missing_packages.append(package) if len(missing_packages): print("These packages are required:") print(4 * " ", *missing_packages) print("Try installing with:") for i in missing_packages: print( f" python3 -m pip install {i}\n" f" conda install -c conda-forge {i}\n", flush=True, ) sys.exit() from datetime import datetime start_date = datetime.now() print(f"Started on {start_date.ctime()}") from inputs import * sys.path.append(path_to_src) from imports import * from tekmc import TEKMC from msd import mean_squared_displacement if ( ".pdb" in trajectory_file or ".h5" in trajectory_file or ".lh5" in trajectory_file ): topology_file = -1 if None in [ topology_file, trajectory_file, atom_name, timestep, spacings_list, n_walks, n_components, ]: print( "Required: Topology, trajectory as supported by \033[1mmdtraj\033[0m", " Atom name for the species of interest", " Time interval between trajectory frames", " List of spacings to perform TEKMC", " Number of walks during TEKMC for a given grid size", " Units: trajectory - nm", " timestep - ns", " grid_size - nm", "Also modify other parameters to your specific case. Look up https://github.com/Thanush1/TEKMC.git for details about all the methods.", sep="\n", flush=True, ) sys.exit() def get_parameters(line_no): file = open(os.path.join(path_to_src,'defaults.py'),'r') all_lines = file.readlines() value = all_lines[line_no - 1].split()[2] value = eval(value) return value # Creating TEKMC object. tekmc = TEKMC( topology_file, trajectory_file, atom_name, timestep, stride=stride, md_file=md_file, n_cpus=n_cpus, cmap=cmap, save_dir=save_dir, threshold=get_parameters(3), symmetrization_type=get_parameters(4), hopping_distance_analysis=hopping_distance_analysis, ) # Various methods of TEKMC object. # Modify the parameters as required. Look up https://github.com/Thanush1/TEKMC.git for more details. spacings_list = sorted(spacings_list, key = lambda x: x[0] if type(x) == list else x, reverse=True) for spacings in spacings_list: tekmc.TEKMC( spacings, n_walks, n_steps=n_steps, save_prob=get_parameters(12), create_prob=get_parameters(13), traj_steps=get_parameters(14), traj_n=get_parameters(15), traj_colors=get_parameters(16), save_random_walks=save_random_walks, ) tekmc.plot_histogram(spacings, n_bins=get_parameters(37)) tekmc.plot_trajectory( spacings, plot_steps=get_parameters(24), n_traj=get_parameters(25), _colors=get_parameters(26), unwrapped=get_parameters(27), trajectories=get_parameters(28), tekmc_file=get_parameters(29), ) tekmc.plot_pathways( spacings, n_components, _colors=get_parameters(45), Threshold=get_parameters(46), ) tekmc.plot_voxels_probability(spacings, color_map=get_parameters(54)) tekmc.compute_diffusion(spacings_list=get_parameters(62)) tekmc.plot_msd(spacings_list=get_parameters(70), _colors=get_parameters(71), y_scale = 'log', x_scale = 'log') tekmc.plot_diffusion(spacings_list=get_parameters(79), _colors=get_parameters(80), y_scale = 'log', x_scale = 'log') tekmc.normalized_MSE(spacings_list=get_parameters(97)) #tekmc.plot_displacement_probability(spacings_list=get_parameters(88), _colors=get_parameters(89)) end_date = datetime.now() print(f"Finished on {end_date.ctime()}") print(f"Total runtime {(end_date - start_date)}")
/********************************************************************************* Assignment - Lab 3 Multiple Table Queries By <give your name> Lab Section: ?? **********************************************************************************/ set pagesize 40 set linesize 120 /********************************************************************************* Question 1A, 1B, 1C Use the tables in your schema. For each country in Asia, display the country name and the region name. Sort the results by country name in ascendening sequence. Give the answer in the requested SQL verisons using the requested keywords. Write the query in SQL/86 and SQL/92. Note: Do NOT use the code for Asia in your search, look for the string 'Asia' **********************************************************************************/ -- 1A -- SQL/86 SELECT country_name, region_name FROM countries c , regions r WHERE r.region_name = 'Asia' ORDER BY c.country_name ASC; -- 1B -- SQL/92 using "ON" SELECT country_name, region_name FROM countries c INNER JOIN regions r ON(r.region_name = 'Asia') ORDER BY c.country_name ASC; -- 1C -- SQL/92 using "USING" SELECT country_name, region_name FROM countries c INNER JOIN regions r USING(region_id) WHERE r.region_name = 'Asia' ORDER BY c.country_name ASC; /********************************************************************************* Question 2A, 2B Use the tables in your schema. Write a query to display the last name, job title, department id, and department name for all employees who work in Southlake. Sort the results by last name in ascending sequence. **********************************************************************************/ -- 2A -- SQL/86 SELECT e.last_name, j.job_title, d.department_id, d.department_name, l.location_id FROM employees e, jobs j, departments d, locations l WHERE l.location_id = d.location_id AND d.department_id = e.department_id AND e.job_id = j.job_id AND l.city = 'Southlake' ORDER BY last_name ASC; -- 2B -- SQL/92 SELECT e.last_name, j.job_title, department_id, d.department_name, location_id FROM locations l INNER JOIN departments d USING(location_id) INNER JOIN employees e USING(department_id) INNER JOIN jobs j USING(job_id) WHERE l.city = 'Southlake' ORDER BY last_name ASC; /********************************************************************************* Question 3A, 3B Use the tables in your schema. Write a query that will list all of the employees (last names), whose last name starts with 'G', and the departments (give the name of the department) to which they belong. Include all employees who have not yet been assigned to any department. If an employee does not belong to a department, use the string "unassigned" for the department name. Sort the results by last name in ascending sequence. Use the terms "Last Name" and "Department" for the column headings. Write the query in SQL/86 and SQL/92. Note: do not use IS NULL or IS NOT NULL in your query. **********************************************************************************/ -- 3A -- SQL/86 SELECT e.last_name, d.department_name FROM employees, department WHERE e.last_name LIKE 'D%' ORDER BY e.last_name ASC; -- 3B -- SQL/92 /********************************************************************************* Question 4A, 4B Use the tables in your schema. Display the employee last name and employee id along with their manager's last name and manager number (in other words the manager's employee id) for all employees whose last name begins with 'T'. Label the columns Employee, Emp#, Manager, and Mgr#, respectively (note the use of upper and lower case). Sort the results by employee last name in descending sequence. Write the query in SQL/86 and SQL/92. **********************************************************************************/ -- 4A -- SQL/86 -- 4B -- SQL/92 /********************************************************************************* Question 5A, 5B Use the tables in your schema. Display the region, the employee first and last name (separated by a space) in a column titled "Employee Name", and the employee's salary. Only include employees with a salary between 9000 and 10000 (inclusive). Sort the report by ascending region name, and then by descending salary. Make it so region names are not repeated (ie: suppress duplicate values - if the region name of a row matches the region name of the row above it - don't show the region name). Hint: you will need to us "BREAK ON". After a grouping of employees within a region, add in a blank line by using "SKIP 1" at the end of the break on clause. Be sure to clear breaks after your query so it does not affect other queries. Write the query in SQL/86 and SQL/92. Note: Remember to join all the tables that are required to connect the employee table to the region table. **********************************************************************************/ -- 5A -- SQL/86 -- 5B -- SQL/92 /********************************************************************************* Question 6 Use the tables in your schema. Create a report showing: First name, last name, and salary of all of the employees who make over $11,000. Use a column command to format the salary to have a heading of "Emp Salary", and left justify it. Put the salaries into a currency format: $9,999,999.99 Sort the report by salary in descending sequence. Turn the TTITLE and BTITLE off after the query and clear the salary column so that it doesn't affect other queries. Create the following header for the report: left-justified: 'Run date: ' use _DATE command centered: Show the user who ran the query as 'Run by: ' SQL.USER right-justified: Put Page number on the right as 'Page: ' SQL.PNO Create the following footer for the report: centered: 'End of Report' **********************************************************************************/ /********************************************************************************* Question 7A, 7B Use the tables in your schema. List the the employees (last name, job name, department name, salary) who make more than X dollars. Make it so that the user running the script is prompted to enter the X amount for salary. Sort the results by salary in descending sequence. Test it with a salary of 4000. Write the query in SQL/86 and SQL/92. **********************************************************************************/ -- 7A -- SQL/86 -- 7B -- SQL/92
<script lang="ts" setup> import { ErrorMessage, Field, Form } from 'vee-validate' import {registrationSchema} from '~/schema/authSchema' import {useAuthStore} from '~/store/authStore' const {handleRegistration} = useAuthStore() </script> <template> <Form method="post" :validation-schema="registrationSchema" @submit="handleRegistration"> <div class="mb-4"> <label for="first_name" class="block text-gray-700 text-sm font-bold mb-2">First Name</label> <Field type="text" id="first_name" name="first_name" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="first_name" class="text-xs text-red-500" /> </div> <div class="mb-4"> <label for="last_name" class="block text-gray-700 text-sm font-bold mb-2">Last Name</label> <Field type="text" id="last_name" name="last_name" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="last_name" class="text-xs text-red-500" /> </div> <div class="mb-4"> <label for="user_name" class="block text-gray-700 text-sm font-bold mb-2">Username</label> <Field type="text" id="user_name" name="user_name" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="user_name" class="text-xs text-red-500" /> </div> <div class="mb-4"> <label for="email" class="block text-gray-700 text-sm font-bold mb-2">Email</label> <Field type="text" id="email" name="email" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="email" class="text-xs text-red-500" /> </div> <!-- Password Input --> <div class="mb-4"> <label for="password" class="block text-gray-700 text-sm font-bold mb-2">Password</label> <Field type="password" id="password" name="password" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="password" class="text-xs text-red-500" /> </div> <div class="mb-4"> <label for="password_confirmation" class="block text-gray-700 text-sm font-bold mb-2">Confirm Password</label> <Field type="password" id="password_confirmation" name="password_confirmation" class="w-full p-2 border border-gray-300 rounded" /> <ErrorMessage name="password" class="text-xs text-red-500" /> </div> <!-- SignUp Button --> <button type="submit" class="bg-secondary text-white font-bold py-2 px-10 rounded focus:outline-none focus:shadow-outline-blue active:bg-secondary-dark hover:bg-secondary-dark"> SignUp </button> </form> </template> <style scoped></style>
package tz.or.mkapafoundation.hrmis.service.dto; import java.io.Serializable; import java.util.Objects; import io.github.jhipster.service.Criteria; import io.github.jhipster.service.filter.BooleanFilter; import io.github.jhipster.service.filter.DoubleFilter; import io.github.jhipster.service.filter.Filter; import io.github.jhipster.service.filter.FloatFilter; import io.github.jhipster.service.filter.IntegerFilter; import io.github.jhipster.service.filter.LongFilter; import io.github.jhipster.service.filter.StringFilter; import io.github.jhipster.service.filter.LocalDateFilter; /** * Criteria class for the {@link tz.or.mkapafoundation.hrmis.domain.Project} entity. This class is used * in {@link tz.or.mkapafoundation.hrmis.web.rest.ProjectResource} to receive all the possible filtering options from * the Http GET request parameters. * For example the following could be a valid request: * {@code /projects?id.greaterThan=5&attr1.contains=something&attr2.specified=false} * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use * fix type specific filters. */ public class ProjectCriteria implements Serializable, Criteria { private static final long serialVersionUID = 1L; private LongFilter id; private StringFilter code; private StringFilter name; private LocalDateFilter startDate; private LocalDateFilter endDate; public ProjectCriteria() { } public ProjectCriteria(ProjectCriteria other) { this.id = other.id == null ? null : other.id.copy(); this.code = other.code == null ? null : other.code.copy(); this.name = other.name == null ? null : other.name.copy(); this.startDate = other.startDate == null ? null : other.startDate.copy(); this.endDate = other.endDate == null ? null : other.endDate.copy(); } @Override public ProjectCriteria copy() { return new ProjectCriteria(this); } public LongFilter getId() { return id; } public void setId(LongFilter id) { this.id = id; } public StringFilter getCode() { return code; } public void setCode(StringFilter code) { this.code = code; } public StringFilter getName() { return name; } public void setName(StringFilter name) { this.name = name; } public LocalDateFilter getStartDate() { return startDate; } public void setStartDate(LocalDateFilter startDate) { this.startDate = startDate; } public LocalDateFilter getEndDate() { return endDate; } public void setEndDate(LocalDateFilter endDate) { this.endDate = endDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ProjectCriteria that = (ProjectCriteria) o; return Objects.equals(id, that.id) && Objects.equals(code, that.code) && Objects.equals(name, that.name) && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate); } @Override public int hashCode() { return Objects.hash( id, code, name, startDate, endDate ); } // prettier-ignore @Override public String toString() { return "ProjectCriteria{" + (id != null ? "id=" + id + ", " : "") + (code != null ? "code=" + code + ", " : "") + (name != null ? "name=" + name + ", " : "") + (startDate != null ? "startDate=" + startDate + ", " : "") + (endDate != null ? "endDate=" + endDate + ", " : "") + "}"; } }
export default { namespaced: true, state: { accessToken: localStorage.getItem('access_token'), authUser: JSON.parse(localStorage.getItem('auth_user')) }, getters: { accessTokenGetter(state) { return state.accessToken }, authUserGetter(state) { return state.authUser } }, mutations: { accessTokenSetter(state, data) { state.accessToken = data }, authUserSetter(state, data) { state.authUser = data } }, actions: { login(context, data) { return new Promise((resolve, reject) => { axios.post('/login', data).then(res => { if(res && res.data && res.data.success) { localStorage.setItem('access_token', res.data.token) localStorage.setItem('auth_user', JSON.stringify(res.data.authUser)) axios.defaults.headers.common['Authorization'] = `Bearer ${res.data.token}`; context.commit('accessTokenSetter', res.data.token) context.commit('authUserSetter', res.data.authUser) } resolve(res) }).catch(err => { console.log(err) if(err && err.data) { context.dispatch('alert/alertResponse', { 'type': err.data.type, 'status': err.status, 'message': err.data.message }, { root:true }) } reject(err) }) }) }, getAuthUser(context, data) { return new Promise((resolve, reject) => { axios.get('/check-auth').then((res) => { resolve(res) }).catch((err) => { if(err && err.data) { context.dispatch('alert/alertResponse', { 'type': err.data.type, 'status': err.status, 'message': err.data.message }, { root:true }) } reject(err) }) }) }, saveUserChanges(context, data) { return new Promise((resolve, reject) => { axios.put(`/change-current-user-data/${data.id}`, data).then(res => { resolve(res) }).catch(err => { if(err && err.data) { context.dispatch('alert/alertResponse', { 'type': err.data.type, 'status': err.status, 'message': err.data.message }, { root:true }) } reject(err) }) }) }, createNewUser(context, data) { return new Promise((resolve, reject) => { axios.post(`/create-user`, data).then(res => { resolve(res) }).catch(err => { if(err && err.data) { context.dispatch('alert/alertResponse', { 'type': err.data.type, 'status': err.status, 'message': err.data.message }, { root:true }) } reject(err) }) }) }, logOut(context, data) { return new Promise((resolve, reject) => { axios.post('/logout').then((res) => { if(res.data.success) { context.commit('accessTokenSetter', '') context.commit('authUserSetter', '') localStorage.removeItem('access_token'); localStorage.removeItem('auth_user') } resolve(res) }).catch((error) => { if(err && err.data) { context.dispatch('alert/alertResponse', { 'type': err.data.type, 'status': err.status, 'message': err.data.message }, { root:true }) } reject(error) }) }) } } }
// // JeVois Smart Embedded Machine Vision Toolkit - Copyright (C) 2016 by Laurent Itti, the University of Southern // California (USC), and iLab at USC. See http://iLab.usc.edu and http://jevois.org for information about this project. // // This file is part of the JeVois Smart Embedded Machine Vision Toolkit. This program is free software; you can // redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software // Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Contact information: Laurent Itti - 3641 Watt Way, HNB-07A - Los Angeles, CA 90089-2520 - USA. // Tel: +1 213 740 3527 - itti@pollux.usc.edu - http://iLab.usc.edu - http://jevois.org /*! \file */ #pragma once #include <jevois/Component/Component.H> #include <jevois/Types/Enum.H> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> namespace superpixel { static jevois::ParameterCategory const ParamCateg("SuperPixel Options"); //! Enum for parameter \relates SuperPixel JEVOIS_DEFINE_ENUM_CLASS(Algo, (SLIC) (SLICO) (SEEDS) ); // could later also support LSC //! Parameter \relates SuperPixel JEVOIS_DECLARE_PARAMETER(algo, Algo, "Algorithm variant to use", Algo::SLICO, Algo_Values, ParamCateg); //! Parameter \relates SuperPixel JEVOIS_DECLARE_PARAMETER(regionsize, int, "SLIC Region size", 30, ParamCateg); //! Parameter \relates SuperPixel JEVOIS_DECLARE_PARAMETER(numpix, int, "Number of SEEDS superpixels", 200, ParamCateg); //! Parameter \relates SuperPixel JEVOIS_DECLARE_PARAMETER(iterations, int, "Number of iterations", 6, jevois::Range<int>(1, 100), ParamCateg); //! Enum for parameter \relates SuperPixel JEVOIS_DEFINE_ENUM_CLASS(OutType, (Labels) (Contours) ); //! Parameter \relates SuperPixel JEVOIS_DECLARE_PARAMETER(output, OutType, "Output labels or demo grayscale input image with superimposed contours", OutType::Contours, OutType_Values, ParamCateg); } // namespace superpixel //! Superpixel image segmentation from OpenCV /*! See tutorial at http://docs.opencv.org/3.2.0/df/d6c/group__ximgproc__superpixel.html and http://docs.opencv.org/3.0-beta/modules/ximgproc/doc/superpixels.html \ingroup components */ class SuperPixel : public jevois::Component, public jevois::Parameter<superpixel::algo, superpixel::regionsize, superpixel::numpix, superpixel::iterations, superpixel::output> { public: //! Default Component constructor ok using jevois::Component::Component; //! Virtual destructor for safe inheritance virtual ~SuperPixel() { } //! Process an RGB image and get some greyscale results /*! outimg should be allocated with same size as the input and CV_8UC1 pixels. */ void process(cv::Mat const & inimg, cv::Mat & outimg); };
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.usbbog.sd.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author user */ @Entity @Table(name = "cuenta_bancaria") @XmlRootElement @NamedQueries({ @NamedQuery(name = "CuentaBancaria.findAll", query = "SELECT c FROM CuentaBancaria c") , @NamedQuery(name = "CuentaBancaria.findByNum", query = "SELECT c FROM CuentaBancaria c WHERE c.num = :num") , @NamedQuery(name = "CuentaBancaria.findByClave", query = "SELECT c FROM CuentaBancaria c WHERE c.clave = :clave") , @NamedQuery(name = "CuentaBancaria.findBySaldo", query = "SELECT c FROM CuentaBancaria c WHERE c.saldo = :saldo")}) public class CuentaBancaria implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "num") private String num; @Basic(optional = false) @Column(name = "clave") private String clave; @Basic(optional = false) @Column(name = "saldo") private double saldo; @JoinColumn(name = "estado_cuenta", referencedColumnName = "nombre") @ManyToOne(optional = false) private EstadoCuenta estadoCuenta; @JoinColumn(name = "tipo_cuenta", referencedColumnName = "nombre") @ManyToOne(optional = false) private TipoCuenta tipoCuenta; @JoinColumn(name = "usuario", referencedColumnName = "num_doc") @OneToOne(optional = false) private User usuario; public CuentaBancaria() { } public CuentaBancaria(String num) { this.num = num; } public CuentaBancaria(String num, String clave, String fechaInicio, double saldo) { this.num = num; this.clave = clave; this.saldo = saldo; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public EstadoCuenta getEstadoCuenta() { return estadoCuenta; } public void setEstadoCuenta(EstadoCuenta estadoCuenta) { this.estadoCuenta = estadoCuenta; } public TipoCuenta getTipoCuenta() { return tipoCuenta; } public void setTipoCuenta(TipoCuenta tipoCuenta) { this.tipoCuenta = tipoCuenta; } public User getUsuario() { return usuario; } public void setUsuario(User usuario) { this.usuario = usuario; } @Override public int hashCode() { int hash = 0; hash += (num != null ? num.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CuentaBancaria)) { return false; } CuentaBancaria other = (CuentaBancaria) object; if ((this.num == null && other.num != null) || (this.num != null && !this.num.equals(other.num))) { return false; } return true; } @Override public String toString() { return "entidadesbanco.CuentaBancaria[ num=" + num + " ]"; } }
/* * Copyright Fraunhofer Institute for Software and Systems Engineering * * 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. * * Contributors: * sovity GmbH * */ package ids.messaging.requests; import java.io.IOException; import java.net.URI; import ids.messaging.common.DeserializeException; import ids.messaging.common.SerializeException; import ids.messaging.core.daps.ClaimsException; import ids.messaging.core.daps.DapsTokenManagerException; import ids.messaging.protocol.http.SendMessageException; import ids.messaging.protocol.http.ShaclValidatorException; import ids.messaging.protocol.multipart.UnknownResponseException; import ids.messaging.protocol.multipart.parser.MultipartParseException; import ids.messaging.requests.exceptions.RejectionException; import ids.messaging.requests.exceptions.UnexpectedPayloadException; import lombok.NonNull; /** * Interface for building selfdescription requests. */ public interface IDSInfrastructureService { /** * Interface Method to create a request for a self-description and send it. * * @param uri The target URI. * @return MessageContrainer with the response. * @throws IOException Every other exception. * @throws DapsTokenManagerException DAPS Token can not be acquired. * @throws MultipartParseException Response could not be parsed. * @throws ClaimsException Errors occurred while validating a DAT token. * @throws ShaclValidatorException Response did not pass SHACL Validation. * @throws SerializeException Serializing using the IDS-Serializer threw an IOException. * @throws UnknownResponseException Could indicate a new unknown IDS-Message-Type. * @throws SendMessageException Sending the IDS-Request returned an IOException. * @throws DeserializeException Deserializing the response threw an IOException. * @throws RejectionException Response was a RejectionMessage. * @throws UnexpectedPayloadException Payload did not match the expected format. */ MessageContainer<?> requestSelfDescription(@NonNull URI uri) throws IOException, DapsTokenManagerException, MultipartParseException, ClaimsException, ShaclValidatorException, SerializeException, UnknownResponseException, SendMessageException, DeserializeException, RejectionException, UnexpectedPayloadException; /** * Interface Method to create a request for a self-description and send it. * * @param uri The target URI. * @param requestedElement URI of the requested element. * @return MessageContrainer with the response. * @throws IOException Every other exception. * @throws DapsTokenManagerException DAPS Token can not be acquired. * @throws MultipartParseException Response could not be parsed. * @throws ClaimsException Errors occurred while validating a DAT token. * @throws ShaclValidatorException Response did not pass SHACL Validation. * @throws SerializeException Serializing using the IDS-Serializer threw an IOException. * @throws UnknownResponseException Could indicate a new unknown IDS-Message-Type. * @throws SendMessageException Sending the IDS-Request returned an IOException. * @throws DeserializeException Deserializing the response threw an IOException. * @throws RejectionException Response was a RejectionMessage. * @throws UnexpectedPayloadException Payload did not match the expected format. */ MessageContainer<?> requestSelfDescription(@NonNull URI uri, @NonNull URI requestedElement) throws IOException, DapsTokenManagerException, MultipartParseException, ClaimsException, ShaclValidatorException, SerializeException, UnknownResponseException, SendMessageException, DeserializeException, RejectionException, UnexpectedPayloadException; }
import {useCallback, useState, useEffect} from 'react'; import useSynergyFinance from './useSynergyFinance'; import {Bank} from '../synergy-finance'; import {PoolStats} from '../synergy-finance/types'; import config from '../config'; import useRefresh from './useRefresh'; const useStatsForPool = (bank: Bank) => { const synergyFinance = useSynergyFinance(); const {fastRefresh} = useRefresh() const [poolAPRs, setPoolAPRs] = useState<PoolStats>(); const fetchAPRsForPool = useCallback(async () => { setPoolAPRs(await synergyFinance.getPoolAPRs(bank)); }, [synergyFinance, bank]); useEffect(() => { fetchAPRsForPool().catch((err) => console.error(`Failed to fetch APR info: ${err.stack}`)); const refreshInterval = setInterval(fetchAPRsForPool, config.refreshInterval); return () => clearInterval(refreshInterval); }, [setPoolAPRs, synergyFinance, fetchAPRsForPool, fastRefresh]); return poolAPRs; }; export default useStatsForPool;
// // File.swift // // // Created by laijihua on 2023/7/20. // import Vapor import Fluent struct PostRepositoryImpl: PostRepository { var req: Request init(_ req: Request) { self.req = req } func add(param: InPost, ownerId: User.IDValue) async throws -> Post { let post = Post(title: param.title, ownerId: ownerId, content: param.content, desc: param.desc, categoryId: param.categoryId) let tags = try await Tag.query(on: req.db).filter(\.$id ~~ param.tagIds).all() try await req.db.transaction { db in try await post.create(on: db) try await post.$tags.attach(tags, on: db) } return post } func page(ownerId: User.IDValue?, inIndex: InSearchPost?) async throws -> FluentKit.Page<Post.Public> { let pageQuery = Post.query(on: req.db) .filter(\.$status == 1) if let inIndex = inIndex { if let cateId = inIndex.categoryId { pageQuery.filter(\.$category.$id == cateId) } if let tagId = inIndex.tagId { pageQuery.join(siblings: \.$tags).filter(Tag.self, \Tag.$id == tagId) } if let searchKey = inIndex.searchKey { pageQuery.filter(\.$title ~~ searchKey) } } return try await pageQuery .sort(\.$createdAt, .descending) .with(\.$tags) .with(\.$category) .with(\.$owner) .paginate(for: req) .map({ $0.asPublic() }) } func delete(ids: InDeleteIds, ownerId: User.IDValue) async throws { try await Post.query(on: req.db) .set(\.$status, to: 0) .group(.and) {group in group.filter(\.$id ~~ ids.ids).filter(\.$owner.$id == ownerId) } .update() } func update(param: InUpdatePost, ownerId: User.IDValue) async throws { try await req.db.transaction { db in try await Post.query(on: db) .set(\.$title, to: param.title) .set(\.$desc, to: param.desc) .set(\.$content, to: param.content) .set(\.$category.$id, to: param.categoryId) .filter(\.$id == param.id) .update() guard let ret = try await Post.query(on: db) .with(\.$tags) .filter(\.$id == param.id) .first() else { throw ApiError(code: .postNotExist) } try await ret.$tags.detachAll(on: db) let newTags = try await Tag.query(on: db).filter(\.$id ~~ param.tagIds).all() try await ret.$tags.attach(newTags, on: db) } } func get(id: Post.IDValue, ownerId: User.IDValue?) async throws -> Post.Public? { let post = try await Post.query(on: req.db) .filter(\.$id == id) .with(\.$owner) .with(\.$category) .with(\.$tags) .first() return post?.asPublic() } func newer(limit: Int) async throws -> [Post.Public] { let posts = try await Post.query(on: req.db) .filter(\.$status == 1) .sort(\.$createdAt, .descending) .limit(limit) .all() return posts.map({$0.asPublic()}) } }
package com.example.musicappui import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.navigation.compose.rememberNavController import com.example.musicappui.ui.theme.MusicAppUITheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { var show: MutableState<Boolean> = remember { mutableStateOf(false) } var navController = rememberNavController() MusicAppUITheme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> MainView(Modifier.padding(innerPadding), navController, show) AddAccount(show) } } } } }
import 'package:favorite_places/models/place_location.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class GoogleMapsScreen extends StatefulWidget { final PlaceLocation location; final bool isSelecting; const GoogleMapsScreen({ super.key, this.location = const PlaceLocation( latitude: 37.422, longitude: -122.084, address: 'Google Headquaters', ), this.isSelecting = true, }); @override State<StatefulWidget> createState() => _GoogleMapsScreenState(); } class _GoogleMapsScreenState extends State<GoogleMapsScreen> { late LatLng? _pickedLocation; @override void initState() { super.initState(); if (!widget.isSelecting) { _pickedLocation = LatLng( widget.location.latitude, widget.location.longitude, ); } else { _pickedLocation = null; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( widget.isSelecting ? 'Pick your location' : 'Your location', ), actions: [ if (widget.isSelecting) IconButton( icon: const Icon(Icons.save), onPressed: () { Navigator.of(context).pop(_pickedLocation); }, ), ], ), body: GoogleMap( initialCameraPosition: CameraPosition( target: LatLng( widget.location.latitude, widget.location.longitude, ), zoom: 18, ), onTap: (position) { if (widget.isSelecting) { setState(() { _pickedLocation = position; }); } }, markers: (widget.isSelecting && _pickedLocation == null) ? {} : { Marker( markerId: const MarkerId('m1'), position: _pickedLocation!, // change default marker color to green icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueGreen, ), ), }, ), ); } }
/*********************************************************************** * audioProcessing.cu * * Auteur: Hicheme BEN GAIED * * Ce fichier est une partie intégrante du plugin Rotator pour * VCV Rack, et il est spécifiquement dédié au traitement audio via CUDA. * Il contient les définitions des kernels CUDA et des fonctions associées * pour le traitement parallèle des signaux audio. * * Fonctionnalités Clés: * - Kernel CUDA 'processAudio' pour le traitement parallèle des signaux audio. * Chaque thread du GPU traite un élément du buffer audio, permettant un * traitement efficace et rapide. * - Mixage pondéré des signaux d'entrée en fonction des poids attribués, * permettant une manipulation flexible des différents signaux audio. * - La fonction 'runAudioProcessingKernel' gère la configuration et l'exécution * des kernels CUDA, y compris la gestion des erreurs. * * Ce fichier assurer une qualité sonore optimale lors * de la spatialisation et des rotations sonores. ***********************************************************************/ #include "audioProcessing.h" #include <cuda_runtime.h> #include <cstdio> //combine source sonor pour avoir une transition pour douce et pas de son qui se teleporte ->rq de pierre __global__ void processAudio(float *inputs[], float *outputBuffer, int bufferSize, float *weights, int numInputs) { int index = threadIdx.x + blockIdx.x * blockDim.x; // calcul l'index qui determine quel element du bufer le thread doit traiter if (index < bufferSize) { float outputSample = 0.0f; for (int i = 0; i < numInputs; ++i) { // somme des prduits des poids et des sons entree pour que chaque son egale en gros pour pas qu'un son soit plus influent qu'un autre outputSample += weights[i] * inputs[i][index]; } // a la fin on a un mixage ponderee outputBuffer[index] = outputSample; } } // parallelisation sur gpu pour melanger plusieurs signaux audio en fct du poids -> rapide efficace et evite perte de son lors des rota void runAudioProcessingKernel(float *inputs[], float *outputBuffer, int bufferSize, float *weights, int numInputs) { int blockSize = 256; int numBlocks = (bufferSize + blockSize - 1) / blockSize; //nombre de bloc a utilise il est calcule en fonction de la taille du buffer processAudio<<<numBlocks, blockSize>>>(inputs, outputBuffer, bufferSize, weights, numInputs); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("Erreur CUDA: %s\n", cudaGetErrorString(err)); } }
i---------------------------------------- iCLI Tricks: n - note taking iMarch 21st, 2018 i---------------------------------------- i iThis is the first in a series of phlog entries where I will share isome of my command line tricks, tips and scripts. i i i## n ## i iNote-taking in the terminal is a big deal for me. Whether I'm in ia meeting or someone stops by for a quick interruption, I need to ibe able to jot down notes quickly and get at them again easily. To ihandle this I have built a helper function called "n". i iNote: If you are familiar with my dotfiles [0] then you know iI keep all these scripts in a folder called ~/.functions and isource them as part of my .bash_profile. i i i### The Idea ### i iWhen I'm on the command line I enter the command "n" and it pops iup a list of all my notes using the FZF [1] fuzzy finder. These ihave a nice preview window to the side so I can quickly scan what iI'm looking for as I type in parts of the name. If I see what iI need in the preview I can either hit ESC to quit back to my ishell or ENTER to open up the note in my EDITOR. i iCreating a new note is easy: i i $ n monkeys i i > creates a new note in my NOTE_DIR called monkeys.md (I default i > all my notes to markdown) and opens it in EDITOR i iWant to categorize them? Add a folder path: i i $ n animals/monkeys i i > creates a new note at $NOTE_DIR/animals/monkeys.md and opens i > it in EDITOR i iYou can search foldernames as part of the fuzzy-finding. i iThe script also has bash-completion built-in. If you don't want to iuse FZF to browse for the file, just type part of the word and hit itab, like so: i i $ n mo<TAB> i i > n monkeys<ENTER> i i i### Requirements ### i iThis requires FZF [1], a fantastic utility for fuzzy-finding. I'm isure you could port it to another tool if you really wanted, ithough. i iThis also requires that you have an environment variable set icalled NOTE_DIR. For me that points to Dropbox where I have a inotes folder. This means all my notes are generated and stored ithere and are shared across systems. I can even get at them iwith my phone. i i i### The Source ### i i #!/usr/bin/env bash i i # Note taking function and command completion i _n() { i local lis cur i lis=$(find "${NOTE_DIR}" -name "*.md" | \ i sed -e "s|${NOTE_DIR}/||" | \ i sed -e 's/\.md$//') i cur=${COMP_WORDS[COMP_CWORD]} i COMPREPLY=( $(compgen -W "$lis" -- "$cur") ) i } i n() { i : "${NOTE_DIR:?'NOTE_DIR ENV Var not set'}" i if [ $# -eq 0 ]; then i local file i file=$(find "${NOTE_DIR}" -name "*.md" | \ i sed -e "s|${NOTE_DIR}/||" | \ i sed -e 's/\.md$//' | \ i fzf \ i --multi \ i --select-1 \ i --exit-0 \ i --preview="cat ${NOTE_DIR}/{}.md" \ i --preview-window=right:70%:wrap) i [[ -n $file ]] && \ i ${EDITOR:-vim} "${NOTE_DIR}/${file}.md" i else i case "$1" in i "-d") i rm "${NOTE_DIR}"/"$2".md i ;; i *) i ${EDITOR:-vim} "${NOTE_DIR}"/"$*".md i ;; i esac i fi i } i complete -F _n n i i i h[0] tomasino's dotfiles URL:http://github.com/jamestomasino/dotfiles h[1] FZF URL:http://github.com/junegunn/fzf
package main import "fmt" func main(){ type student struct { name string height float64 age int32 isGraduated bool hobbies []string } var data = student{ name: "wick", height: 182.5, age: 26, isGraduated: false, hobbies: []string{"eating", "sleeping"}, } fmt.Println("\nLayout Format %b\n") fmt.Printf("%b\n", data.age) // 11010 fmt.Println("\nLayout Format %c\n") fmt.Printf("%c\n", 1400) // ո fmt.Printf("%c\n", 1235) // ӓ fmt.Println("\nLayout Format %d\n") fmt.Printf("%d\n", data.age) // 26 fmt.Println("\nLayout Format %e atau %E\n") fmt.Printf("%e\n", data.height) // 1.825000e+02 fmt.Printf("%E\n", data.height) // 1.825000E+02 fmt.Println("\nLayout Format %f atau %F\n") fmt.Printf("%f\n", data.height) // 182.500000 fmt.Printf("%.9f\n", data.height) // 182.500000000 fmt.Printf("%.2f\n", data.height) // 182.50 fmt.Printf("%.f\n", data.height) // 182 fmt.Println("\nLayout Format %g atau %G\n") fmt.Printf("%e\n", 0.123123123123) // 1.231231e-01 fmt.Printf("%f\n", 0.123123123123) // 0.123123 fmt.Printf("%g\n", 0.123123123123) // 0.123123123123 fmt.Printf("%g\n", 0.12) // 0.12 fmt.Printf("%.5g\n", 0.12) // 0.12 fmt.Println("\nLayout Format %o\n") fmt.Printf("%o\n", data.age) // 32 fmt.Println("\nLayout Format %p\n") fmt.Printf("%p\n", &data.name) // 0x2081be0c0 fmt.Println("\nLayout Format %q\n") fmt.Printf("%q\n", `" name \ height "`) // "\" name \\ height \"" fmt.Println("\nLayout Format %s\n") fmt.Printf("%s\n", data.name) // wick fmt.Println("\nLayout Format %t\n") fmt.Printf("%t\n", data.isGraduated) // false fmt.Println("\nLayout Format %T\n") fmt.Printf("%T\n", data.name) // string fmt.Printf("%T\n", data.height) // float64 fmt.Printf("%T\n", data.age) // int32 fmt.Printf("%T\n", data.isGraduated) // bool fmt.Printf("%T\n", data.hobbies) // []string fmt.Println("\nLayout Format %v\n") fmt.Printf("%v\n", data) // {wick 182.5 26 false [eating sleeping]} fmt.Println("\nLayout Format %+v\n") fmt.Printf("%+v\n", data) // {name:wick height:182.5 age:26 isGraduated:false hobbies:[eating sleeping]} fmt.Println("\nLayout Format %#v\n") fmt.Printf("%#v\n", data) // main.student{name:"wick", height:182.5, age:26, isGraduated:false, hobbies:[]string{"eating", "sleeping"}} var data2 = struct { name string height float64 }{ name: "wick", height: 182.5, } fmt.Printf("%#v\n", data2) // struct { name string; height float64 }{name:"wick", height:182.5} fmt.Println("\nLayout Format %x atau %X\n") fmt.Printf("%x\n", data.age) // 1a var d = data.name fmt.Printf("%x%x%x%x\n", d[0], d[1], d[2], d[3]) // 7769636b fmt.Printf("%x\n", d) // 7769636b fmt.Println("\nLayout Format %%\n") fmt.Printf("%%\n") // % }
package com.qdi.rajapay.main_menu.prepaid_data; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSnapHelper; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.qdi.rajapay.BaseActivity; import com.qdi.rajapay.R; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @module 4.10 Prabayar Data * @screen 4.10.1 * @screen 4.10.5 */ public class PrepaidDataInputPhoneNoActivity extends BaseActivity { LinearLayout choose_packet_layout, operator_available_layout; EditText phone_no; RecyclerView list, listCategory; ImageView contact, operator; CoordinatorLayout layout; PrepaidDataInputPhoneNoAdapter adapter; PrepaidDataInputPhoneNoCategoryAdapter catAdapter; RecyclerView.LayoutManager layout_manager; ArrayList<JSONObject> provider_array = new ArrayList<>(); ArrayList<JSONObject> arrCat = new ArrayList<>(), selectedCat = new ArrayList<>(); JSONObject arrProd = new JSONObject(); JSONObject data_selected, selected_provider = new JSONObject(), data_list = new JSONObject(); String selected_tab = "regular"; Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { try { if(phone_no.getText().length() > 7) check_provider(); else{ operator_available_layout.setVisibility(View.VISIBLE); choose_packet_layout.setVisibility(View.GONE); /** * @author : Jesslyn * @note : set image to invisible instead of gone */ // <code> operator.setVisibility(View.INVISIBLE); // </code> } } catch (JSONException e) { e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu_prepaid_data_input_phone_no); init_toolbar(getResources().getString(R.string.home_mobile_data)); try { init(); } catch (JSONException e) { e.printStackTrace(); } // @CFI phone_no.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { onNext(); } @Override public void afterTextChanged(Editable s) { } }); contact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pick_contact(); } }); } private void init() throws JSONException { choose_packet_layout = findViewById(R.id.choose_packet_layout); operator_available_layout = findViewById(R.id.operator_available_layout); phone_no = findViewById(R.id.phone_no); layout = findViewById(R.id.layout); list = findViewById(R.id.list); final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); listCategory = findViewById(R.id.list_category); listCategory.setLayoutManager(layoutManager); final LinearSnapHelper snapHelper = new LinearSnapHelper(); snapHelper.attachToRecyclerView(listCategory); listCategory.setOnFlingListener(snapHelper); contact = findViewById(R.id.contact); operator = findViewById(R.id.operator); /** * @author Jesslyn * @note add shimmer lib */ // <code> shimmerInit(); // </code> /** * @author Jesslyn * @note init custom keyboard */ // <code> initNumpadKeyboard(phone_no, new NumpadKeyboardSubmit() { @Override public void onSubmit() { onNext(); } }); // </code> // @CFI get_provider_data(); manage_tab_list(); catAdapter = new PrepaidDataInputPhoneNoCategoryAdapter(arrCat, this); listCategory.setAdapter(catAdapter); catAdapter.setOnItemClickListener(new PrepaidDataInputPhoneNoCategoryAdapter.ClickListener() { @Override public void onClick(int position) { try{ if(position > 0 && catAdapter.getPaddingPixel() == 0){ int paddingDp = 150; float density = getResources().getDisplayMetrics().density; int paddingPixel = (int)(paddingDp * density); listCategory.setPaddingRelative(paddingPixel,0,paddingPixel,0); catAdapter.setPaddingPixel(paddingPixel); }else if(position == 0){ int paddingDp = 0; float density = getResources().getDisplayMetrics().density; int paddingPixel = (int)(paddingDp * density); listCategory.setPaddingRelative(paddingPixel,0,paddingPixel,0); catAdapter.setPaddingPixel(paddingPixel); } listCategory.smoothScrollToPosition(position); arrCat.get(catAdapter.curSelected).put("isSelected", false); arrCat.get(position).put("isSelected", true); selected_tab = arrCat.get(position).getString("text"); manage_tab_list(); }catch (JSONException e){ e.printStackTrace(); } catAdapter.notifyDataSetChanged(); } }); } /** * @author Jesslyn * @note set function onNext */ // <code> private void onNext(){ handler.removeCallbacks(runnable); handler.postDelayed(runnable,2000); } // </code> private void manage_tab_list(){ try { selectedCat = new ArrayList<>(); if(arrProd.has(selected_tab)) selectedCat = (ArrayList<JSONObject>) arrProd.get(selected_tab); adapter = new PrepaidDataInputPhoneNoAdapter(selectedCat,this); list.setAdapter(adapter); }catch(JSONException e){ e.printStackTrace(); } layout_manager = new GridLayoutManager(this,2); list.setLayoutManager(layout_manager); adapter.setOnItemClickListener(new PrepaidDataInputPhoneNoAdapter.ClickListener() { @Override public void onClick(int position) { try { data_selected = selectedCat.get(position); if(selected_tab.equalsIgnoreCase("NGRS")){ if(data_selected.getInt("isProblem") == 1) show_error_message(layout,getResources().getString(R.string.trouble_click_label)); else get_detail_ngrs(position); }else{ if(data_selected.getInt("isProblem") == 1) show_error_message(layout,getResources().getString(R.string.trouble_click_label)); else { PrepaidDataInputPhoneNoModal modal = new PrepaidDataInputPhoneNoModal(); modal.show(getSupportFragmentManager(), "modal"); } } } catch (JSONException e) { e.printStackTrace(); } } }); } private void check_provider() throws JSONException { selected_provider = new JSONObject(); String input = phone_no.getText().toString(); if(input.charAt(0) != '0') input = "0"+phone_no.getText().toString(); for(int x = 0; x < provider_array.size(); x++){ boolean flag = false; String[] prefix_array = provider_array.get(x).getString("prefixProduct").split(","); for(int y = 0; y < prefix_array.length; y++){ if(input.length() >= prefix_array[y].length() && check_phone_no(prefix_array[y], input.substring(0,input.length() < prefix_array[y].length() ? input.length() : prefix_array[y].length()) )) { selected_provider = provider_array.get(x); flag = true; break; } } if(flag) break; } if(!selected_provider.toString().equals("{}")) { if(selected_provider.getInt("isProblem") == 0) { choose_packet_layout.setVisibility(View.VISIBLE); operator_available_layout.setVisibility(View.GONE); operator.setVisibility(View.VISIBLE); Picasso.get() .load(selected_provider.getString("image")) .into(operator); get_package_data(); } else show_error_message(layout, getResources().getString(R.string.provider_trouble_click_label)); } else { operator_available_layout.setVisibility(View.VISIBLE); choose_packet_layout.setVisibility(View.GONE); /** * @author : Jesslyn * @note : set image to invisible instead of gone */ // <code> operator.setVisibility(View.INVISIBLE); // </code> } } private boolean check_phone_no(String prefix, String phone_no) { for(int x = 0; x < prefix.length(); x++){ if(prefix.charAt(x) != phone_no.charAt(x)) return false; } return true; } private void get_provider_data() { url = BASE_URL+"/mobile/prepaid-data/show-operator-prefix"; JSONObject param = getBaseAuth(); try{ param.put("productType", "DATA"); }catch(Exception e){ e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, param, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONObject response_data = response.getJSONObject("response"); if (!response_data.getString("type").equals("Failed")) { JSONArray jsonArray = response_data.getJSONArray("arrDataPrefix"); for(int x = 0; x < jsonArray.length(); x++) provider_array.add(jsonArray.getJSONObject(x)); String noHp = getIntent().getStringExtra("no_hp"); if(noHp != null) phone_no.setText(noHp); } else { show_error_message(layout,response_data.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { try { error_handling(error, layout); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }) { @Override public Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Accept", "application/json"); return headers; } }; consume_api(jsonObjectRequest); } private void get_package_data() throws JSONException { shimmerStart(); String phone = getPhoneNo(phone_no); url = BASE_URL+"/mobile/prepaid/data-pricelist"; JSONObject param = getBaseAuth(); try{ param.put("productType", "DATA"); param.put("noHp", phone); param.put("idProduct", selected_provider.getString("idProduct") ); }catch(Exception e){ e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, param, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONObject response_data = response.getJSONObject("response"); if (!response_data.getString("type").equals("Failed")) { arrCat.clear(); data_list = response_data; JSONObject resp = response_data.getJSONObject("arrDataPriceRslt"); Iterator<String> keys = resp.keys(); while(keys.hasNext()) { ArrayList<JSONObject> temp = new ArrayList<>(); String key = keys.next(); if (resp.getJSONArray(key) instanceof JSONArray) { JSONArray arr = resp.getJSONArray(key); for(int j = 0; j < arr.length(); j++){ JSONObject jsonObject = arr.getJSONObject(j); /** * @author : Jesslyn * @note : 1. change status information * 2. add name, change detail */ // <code> jsonObject.put("status",jsonObject.getInt("isProblem") == 0 ? "Tersedia" : "Gangguan"); jsonObject.put("name",jsonObject.getString("nameData")); jsonObject.put("detail",jsonObject.getString("detailData")); // <code> jsonObject.put("price",jsonObject.getDouble("vendorAmount")); /** * @author Jesslyn * @note req 14, change price_str using amount */ // <code> jsonObject.put("price_str","Rp. "+formatter.format(jsonObject.getDouble("amount"))); // add price display for displaying first price attempt (NGRS) jsonObject.put("price_display","Rp. "+formatter.format(jsonObject.getDouble("amount"))); // </code> // </code> jsonObject.put("image_url",response_data.getString("image")); jsonObject.put("productType",response_data.getString("productType")); jsonObject.put("productCategory",response_data.getString("productCategory")); jsonObject.put("idProduct",response_data.getString("idProduct")); temp.add(jsonObject); } // @note maintain tab list and selected tab (first attempt) JSONObject obj = new JSONObject(); obj.put("text", key); obj.put("isSelected", arrCat.size() == 0); // @note set selected data to first attempt if(arrCat.size() == 0) selected_tab = key; arrCat.add(obj); arrProd.put(key, temp); } } adapter.notifyDataSetChanged(); catAdapter.notifyDataSetChanged(); // @note : display data manage_tab_list(); // </code> } else { show_error_message(layout,response_data.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } finally { shimmerStop(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { try { error_handling(error, layout); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); }finally { shimmerStop(); } } }) { @Override public Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Accept", "application/json"); return headers; } }; consume_api(jsonObjectRequest); } private void get_detail_ngrs(final int index_ngrs) throws JSONException { /** * @author : Jesslyn * @note : 1. add vendorAmount to param request * 2. fixing phone number not updated (get phone number directly from phone_no edit text * 3. change request to post and use JSONObject */ // <code> String noHp = getPhoneNo(phone_no); url = BASE_URL+"/mobile/prepaid/data-ngrs-check"; JSONObject param = getBaseAuth(); try{ param.put("noHp", noHp); param.put("idProduct", data_list.getString("idProduct") ); param.put("cdeProduct", data_list.getString("cdeProduct") ); param.put("nameProduct", data_list.getString("nameProduct") ); param.put("productType", data_list.getString("productType") ); param.put("productCategory", data_list.getString("productCategory") ); param.put("idProductDetail", selectedCat.get(index_ngrs).getString("idProductDetail") ); param.put("codeData", selectedCat.get(index_ngrs).getString("codeData") ); param.put("nameData", selectedCat.get(index_ngrs).getString("nameData") ); param.put("typeData", selectedCat.get(index_ngrs).getString("typeData") ); param.put("codeCheckData", selectedCat.get(index_ngrs).getString("codeCheckData") ); param.put("vendorAmount", selectedCat.get(index_ngrs).getString("vendorAmount") ); param.put("amount", selectedCat.get(index_ngrs).getString("amount") ); }catch(Exception e){ e.printStackTrace(); } // </code> show_wait_modal(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, param, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { dismiss_wait_modal(); JSONObject response_data = response.getJSONObject("response"); if (!response_data.getString("type").equals("Failed")) { JSONObject jsonObject = selectedCat.get(index_ngrs); /** * @author : Jesslyn * @note : 1. Fixing issue price always 0 * 2. change to vendorAmount (to make standardization code) */ // <code> jsonObject.put("price",response_data.getDouble("vendorAmount")); jsonObject.put("price_str","Rp. "+formatter.format(response_data.getDouble("vendorAmount"))); // </code> /** * @author Dinda * @note Case CICD 10145 - replace amount and vendorAmount with data from NGRS check */ // <code> jsonObject.put("vendorAmount", response_data.getInt("vendorAmount")); jsonObject.put("amount", response_data.getInt("amount")); // </code> /** * @author : Jesslyn * @note : disable notify dataset change */ // <code> // adapter.notifyItemChanged(index_ngrs); // </code> data_selected = jsonObject; PrepaidDataInputPhoneNoModal modal = new PrepaidDataInputPhoneNoModal(); modal.show(getSupportFragmentManager(),"modal"); } else { show_error_message(layout,response_data.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { try { error_handling(error, layout); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }) { @Override public Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Accept", "application/json"); return headers; } }; consume_api(jsonObjectRequest); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK){ if(requestCode == CONTACT_INTENT){ Uri contactData = data.getData(); Cursor c = getContentResolver().query(contactData, null, null, null, null); if (c.getCount() > 0) { c.moveToFirst(); for(String column:c.getColumnNames()) { if(c.getString(c.getColumnIndex(column)) != null && column.equals("data4")) /** * @author Jesslyn * @note Fixing issue +62 */ // <code> phone_no.setText(parsePhoneNo(c.getString(c.getColumnIndex(column)))); // </code> } } } } } }
const express = require('express'); const urlMetadata = require('url-metadata'); const app = express(); const port = 3000; async function extractMetadata(url) { try { const metadata = await urlMetadata(url); console.log(metadata) const extractedData = { title: metadata.title, description: metadata.description, images: metadata.imgTags.map(imgTag => imgTag.src), // extract image URLs from imgTags sitename: extractSiteName(url), // helper function to extract sitename favicon: metadata.favicon, duration: null, // might not be available from url-metadata domain: extractDomain(url), // helper function to extract domain url, ogImageUrl: metadata['og:image'], ogTitle: metadata['og:title'], ogDescription: metadata['og:description'], }; return extractedData; } catch (error) { console.error(`Error fetching metadata for ${url}:`, error); return null; // handle errors gracefully } } function extractSiteName(url) { const hostname = new URL(url).hostname; return hostname.split('.')[0]; // basic site name extraction } function extractDomain(url) { return new URL(url).origin; } // Route to handle metadata extraction requests app.get('/metadata', async (req, res) => { const targetUrl = req.query.url; if (!targetUrl) { return res.status(400).json({ message: 'Missing required parameter: url' }); } const metadata = await extractMetadata(targetUrl); if (metadata) { res.json(metadata); } else { res.status(500).json({ message: 'Error fetching metadata' }); } }); app.listen(port, () => { console.log(`Server listening on port ${port}`); });
# coding: utf-8 from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.utils.timezone import now from .conf import FORM_MODEL, FORM_ENTRY_MODEL from .fields import NAMES from .utils import unique_slug # # # Basic abstract models. # # # class AbstractForm(models.Model): ''' The base model for constructing forms. ''' title = models.CharField(_('Title'), max_length=200) slug = models.SlugField(_('Slug'), max_length=300, unique=True) response = models.TextField(_('Response'), blank=True) emails_to = models.CharField(_('Address to'), blank=True, max_length=200) email_from = models.EmailField(_('From address'), blank=True) email_subject = models.CharField(_('Email subject'), max_length=200, blank=True) email_message = models.TextField(_('Message'), blank=True) class Meta: verbose_name = _('Form') verbose_name_plural = _('Forms') abstract = True def __unicode__(self): return self.title def save(self, *args, **kwargs): ''' Create a unique slug from title. ''' if not self.slug: slug = slugify(self) self.slug = unique_slug(self.__class__.objects, 'slug', slug) super(AbstractForm, self).save(*args, **kwargs) class AbstractField(models.Model): ''' The base model field. ''' label = models.CharField(_('Label'), max_length=200) slug = models.SlugField(_('Slug'), max_length=300, blank=True, default='') field_type = models.IntegerField(_('Type'), choices=NAMES) required = models.BooleanField(_('Required'), default=False) choices = models.CharField(_('Choices'), max_length=1000, blank=True) default = models.CharField(_('Default value'), blank=True, max_length=2000) placeholder_text = models.CharField(_('Placeholder text'), null=True, blank=True, max_length=200) help_text = models.CharField(_('Help text'), blank=True, max_length=200) form = models.ForeignKey(FORM_MODEL, related_name='fields') order = models.IntegerField(_('Order'), null=True, blank=True) class Meta: verbose_name = _('Field') verbose_name_plural = _('Fields') ordering = ('order',) abstract = True def __unicode__(self): return self.label def get_choices(self): for choice in self.choices.split(','): choice = choice.strip() yield choice, choice def save(self, *args, **kwargs): ''' Create a unique slug from label and setting order. ''' if not self.slug: slug = slugify(self).replace('-', '_') self.slug = unique_slug(self.form.fields, 'slug', slug) if self.order is None: self.order = self.form.fields.count() return super(AbstractField, self).save(*args, **kwargs) def delete(self, *args, **kwargs): fields_after = self.form.fields.filter(order__gte=self.order) fields_after.update(order=models.F('order') - 1) super(AbstractField, self).delete(*args, **kwargs) def is_a(self, *args): ''' Helper that returns True if the field's type is given in any arg. ''' return self.field_type in args class AbstractFormEntry(models.Model): ''' An entry submitted via constructed form. ''' creation_time = models.DateTimeField(_('Date/time')) form = models.ForeignKey(FORM_MODEL, related_name='entries') class Meta: verbose_name = _('Form entry') verbose_name_plural = _('Form entries') abstract = True def __unicode__(self): return '%s - %s' % (self.form, self.creation_time) def save(self, *args, **kwargs): self.creation_time = now() return super(AbstractFormEntry, self).save(*args, **kwargs) class AbstractFieldEntry(models.Model): ''' A single field value for a form entry. ''' field_id = models.IntegerField() value = models.CharField(max_length=2000, null=True) entry = models.ForeignKey(FORM_ENTRY_MODEL, related_name='fields') order = models.IntegerField(_('Order'), null=True, blank=True) class Meta: verbose_name = _('Form field entry') verbose_name_plural = _('Form field entries') ordering = ('order',) abstract = True def __unicode__(self): return '%s - %s' % (self.entry.form, self.field_id) def save(self, *args, **kwargs): if self.order is None: self.order = self.entry.fields.count() return super(AbstractFieldEntry, self).save(*args, **kwargs) # # # Default implementations. # # # class Form(AbstractForm): pass class Field(AbstractField): pass class FormEntry(AbstractFormEntry): pass class FieldEntry(AbstractFieldEntry): pass
// // ViewController.swift // Project4-6 // // Created by Bernardo Cuervo on 16/01/22. // Copyright © 2022 Bernardo Cuervo. All rights reserved. // import UIKit class ViewController: UITableViewController { var shoppingList = [String]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addItem)) title = "ShoppingList" //navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .never navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareList)) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Item", for: indexPath) cell.textLabel?.text = shoppingList[indexPath.row] return cell } @objc func addItem() { let ac = UIAlertController(title: "Enter item", message: nil, preferredStyle: .alert) ac.addTextField() let submitAction = UIAlertAction(title: "Submit", style: .default) { [unowned self, ac] action in let item = ac.textFields![0] self.submit(item: item.text!) } ac.addAction(submitAction) present(ac, animated: true) } func submit(item: String) { let _ = item.lowercased() shoppingList.insert(item, at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) //return } @objc func shareList() { let list = shoppingList.joined(separator: "\n") // guard let list = shoppingList.joined(separator: "\n") else { // print("No list found") // return // } let vc = UIActivityViewController(activityItems: [list], applicationActivities: []) vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem present(vc, animated: true) } //let list = shoppingList.joined(separator: "\n") }
<?php namespace Arshad\Slider\Helper; use Arshad\Slider\Model\SliderFactory; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Framework\App\Http\Context as HttpContext; use Magento\Framework\App\ObjectManager; use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\Json\Helper\Data as JsonHelper; use Arshad\Slider\Model\ResourceModel\Banner\Collection; use Arshad\Slider\Model\BannerFactory; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Store\Model\StoreManagerInterface; class Data extends AbstractHelper { /** * @var BannerFactory */ public $bannerFactory; /** * @type ObjectManagerInterface */ protected $objectManager; /** * @var SliderFactory */ private $sliderFactory; /** * @type StoreManagerInterface */ protected $storeManager; /** * @var DateTime */ protected $date; /** * @var HttpContext */ protected $httpContext; public function __construct( BannerFactory $bannerFactory, ObjectManagerInterface $objectManager, SliderFactory $sliderFactory, StoreManagerInterface $storeManager, HttpContext $httpContext, DateTime $date, Context $context ) { $this->bannerFactory = $bannerFactory; $this->objectManager = $objectManager; $this->sliderFactory = $sliderFactory; $this->storeManager = $storeManager; $this->httpContext = $httpContext; $this->date = $date; parent::__construct($context); } public function versionCompare($ver, $operator = '>=') { $productMetadata = $this->objectManager->get(ProductMetadataInterface::class); $version = $productMetadata->getVersion(); //will return the magento version return version_compare($version, $ver, $operator); } public function serialize($data) { if ($this->versionCompare('2.2.0')) { return self::jsonEncode($data); } return $this->getSerializeClass()->serialize($data); } protected function getSerializeClass() { return $this->objectManager->get('Zend_Serializer_Adapter_PhpSerialize'); } public static function jsonEncode($valueToEncode) { try { $encodeValue = self::getJsonHelper()->jsonEncode($valueToEncode); } catch (Exception $e) { $encodeValue = '{}'; } return $encodeValue; } /** * @return JsonHelper|mixed */ public static function getJsonHelper() { return ObjectManager::getInstance()->get(JsonHelper::class); } /** * @param null $id * * @return Collection */ public function getBannerCollection($id = null) { $collection = $this->bannerFactory->create()->getCollection(); $collection->join( ['banner_slider' => $collection->getTable('arshad_banner_slider')], 'main_table.banner_id=banner_slider.banner_id AND banner_slider.slider_id=' . $id, ['position'] ); $collection->addOrder('position', 'ASC'); return $collection; } public function getBannerOptions(\Arshad\Slider\Model\Slider $slider) { $sliderOptions = ['animateOut' => $slider->getEffect(), 'nav' => $slider->getNav(), 'dots' => $slider->getDots()]; return self::jsonEncode($sliderOptions); } public function getActiveSliders() { /** @var \Arshad\Slider\Model\ResourceModel\Slider\Collection $collection */ $collection = $this->sliderFactory->create() ->getCollection() ->addFieldToFilter('customer_group_ids', [ 'finset' => $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_GROUP) ]) ->addFieldToFilter('status', 1); $collection->getSelect() ->where('FIND_IN_SET(0, store_ids) OR FIND_IN_SET(?, store_ids)', $this->storeManager->getStore()->getId()) ->where('from_date is null OR from_date <= ?', $this->date->date()) ->where('to_date is null OR to_date >= ?', $this->date->date()); return $collection; } public function isEnabled() { return $this->scopeConfig->getValue('arshadslider/general/enabled'); } }
<mat-toolbar class="subtitulo">Beneficiário</mat-toolbar> <div class="painel-principal" style="padding: 10px;"> <div class="painel-consultar"> <form [formGroup]="form" role="form"> <div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="16px" fxFlexFill> <div fxFlex="35%" fxLayoutGap="20px"> <mat-form-field style="width: 100%;" fxLayoutGap="20px" fxFlexOffset="20px"> <input matInput maxlength="255" name="beneficiario" placeholder="Nome do Benefiário:" formControlName="beneficiario"> </mat-form-field> </div> <div fxFlex="35%" fxLayoutGap="20px" fxFlexOffset="40px"> <mat-form-field style="width: 100%;"> <input matInput maxlength="255" name="mae" placeholder="Nome da Mãe:" formControlName="mae"> </mat-form-field> </div> <div fxFlex="15%" fxLayoutGap="20px" fxFlexOffset="40px"> <mat-form-field style="width: 100%;"> <input matInput name="cpf" placeholder="CPF:" formControlName="cpf" [textMask]="{mask: mascaraCpf}"> </mat-form-field> </div> </div> <div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="16px" fxFlexFill> <div fxFlex="35%" fxLayoutGap="20px"> <mat-form-field style="width: 100%;" fxLayoutGap="20px" fxFlexOffset="20px"> <input matInput name="dataInicioEntrada" [matDatepicker]="dataInicioEntrada" placeholder="Data Início Entrada" formControlName="dataInicioEntradaInstituicao" (input)="onMascaraDataInput($event)"> <mat-datepicker-toggle matSuffix [for]="dataInicioEntrada"></mat-datepicker-toggle> <mat-datepicker #dataInicioEntrada></mat-datepicker> </mat-form-field> </div> <div fxFlex="35%" fxLayoutGap="20px" fxFlexOffset="40px"> <mat-form-field style="width: 100%;"> <input matInput name="dataFimEntrada" [matDatepicker]="dataFimEntrada" placeholder="Data Fim Entrada" formControlName="dataFimEntradaInstituicao" (input)="onMascaraDataInput($event)"> <mat-datepicker-toggle matSuffix [for]="dataFimEntrada"></mat-datepicker-toggle> <mat-datepicker #dataFimEntrada></mat-datepicker> </mat-form-field> </div> </div> <div dir="rtl" class="botoes" fxLayoutGap="20px" style="padding-top: 20px; padding-bottom: 20px;" fxFlexFill> <button mat-raised-button fxFlex="20%" (click)="consultar()"> CONSULTAR </button> <button mat-raised-button fxFlex="20%" style="padding-right: 20px" (click)="limpar()" route> LIMPAR </button> </div> </form> <table *ngIf="mostrarTabela; else tabelaSemDados" mat-table [dataSource]="dataSource" style="margin-top: 20px"> <ng-container matColumnDef="matricula"> <th mat-header-cell *matHeaderCellDef> Matrícula: </th> <td mat-cell *matCellDef="let element"> {{element.matriculaAluno}} </td> </ng-container> <ng-container matColumnDef="nome"> <th mat-header-cell *matHeaderCellDef> Nome: </th> <td mat-cell *matCellDef="let element"> {{element.pessoaFisica.nome}} </td> </ng-container> <ng-container matColumnDef="stAtivo"> <th mat-header-cell *matHeaderCellDef> Aluno Ativo </th> <td mat-cell *matCellDef="let element"> {{element.stAtivo ? 'Sim' : 'Não'}} </td> </ng-container> <ng-container matColumnDef="participaApresentacaoExterna"> <th mat-header-cell *matHeaderCellDef> Participa apresentações externas </th> <td mat-cell *matCellDef="let element"> {{element.participaApresentacaoExterna ? 'Sim' : 'Não'}} </td> </ng-container> <ng-container matColumnDef="paisCasados"> <th mat-header-cell *matHeaderCellDef> Pais do beneficiário são casados? </th> <td mat-cell *matCellDef="let element"> {{element.paisCasados ? 'Sim' : 'Não'}} </td> </ng-container> <ng-container matColumnDef="moraPais"> <th mat-header-cell *matHeaderCellDef> Mora com os Pais? </th> <td mat-cell *matCellDef="let element"> {{element.moraPais ? 'Sim' : 'Não'}} </td> </ng-container> <ng-container matColumnDef="turno"> <th mat-header-cell *matHeaderCellDef> Turno: </th> <td mat-cell *matCellDef="let element"> {{element.turno}} </td> </ng-container> <ng-container matColumnDef="serie"> <th mat-header-cell *matHeaderCellDef> Série: </th> <td mat-cell *matCellDef="let element"> {{element.serieEscola}} </td> </ng-container> <ng-container matColumnDef="dataEntrada"> <th mat-header-cell *matHeaderCellDef> Data Admissão: </th> <td mat-cell *matCellDef="let element"> {{element.dataEntrada | dataSimples}} </td> </ng-container> <ng-container matColumnDef="dataDesligamento"> <th mat-header-cell *matHeaderCellDef> Data Desligamento: </th> <td mat-cell *matCellDef="let element"> {{element.dataDesligamento | dataSimples}} </td> </ng-container> <ng-container matColumnDef="ativo"> <th mat-header-cell *matHeaderCellDef> Ativo: </th> <td mat-cell *matCellDef="let element"> {{element.stAtivo | simNao}} </td> </ng-container> <ng-container matColumnDef="acoes"> <th mat-header-cell *matHeaderCellDef> Ações </th> <td mat-cell *matCellDef="let element"> <button *ngIf="perfilAcesso.deleta" mat-button (click)="deletar(element)"> <mat-icon>delete</mat-icon> </button> <button *ngIf="perfilAcesso.consulta" mat-button (click)="atualizar(element)"> <mat-icon>search</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <div [hidden]="!mostrarTabela"> <mat-paginator [length]="numberItens" [pageSizeOptions]="[10, 20, 40, 60, 80, 100]" showFirstLastButtons (page)="onEventPaginate($event)"></mat-paginator> </div> <ng-template #tabelaSemDados> <div fxLayout="row" fxLayoutAlign="center center" style="padding-top: 20px"> {{msg}} </div> </ng-template> <div fxLayout="row" *ngIf="perfilAcesso.insere" fxLayoutAlign="end center" fxLayoutGap="16px" style="padding-top: 50px"> <div> <button matTooltip="Adicionar novo aluno" mat-fab color="primary" [routerLink]="['/aluno/cadastrar']" routerLinkActive="router-link-active"> <mat-icon>add</mat-icon> </button> </div> </div> </div> </div>
// // RelayDetailView.swift // Nos // // Created by Martin Dutra on 6/7/23. // import SwiftUI struct RelayDetailView: View { var relay: Relay func row(title: Localized, value: String) -> some View { HStack(alignment: .top) { Text("\(title.string): ") Text(value) .textSelection(.enabled) } } var body: some View { List { Section { Text(relay.address ?? Localized.error.string) .textSelection(.enabled) } header: { Localized.address.view .foregroundColor(.primaryTxt) .fontWeight(.heavy) } .listRowBackground(LinearGradient( colors: [Color.cardBgTop, Color.cardBgBottom], startPoint: .top, endPoint: .bottom )) Section { if let name = relay.name { row(title: .name, value: name) } if let description = relay.relayDescription { row(title: .description, value: description) } if let supportedNIPs = relay.supportedNIPs { row(title: .supportedNIPs, value: supportedNIPs.map { String($0) }.joined(separator: ", ")) } if let pubkey = relay.pubkey { row(title: .pubkey, value: pubkey) } if let contact = relay.contact { row(title: .contact, value: contact) } if let software = relay.software { row(title: .software, value: software) } if let version = relay.version { row(title: .version, value: version) } } header: { Localized.metadata.view .foregroundColor(.primaryTxt) .fontWeight(.heavy) } footer: { #if DEBUG if let date = relay.metadataFetchedAt { Text("\(Localized.fetchedAt.string): \(date.distanceFromNowString())") } #endif } .listRowBackground(LinearGradient( colors: [Color.cardBgTop, Color.cardBgBottom], startPoint: .top, endPoint: .bottom )) } .scrollContentBackground(.hidden) .background(Color.appBg) .nosNavigationBar(title: .relay) } } struct RelayDetailView_Previews: PreviewProvider { static var previewContext = PersistenceController.preview.container.viewContext static var relay: Relay { do { return try Relay(context: previewContext, address: "wss://example.com") } catch { return Relay(context: previewContext) } } static var previews: some View { RelayDetailView(relay: relay) } }
<form class="row g-3 form" (ngSubmit)="signUp(registerForm)" [formGroup]="registerForm" > <div class="mb-3 col-md-12 form-group"> <label for="username" class="form-label" >Ingrese un nombre de usuario</label > <input name="username" class="form-control" id="username" formControlName="username" required [ngClass]="{ 'is-invalid': (username?.touched || showValidation) && username?.errors, 'is-valid': username?.valid && username?.touched }" /> <span class="invalid-feedback" *ngIf=" (username?.touched || showValidation) && username?.errors?.required " > Debe ingresar un nombre de usuario. <p>El nombre de usuario debe tener 4 o más caracteres.</p> </span> </div> <div class="mb-3 col-md-6 form-group"> <label for="name" class="form-label">Ingrese su nombre</label> <input name="name" class="form-control" id="name" formControlName="name" required [ngClass]="{ 'is-invalid': (name?.touched || showValidation) && name?.errors?.required, 'is-valid': name?.valid && name?.touched }" /> <span class="invalid-feedback" *ngIf="(name?.touched || showValidation) && name?.errors?.required" > Debe ingresar su nombre. </span> </div> <div class="mb-3 col-md-6 form-group"> <label for="lastname" class="form-label">Ingrese su apellido</label> <input name="lastname" class="form-control" id="lastname" formControlName="lastname" required [ngClass]="{ 'is-invalid': (lastname?.touched || showValidation) && lastname?.errors?.required, 'is-valid': lastname?.valid && lastname?.touched }" /> <span class="invalid-feedback" *ngIf=" (lastname?.touched || showValidation) && lastname?.errors?.required " > Debe ingresar su apellido. </span> </div> <div class="mb-3 col-md-12 form-group"> <label for="password" class="form-label">Ingrese una contraseña</label> <input name="password" type="password" class="form-control" id="password" formControlName="password" required [ngClass]="{ 'is-invalid': (password?.touched || showValidation) && password?.errors?.required, 'is-valid': password?.valid && password?.touched }" /> <span class="invalid-feedback" *ngIf=" (password?.touched || showValidation) && password?.errors?.required " > Debe ingresar una contraseña. <p>Mínimo 5 caracteres.</p> </span> </div> <div class="mb-3 col-md-12 form-group"> <label for="repeatpassword" class="form-label">Repita la contraseña</label> <input name="repeatpassword" type="password" class="form-control" id="repeatpassword" formControlName="repeatpassword" required [ngClass]="{ 'is-invalid': ((repeatpassword?.touched || showValidation) && repeatpassword?.errors?.required) || repeatpassword?.errors?.mustMatch, 'is-valid': repeatpassword?.valid && repeatpassword?.touched }" /> <span class="invalid-feedback" *ngIf=" (repeatpassword?.touched || showValidation) && repeatpassword?.errors?.required " > Debe repetir la contraseña. </span> <span class="invalid-feedback" *ngIf="repeatpassword?.errors?.mustMatch"> Las contraseñas no coinciden. </span> </div> <div class="mb-3 col-md-12"> <button class="btn btn-secondary btn-block" type="submit"> Crear cuenta </button> </div> </form>
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import React from "react"; import AccountIcon from "../../../assets/images/bt-acc.svg"; import DiscoveryIcon from "../../../assets/images/bt-disco.svg"; import FavoriteIcon from "../../../assets/images/bt-fav.svg"; import HomeIcon from "../../../assets/images/bt-home.svg"; import InboxIcon from "../../../assets/images/btn-mess.svg"; import Account from "../views/account"; import Discovery from "../views/discovery"; import Favorites from "../views/favorites"; import Homepage from "../views/homepage"; import Inbox from "../views/inbox"; const BottomNavigation = createBottomTabNavigator(); const BottomTab = () => { return ( <BottomNavigation.Navigator initialRouteName="homepage" screenOptions={{ tabBarActiveBackgroundColor: "hsla(100,100%,10%,0.5)", tabBarShowLabel: false, headerShown: false, }} > <BottomNavigation.Screen name="homepage" component={Homepage} options={{ title: "Home", tabBarIcon: () => { return <HomeIcon width={30} height={30} style={{ opacity: 0.7 }} />; }, }} /> <BottomNavigation.Screen name="favorites" component={Favorites} options={{ title: "Favorites", tabBarIcon: () => { return ( <FavoriteIcon width={30} height={30} style={{ opacity: 0.7 }} /> ); }, }} /> <BottomNavigation.Screen name="discovery" component={Discovery} options={{ title: "Discovery", // headerShown: true, // headerTransparent: true, // headerTintColor: "white", tabBarIcon: () => { return ( <DiscoveryIcon width={30} height={30} style={{ opacity: 0.7 }} /> ); }, }} /> <BottomNavigation.Screen name="inbox" component={Inbox} options={{ title: "Inbox", tabBarIcon: () => { return ( <InboxIcon width={30} height={30} style={{ opacity: 0.7 }} /> ); }, }} /> <BottomNavigation.Screen name="account" component={Account} options={{ title: "Account", tabBarIcon: () => { return ( <AccountIcon width={30} height={30} style={{ opacity: 0.7 }} /> ); }, }} /> </BottomNavigation.Navigator> ); }; export default BottomTab;
// import { readFile, readdir } from "node:fs/promises"; // To read the file from the file system. import { marked } from "marked"; // To convert markdown to HTML. // import matter from "gray-matter"; // To parse the front matter from the markdown file. import qs from "qs"; // import { writeFileSync } from "node:fs"; const URL = process.env.NEXT_API_URL || "http://localhost:1337"; export async function getFeaturedReview(pageSize) { const reviews = await getReviews(pageSize); return reviews; } export async function getReview(slug) { const populate = "?" + qs.stringify( { filters: { slug: { $eq: slug } }, fields: ["slug", "title", "subtitle", "publishedAt", "body"], populate: { image: { fields: ["url"] } }, pagination: { pageSize: 6 }, // sort: ["publishedAt:desc"], }, { encodeValuesOnly: true } ); // By default , strapi treats image as seperate object and does not include it in the api call , this code also includes the media in the call. const endpoint = URL + "/api/reviews" + populate; const response = await fetch(endpoint); const { data } = await response.json(); if(data[0] === undefined) { return null; } const { attributes } = data[0]; return { slug: attributes.slug, title: attributes.title, subtitle:attributes.subtitle, date: attributes.publishedAt.slice(0, "yyyy-mm-dd".length), image: URL + attributes.image.data.attributes.url, body: marked(attributes.body,{headerIds:false,mangle:false}), }; } export async function getReviews(pageSize,page) { let pageCount = ""; const populate = "?" + qs.stringify( { fields: ["slug", "title", "subtitle", "publishedAt"], populate: { image: { fields: ["url"] } }, pagination: {pageSize,page }, sort: ["publishedAt:desc"], }, { encodeValuesOnly: true } ); // By default , strapi treats image as seperate object and does not include it in the api call , this code also includes the media in the call. const endpoint = URL + "/api/reviews" + populate; const response = await fetch(endpoint); const { data , meta } = await response.json(); return data.map(({ attributes }) => ({ slug: attributes.slug, title: attributes.title, subtitle: attributes.subtitle, date: attributes.publishedAt.slice(0, 'yyyy-mm-dd'.length), image: URL + attributes.image.data.attributes.url, pageCount, }) ); } export async function getSlugs() { const populate = `?${ qs.stringify( { fields: ["slug"], pagination: { pageSize: 100 }, sort: ["publishedAt:desc"], }, { encodeValuesOnly: true } )}`; // By default , strapi treats image as seperate object and does not include it in the api call , this code also includes the media in the call. const endpoint = URL + "/api/reviews" + populate; const response = await fetch(endpoint); const { data } = await response.json(); return data.map(({ attributes }) => ({ slug: attributes.slug, })); } export async function getPageCount(pageSize,page) { let pageCount = 0; const populate = "?" + qs.stringify( { fields: ["slug", "title", "subtitle", "publishedAt"], populate: { image: { fields: ["url"] } }, pagination: {pageSize,page }, sort: ["publishedAt:desc"], }, { encodeValuesOnly: true } ); // By default , strapi treats image as seperate object and does not include it in the api call , this code also includes the media in the call. const endpoint = URL + "/api/reviews" + populate; const response = await fetch(endpoint); const { data , meta } = await response.json(); pageCount = meta.pagination.pageCount; return pageCount; }
import Services from "./class.services.js"; import persistence from "../persistence/persistence.js"; const { productDao } = persistence; import { generateProduct } from "../utils/utils.js"; import ProductRepository from "../persistence/repository/product/product.repository.js"; const productRepository = new ProductRepository(); export default class ProductService extends Services { constructor() { super(productDao); } async createMocksProducts(cant = 100) { try { const productsArray = []; for (let i = 0; i < cant; i++) { const product = generateProduct(); productsArray.push(product); } const products = await productDao.create(productsArray); return products; } catch (error) { throw new Error(error.message); } } async createProduct(product) { try { const newProduct = await productRepository.createProduct(product); if (!newProduct) { return false; } else { return newProduct; } } catch (error) { throw new Error(error.message); } } async getProductById(id) { try { const product = await productRepository.getProductById(id); if (!product) { return false; } else { return product; } } catch (error) { throw new Error(error.message); } } }
首先$a_i <= 10^9$先离散化 一个很$naive$的想法是先$O(n)$预处理除所有的$f(1, i, a_i)$和$f(j, n, a_j)$分别存在$f_1$和$f_2$中 我们考虑一个位置$i$对答案的贡献 显然只有$f_2[j] < f_1[i]$的$j$才对答案有贡献 那我们就可以维护一个树状数组 倒着枚举统计答案即可 ```cpp const int N = 1e6 + 10; int n, ans; int a[N], lsh[N], qaq; int num1[N], num2[N], f1[N], f2[N]; int tree[N]; inline void add(int x) { for(; x <= n; x += x & -x) tree[x] += 1; } inline int ask(int x) { int res = 0; for(; x; x -= x & -x) res += tree[x]; return res; } signed main() { read(n); for(R int i = 1; i <= n; i++) read(a[i]), lsh[i] = a[i]; //离散 sort(lsh + 1, lsh + n + 1); qaq = unique(lsh + 1, lsh + n + 1) - lsh - 1; for(R int i = 1; i <= n; i++) a[i] = lower_bound(lsh + 1, lsh + qaq + 1, a[i]) - lsh; //预处理f1 f2 for(R int i = 1; i <= n; i++) { num1[a[i]]++; f1[i] = num1[a[i]]; } for(R int i = n; i >= 1; i--) { num2[a[i]]++; f2[i] = num2[a[i]]; } //倒着枚举统计答案 for(R int i = n; i >= 1; i--) { ans += ask(f1[i] - 1); add(f2[i]); } writeln(ans); return 0; } ```
import { QueryClientProvider } from '@tanstack/react-query' import { CustomUserProperties, InterfaceEventName, WalletConnectionResult } from '@uniswap/analytics-events' import { sendAnalyticsEvent, useTrace, user } from 'analytics' import { recentConnectorIdAtom } from 'components/Web3Provider/constants' import { queryClient, wagmiConfig } from 'components/Web3Provider/wagmi' import { useIsSupportedChainId } from 'constants/chains' import { RPC_PROVIDERS } from 'constants/providers' import { useEthersWeb3Provider } from 'hooks/useEthersProvider' import usePrevious from 'hooks/usePrevious' import { useUpdateAtom } from 'jotai/utils' import { ReactNode, useEffect } from 'react' import { useLocation } from 'react-router-dom' import { useConnectedWallets } from 'state/wallets/hooks' import { FeatureFlags } from 'uniswap/src/features/gating/flags' import { useFeatureFlag } from 'uniswap/src/features/gating/hooks' import { getCurrentPageFromLocation } from 'utils/urlRoutes' import { getWalletMeta } from 'utils/walletMeta' import { WagmiProvider, useAccount } from 'wagmi' export default function Web3Provider({ children }: { children: ReactNode }) { return ( <WagmiProvider config={wagmiConfig}> <QueryClientProvider client={queryClient}> <Updater /> {children} </QueryClientProvider> </WagmiProvider> ) } /** A component to run hooks under the Web3ReactProvider context. */ function Updater() { const { address: account, chainId } = useAccount() const provider = useEthersWeb3Provider() const isSupportedChain = useIsSupportedChainId(chainId) const { connector } = useAccount() const { pathname } = useLocation() const currentPage = getCurrentPageFromLocation(pathname) const analyticsContext = useTrace() const networkProvider = isSupportedChain ? RPC_PROVIDERS[chainId] : undefined const updateRecentConnectorId = useUpdateAtom(recentConnectorIdAtom) useEffect(() => { if (connector) updateRecentConnectorId(connector.id) }, [connector, updateRecentConnectorId]) // Trace RPC calls (for debugging). const shouldTrace = useFeatureFlag(FeatureFlags.TraceJsonRpc) useEffect(() => { if (shouldTrace) { provider?.on('debug', trace) if (provider !== networkProvider) { networkProvider?.on('debug', trace) } } return () => { provider?.off('debug', trace) networkProvider?.off('debug', trace) } }, [analyticsContext, networkProvider, provider, shouldTrace]) const previousConnectedChainId = usePrevious(chainId) useEffect(() => { const chainChanged = previousConnectedChainId && previousConnectedChainId !== chainId if (chainChanged) { sendAnalyticsEvent(InterfaceEventName.CHAIN_CHANGED, { result: WalletConnectionResult.SUCCEEDED, wallet_address: account, wallet_type: connector?.name ?? 'Network', chain_id: chainId, previousConnectedChainId, page: currentPage, }) } }, [account, chainId, connector, currentPage, previousConnectedChainId]) // Send analytics events when the active account changes. const previousAccount = usePrevious(account) const [connectedWallets, addConnectedWallet] = useConnectedWallets() useEffect(() => { if (account && account !== previousAccount) { const walletType = connector?.name ?? 'Network' const peerWalletAgent = provider ? getWalletMeta(provider)?.agent : undefined const isReconnect = connectedWallets.some( (wallet) => wallet.account === account && wallet.walletType === walletType ) provider ?.send('web3_clientVersion', []) .then((clientVersion) => { user.set(CustomUserProperties.WALLET_VERSION, clientVersion) }) .catch((error) => { console.warn('Failed to get client version', error) }) // User properties *must* be set before sending corresponding event properties, // so that the event contains the correct and up-to-date user properties. user.set(CustomUserProperties.WALLET_ADDRESS, account) user.postInsert(CustomUserProperties.ALL_WALLET_ADDRESSES_CONNECTED, account) user.set(CustomUserProperties.WALLET_TYPE, walletType) user.set(CustomUserProperties.PEER_WALLET_AGENT, peerWalletAgent ?? '') if (chainId) { user.set(CustomUserProperties.CHAIN_ID, chainId) user.postInsert(CustomUserProperties.ALL_WALLET_CHAIN_IDS, chainId) } sendAnalyticsEvent(InterfaceEventName.WALLET_CONNECTED, { result: WalletConnectionResult.SUCCEEDED, wallet_address: account, wallet_type: walletType, is_reconnect: isReconnect, peer_wallet_agent: peerWalletAgent, page: currentPage, }) addConnectedWallet({ account, walletType }) } }, [account, addConnectedWallet, currentPage, chainId, connectedWallets, connector, previousAccount, provider]) return null } function trace(event: any) { if (!event?.request) return const { method, id, params } = event.request console.groupCollapsed(method, id) console.debug(params) console.groupEnd() }
package main import ( "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" ) func (app *application) routes() http.Handler { mux := chi.NewRouter() mux.Use(middleware.Recoverer) mux.Use(cors.Handler(cors.Options{ AllowedOrigins: []string{"https://*", "http://*"}, AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, ExposedHeaders: []string{"link"}, AllowCredentials: true, MaxAge: 300, })) mux.Post("/users/login", app.Login) mux.Post("/users/logout", app.Logout) mux.Post("/validate-token", app.ValidateToken) mux.Route("/admin", func(mux chi.Router) { mux.Use(app.AuthTokenMiddleware) mux.Post("/users/all", app.AllUsers) mux.Post("users/save", app.EditUser) mux.Post("users/delete", app.DeleteUser) mux.Post("/log-user-out/{id}", app.LogUserOutAndSetInactive) }) mux.Get("/users/all", func(w http.ResponseWriter, r *http.Request) { }) return mux }
# # This file is part of the mpc_quad_ros distribution (https://github.com/smidmatej/mpc_quad_ros). # Copyright (c) 2023 Smid Matej. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation import matplotlib.pyplot as plt import matplotlib import pandas as pd import numpy as np from utils.utils import v_dot_q import matplotlib as style from matplotlib import gridspec import matplotlib.colors as colors from tqdm import tqdm from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm import seaborn as sns import os from utils.save_dataset import load_dict from functools import partial from gp.GPE import GPEnsemble class Visualiser: def __init__(self, trajectory_filename=None): # Color scheme convert from [0,255] to [0,1] self.cs = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] if trajectory_filename: self.trajectory_filename = trajectory_filename print(f'Visualising data in {self.trajectory_filename}') self.data_dict = load_dict(self.trajectory_filename) def visualize_trajectory(self, filepath, result_filename): print(f'Visualising data in {filepath}') df = pd.read_csv(filepath, encoding='utf-8') font = {'family' : 'normal', 'size' : 14} matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rc('font', **font) plt.style.use('fast') sns.set_style("whitegrid") self.fig = plt.figure(figsize=(10,10), dpi=100) self.ax = self.fig.add_subplot(projection='3d') # Get rid of colored axes planes # First remove fill self.ax.xaxis.pane.fill = False self.ax.yaxis.pane.fill = False self.ax.zaxis.pane.fill = False # Now set color to white (or whatever is "invisible") self.ax.xaxis.pane.set_edgecolor('k') self.ax.yaxis.pane.set_edgecolor('k') self.ax.zaxis.pane.set_edgecolor('k') plt.plot(df['x'], df['y'], df['z'], color=self.cs[1], alpha=0.5) self.ax.set_xlabel('Position $x$ [m]') self.ax.set_ylabel('Position $y$ [m]') self.ax.set_zlabel('Position $z$ [m]') self.ax.set_zlim([0, 2*max(df['z'])]) self.ax.view_init(elev=20, azim=120, roll=0) plt.tight_layout() print(f'Saving plot to {result_filename}') plt.savefig(result_filename, format="pdf") plt.show() def visualize_cov_data(self, filepath, result_filename): print(f'Visualising data in {filepath}') font = {'family' : 'normal', 'size' : 14} matplotlib.rc('font', **font) matplotlib.rcParams['pdf.fonttype'] = 42 df = pd.read_csv(filepath, encoding='utf-8') gp0 = df[df['gp'] == 0] gp2 = df[df['gp'] == 2] plt.style.use('fast') sns.set_style("whitegrid") labs = ['x', 'y', 'z'] gs = gridspec.GridSpec(1, 3) self.fig = plt.figure(figsize=(12,6), dpi=100) self.ax = [None]*3 for d in range(3): self.ax[d] = self.fig.add_subplot(gs[d]) self.ax[d].scatter(gp0['v_p'], np.abs(gp0['c_'+labs[d]]), marker='.', color=self.cs[1], s=100, label='gp0') self.ax[d].scatter(gp2['v_p'], np.abs(gp2['c_'+labs[d]]), marker='.', color=self.cs[2], s=100, label='gp2') self.ax[d].plot(gp0['v_p'], np.abs(gp0['c_'+labs[d]]), '--', color=self.cs[1]) self.ax[d].plot(gp2['v_p'], np.abs(gp2['c_'+labs[d]]), '--', color=self.cs[2]) self.ax[d].set_xlabel(r'Peak velocity $v_{peak}$ [$ms^{-1}$]') cov_text = f'cov(v_{labs[d]},e_{labs[d]})' self.ax[d].set_ylabel(r'$\vert ' + cov_text + r' \vert$ [$m^2s^{-1}$]') #self.ax[d].legend() self.ax[d].set_title(f'${labs[d]}_B$') #plt.tight_layout(pad=4, w_pad=0.5) plt.tight_layout(rect=[0, 0, 1, 0.95]) self.fig.legend(labels=['Nominal', 'RGP augmented'], bbox_to_anchor=(0.5, 1), fancybox=True, shadow=True, ncol=5, loc='upper center', fontsize='large') print(f'Saving plot to {result_filename}') plt.savefig(result_filename, format="pdf") plt.show() def create_3D_plot(self, result_filename): plt.rc('axes', labelsize=14) # fontsize of the x and y labels # Load data self.position = np.stack(self.data_dict['x_odom'], axis=0)[:,:3] self.orientation = np.stack(self.data_dict['x_odom'], axis=0)[:, 3:7] self.velocity = np.stack(self.data_dict['x_odom'], axis=0)[:,7:10] self.control = np.stack(self.data_dict['w_odom'], axis=0)[:,:] self.t = np.stack(self.data_dict['t_odom'], axis=0)[:] self.speed = np.linalg.norm(self.velocity, axis=1) self.dp = np.diff(self.position, axis=0)/np.diff(self.t)[:,None] self.dp_norm = np.linalg.norm(self.dp, axis=1) plt.style.use('fast') sns.set_style("whitegrid") self.fig = plt.figure(figsize=(10,10), dpi=100) self.ax = self.fig.add_subplot(projection='3d') # Get rid of colored axes planes # First remove fill self.ax.xaxis.pane.fill = False self.ax.yaxis.pane.fill = False self.ax.zaxis.pane.fill = False # Now set color to white (or whatever is "invisible") self.ax.xaxis.pane.set_edgecolor('k') self.ax.yaxis.pane.set_edgecolor('k') self.ax.zaxis.pane.set_edgecolor('k') self.particle, = plt.plot(self.position[0,0], self.position[0,1], self.position[0,2], marker='o', color=self.cs[3]) self.traj, = plt.plot(self.position[:,0], self.position[:,1], self.position[:,2], color=self.cs[1], alpha=0.5) #self.ax.set_xlim((self.min_lim, self.max_lim)) #self.ax.set_ylim((self.min_lim, self.max_lim)) #self.ax.set_zlim((self.min_lim, self.max_lim)) self.ax.set_xlabel('Position $x$ [m]') self.ax.set_ylabel('Position $y$ [m]') self.ax.set_zlabel('Position $z$ [m]') self.ax.view_init(elev=20, azim=20, roll=0) print(f'Saving plot to {result_filename}') plt.savefig(result_filename, format="pdf") plt.show() plt.close() def create_animation(self, result_animation_filename, desired_number_of_frames, use_color_map=True, gif=False): self.desired_number_of_frames = desired_number_of_frames self.use_color_map = use_color_map self.prepare_animation_data() self.prepare_animation_figure() interval = 20 # 50 fps self.number_of_frames = self.position.shape[0] print('Creating animation...') print(f'Number of frames: {self.number_of_frames}, fps: {1000/interval}, duration: {self.number_of_frames*interval/1000} s') self.pbar = tqdm(total=self.number_of_frames) def animate(i): # Current position #print(f'Frame: {i}') self.particle.set_data_3d(self.position[i,0], self.position[i,1], self.position[i,2]) if self.use_color_map: # Plots the visited trajectory based on color. Computationaly expensive self.traj, = self.ax.plot(self.position[i:i+2,0], self.position[i:i+2,1], self.position[i:i+2,2], \ color=plt.cm.jet(self.speed[i]/max(self.speed)), linewidth=0.8) # orientation self.vector_up.set_data_3d(np.array([self.position[i,0], self.position[i,0] + self.body_up[i,0]]), \ np.array([self.position[i,1], self.position[i,1] + self.body_up[i,1]]), \ np.array([self.position[i,2], self.position[i,2] + self.body_up[i,2]])) # Norm of veloctity to plot to a different ax self.v_traj.set_data(self.t[:i+1], self.speed[:i+1]) if i < self.number_of_frames-1: # dp_norm is a diff, missing the last value self.dp_traj.set_data(self.t[:i+1], self.dp_norm[:i+1]) for j in range(self.control.shape[1]): self.control_traj[j].set_data(self.t[:i+1], self.control[:i+1,j]) self.pbar.update() ani = animation.FuncAnimation(self.fig, animate, frames=self.number_of_frames, interval=interval) ani.save(result_animation_filename + '.mp4', writer='ffmpeg', fps=10, dpi=100) if gif: ani.save(result_animation_filename + '.gif', writer='imagemagick', fps=10, dpi=100) def create_rgp_animation(self, result_animation_filename, desired_number_of_frames, use_color_map=True, gif=False): self.desired_number_of_frames = desired_number_of_frames self.use_color_map = use_color_map self.prepare_rgp_animation_data() self.prepare_rgp_animation_figure() interval = 20 # 50 fps self.number_of_frames = len(self.X) print('Creating RGP animation...') print(f'Number of frames: {self.number_of_frames}, fps: {1000/interval}, duration: {self.number_of_frames*interval/1000} s') self.pbar = tqdm(total=self.number_of_frames) def animate(i): for d in range(3): self.scat_basis_vectors[d].set_offsets(np.array([self.X[i][d].ravel(), self.y[i][d].ravel()]).T) self.pbar.update() ani = animation.FuncAnimation(self.fig, animate, frames=self.number_of_frames, interval=interval) ani.save(result_animation_filename + '.mp4', writer='ffmpeg', fps=10, dpi=100) if gif: ani.save(result_animation_filename + '.gif', writer='imagemagick', fps=10, dpi=100) def prepare_animation_data(self): # Calculates how many datapoints to skip to get the desired number of frames skip = int(self.data_dict['x_odom'].shape[0]/self.desired_number_of_frames) # Load data self.position = self.data_dict['x_odom'][::skip,:3] self.orientation = self.data_dict['x_odom'][::skip, 3:7] self.velocity = self.data_dict['x_odom'][::skip,7:10] self.control = w[::skip,:] self.t = t[::skip] self.speed = np.linalg.norm(self.velocity, axis=1) self.dp = np.diff(self.position, axis=0)/np.diff(self.t)[:,None] self.dp_norm = np.linalg.norm(self.dp, axis=1) # Limits of the plot for xlim, ylim, zlim # xlim=ylim=zlim self.min_lim = min(min(self.position[:,0]), min(self.position[:,1]), min(self.position[:,2])) self.max_lim = max(max(self.position[:,0]), max(self.position[:,1]), max(self.position[:,2])) # Up arrow us just for visualization, dont want it to be too big/small self.up_arrow_length = (self.max_lim - self.min_lim)/5 self.body_up = np.array([v_dot_q(np.array([0, 0, self.up_arrow_length]), self.orientation[i,:]) for i in range(self.orientation.shape[0])]) def prepare_animation_figure(self): animation.writer = animation.writers['ffmpeg'] plt.ioff() # Turn off interactive mode to hide rendering animations # Color scheme convert from [0,255] to [0,1] self.cs = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] plt.style.use('fast') sns.set_style("whitegrid") gs = gridspec.GridSpec(2, 2) self.fig = plt.figure(figsize=(10,10), dpi=100) self.ax = self.fig.add_subplot(gs[0:2,0], projection='3d') # Get rid of colored axes planes # First remove fill self.ax.xaxis.pane.fill = False self.ax.yaxis.pane.fill = False self.ax.zaxis.pane.fill = False # Now set color to white (or whatever is "invisible") self.ax.xaxis.pane.set_edgecolor('k') self.ax.yaxis.pane.set_edgecolor('k') self.ax.zaxis.pane.set_edgecolor('k') self.particle, = plt.plot([],[], marker='o', color=self.cs[1]) self.vector_up, = plt.plot([],[], color=self.cs[3]) self.traj, = plt.plot([],[], color=self.cs[0], alpha=0.5) self.ax.set_xlim((self.min_lim, self.max_lim)) self.ax.set_ylim((self.min_lim, self.max_lim)) self.ax.set_zlim((self.min_lim, self.max_lim)) self.ax.set_xlabel('Position x [m]') self.ax.set_ylabel('Position y [m]') self.ax.set_zlabel('Position z [m]') self.ax.set_title('Quadcopter flight') self.ax_control = self.fig.add_subplot(gs[0,1]) self.control_traj = [None]*4 for i in range(self.control.shape[1]): self.control_traj[i], = self.ax_control.plot([], [], label='u'+str(i), c=self.cs[i]) self.ax_control.set_xlim((min(self.t), max(self.t))) self.ax_control.set_ylim((0, 1)) self.ax_control.set_xlabel('Time [s]') self.ax_control.set_ylabel('Control u ') self.ax_control.set_title('Control') self.ax_control.legend(('u0', 'u1', 'u2', 'u3'), loc='upper right') self.ax_speed = self.fig.add_subplot(gs[1,1]) self.v_traj, = plt.plot([],[], color=self.cs[0]) self.dp_traj, = plt.plot([],[], color=self.cs[0]) self.ax_speed.set_xlim((min(self.t), max(self.t))) self.ax_speed.set_ylim((0, max(self.speed))) self.ax_speed.set_xlabel('Time [s]') self.ax_speed.set_ylabel('Speed [m/s]') self.ax_speed.set_title('Velocity magnitude') self.fig.tight_layout() def prepare_rgp_animation_figure(self): animation.writer = animation.writers['ffmpeg'] plt.ioff() # Turn off interactive mode to hide rendering animations # Color scheme convert from [0,255] to [0,1] self.cs = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] plt.style.use('fast') sns.set_style("whitegrid") gs = gridspec.GridSpec(1, 3) self.fig = plt.figure(figsize=(10,6), dpi=100) labels = ['x', 'y', 'z'] self.ax = [None]*3 self.scat_basis_vectors = [None]*3 for d in range(3): self.ax[d] = self.fig.add_subplot(gs[d]) self.scat_basis_vectors[d] = self.ax[d].scatter([], [], marker='o', label='Basis Vectors') self.ax[d].set_xlim(self.x_lim) self.ax[d].set_ylim(self.y_lim) self.ax[d].set_xlabel('Velocity [ms-1]') self.ax[d].set_ylabel('Drag acceleration [ms-2]') self.ax[d].set_title(f'RGP basis vectors in {labels[d]}') self.fig.tight_layout() def prepare_rgp_animation_data(self): # Calculates how many datapoints to skip to get the desired number of frames skip = int(self.data_dict['x_odom'].shape[0]/self.desired_number_of_frames) # Load data self.X_array = self.data_dict['rgp_basis_vectors'][::skip] self.y_array = self.data_dict['rgp_params'][::skip] n_basis = self.X_array.shape[1]//3 self.X = [None]*self.X_array.shape[0] self.y = [None]*self.X_array.shape[0] for i in range(self.X_array.shape[0]): self.X[i] = [self.X_array[i][d*n_basis:(d+1)*n_basis] for d in range(3)] self.y[i] = [self.y_array[i][d*n_basis:(d+1)*n_basis] for d in range(3)] x_min = 100000 x_max = -100000 y_min = 100000 y_max = -100000 for i in range(len(self.X)): x_min = min(x_min, min(min(self.X[i][0]), min(self.X[i][1]), min(self.X[i][2]))) x_max = max(x_max, max(max(self.X[i][0]), max(self.X[i][1]), max(self.X[i][2]))) y_max = max(y_max, max(max(self.y[i][0]), max(self.y[i][1]), max(self.y[i][2]))) y_min = min(y_min, min(min(self.y[i][0]), min(self.y[i][1]), min(self.y[i][2]))) self.x_lim = (x_min, x_max) self.y_lim = (y_min, y_max) def create_rgp_full_animation(self, result_animation_filename, desired_number_of_frames, use_color_map=True, gif=False): self.desired_number_of_frames = desired_number_of_frames self.use_color_map = use_color_map self.prepare_rgp_full_animation_data() self.prepare_rgp_full_animation_figure() for d in range(3): self.scat_basis_vectors[d].set_offsets(np.array([self.X_basis[0][d], self.mu_g_t[0][d]]).T) self.rgp_mean_plot[d].set_data(self.X_query[d], self.y_query[0][d]) self.fill_between_plots[d].remove() self.fill_between_plots[d] = self.ax[d].fill_between(self.X_query[d].reshape(-1), self.y_query[0][d].reshape(-1) - 2*self.std_query[0][d], self.y_query[0][d].reshape(-1) + 2*self.std_query[0][d], color=self.cs[1], alpha=0.2) plt.savefig(result_animation_filename + "_1st.pdf", format="pdf", bbox_inches="tight") interval = 20 # 50 fps self.number_of_frames = len(self.X_basis) print('Creating RGP animation...') print(f'Number of frames: {self.number_of_frames}, fps: {1000/interval}, duration: {self.number_of_frames*interval/1000} s') self.pbar = tqdm(total=self.number_of_frames) def animate(i): for d in range(3): # # Inneficient way to take a [:i][d] slice, should have used a array. X_sample_array = np.array([float(self.X_sample[j][d]) for j in range(i+1)]).reshape(-1,1) y_sample_array = np.array([float(self.y_sample[j][d]) for j in range(i+1)]).reshape(-1,1) self.scat_basis_vectors[d].set_offsets(np.array([self.X_basis[i][d], self.mu_g_t[i][d]]).T) self.rgp_mean_plot[d].set_data(self.X_query[d], self.y_query[i][d]) self.fill_between_plots[d].remove() self.fill_between_plots[d] = self.ax[d].fill_between(self.X_query[d].reshape(-1), self.y_query[i][d].reshape(-1) - 2*self.std_query[i][d], self.y_query[i][d].reshape(-1) + 2*self.std_query[i][d], color=self.cs[1], alpha=0.2) self.scat_samples[d].set_offsets(np.concatenate((X_sample_array, y_sample_array), axis=1)) self.pbar.update() if i == self.number_of_frames-1: plt.savefig(result_animation_filename + "_last.pdf", format="pdf", bbox_inches="tight") print(f'Saving to {result_animation_filename}') ani = animation.FuncAnimation(self.fig, animate, frames=self.number_of_frames, interval=interval) ani.save(result_animation_filename + '.mp4', writer='ffmpeg', fps=10, dpi=100) if gif: ani.save(result_animation_filename + '.gif', writer='imagemagick', fps=10, dpi=100) def prepare_rgp_full_animation_figure(self): animation.writer = animation.writers['ffmpeg'] plt.ioff() # Turn off interactive mode to hide rendering animations # Color scheme convert from [0,255] to [0,1] self.cs = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] plt.style.use('fast') sns.set_style("whitegrid") gs = gridspec.GridSpec(1, 3) self.fig = plt.figure(figsize=(12,6), dpi=100) labels = ['x', 'y', 'z'] self.ax = [None]*3 self.scat_basis_vectors = [None]*3 self.scat_samples = [None]*3 self.rgp_mean_plot = [None]*3 self.fill_between_plots = [None]*3 for d in range(3): self.ax[d] = self.fig.add_subplot(gs[d]) self.scat_samples[d] = self.ax[d].scatter([], [], marker='.', color=self.cs[1], label='Samples') self.scat_basis_vectors[d] = self.ax[d].scatter([], [], marker='o', color=self.cs[2], label='Basis Vectors') self.rgp_mean_plot[d], = self.ax[d].plot([], [], '--', color=self.cs[0], label='E[g(x)]') self.fill_between_plots[d] = self.ax[d].fill_between([], [], [], color=self.cs[3], alpha=0.2, label="2std") self.ax[d].set_xlim(self.x_lim[d]) self.ax[d].set_ylim(self.y_lim[d]) self.ax[d].set_xlabel('Velocity [ms-1]') self.ax[d].set_ylabel('Drag acceleration [ms-2]') #self.ax[d].legend() self.ax[d].set_title(f'RGP basis vectors in {labels[d]}') plt.tight_layout(pad=20) self.fig.legend(labels=['Samples', 'Basis Vectors', 'E$[g(x)]$'], bbox_to_anchor=(0.5, 1), fancybox=True, shadow=True, ncol=5, loc='upper center', fontsize='large') def prepare_rgp_full_animation_data(self): print("Preparing data...") # Calculates how many datapoints to skip to get the desired number of frames skip = len(self.data_dict['x_odom'])//self.desired_number_of_frames self.X_basis = self.data_dict['rgp_basis_vectors'][::skip] self.mu_g_t = self.data_dict['rgp_mu_g_t'][::skip] self.C_g_t = self.data_dict['rgp_C_g_t'][::skip] self.theta = self.data_dict['rgp_theta'][::skip] self.X_sample = self.data_dict['v_body'][::skip] self.y_sample = self.data_dict['a_drag'][::skip] n_dims = 3 n_samples = len(self.X_basis) self.y_query = [None]*n_samples self.std_query = [None]*n_samples x_min = [100000]*n_dims x_max = [-100000]*n_dims for d in range(n_dims): for i in range(n_samples): x_min[d] = min(x_min[d], min(self.X_basis[i][d])) x_max[d] = max(x_max[d], max(self.X_basis[i][d])) self.X_query = [np.linspace(x_min[d], x_max[d], 100) for d in range(n_dims)] print("Predicting...") pbar = tqdm(total=n_samples) v_list = [(min(self.X_basis[i][d]), max(self.X_basis[i][d])) for d in range(len(self.X_basis[i]))] n_list = [len(self.X_basis[i][d]) for d in range(len(self.X_basis[i]))] self.rgpe = GPEnsemble.fromrange(v_list, n_list, self.theta[i][0]) self.y_query[0], self.std_query[0] = self.rgpe.predict(self.X_query, std=True) for i in range(1, n_samples): self.rgpe = GPEnsemble.frombasisvectors(self.X_basis[i], self.mu_g_t[i], self.C_g_t[i], self.theta[i]) self.y_query[i], self.std_query[i] = self.rgpe.predict(self.X_query, std=True) pbar.update(1) pbar.close() y_min = 100000 y_max = -100000 for d in range(n_dims): for i in range(n_samples): y_min = min(y_min, min(min(self.mu_g_t[i][d]), min(self.y_query[i][d]), min(self.y_sample[i][d]), -2*min(self.std_query[i][d]))) y_max = max(y_max, max(max(self.mu_g_t[i][d]), max(self.y_query[i][d]), max(self.y_sample[i][d]), 2*max(self.std_query[i][d]))) y_lim_dif = y_max-y_min self.x_lim = [(x_min[d], x_max[d]) for d in range(n_dims)] self.y_lim = [(y_min - np.sign(y_lim_dif)*y_lim_dif/10, y_max + np.sign(y_lim_dif)*y_lim_dif/10) for d in range(n_dims)] def create_rgp_before_after(self, result_filename, use_color_map=True): font = {'family' : 'normal', 'size' : 14} matplotlib.rc('font', **font) matplotlib.rcParams['pdf.fonttype'] = 42 self.prepare_rgp_before_after_data() self.prepare_rgp_before_after_figure() for d in range(3): self.scat_basis_vectors[d].set_offsets(np.array([self.X_basis[0][d], self.mu_g_t[0][d]]).T) self.rgp_mean_plot[d].set_data(self.X_query[d], self.y_query[0][d]) self.fill_between_plots[d].remove() self.fill_between_plots[d] = self.ax[d].fill_between(self.X_query[d].reshape(-1), self.y_query[0][d].reshape(-1) - 2*self.std_query[0][d], self.y_query[0][d].reshape(-1) + 2*self.std_query[0][d], color=self.cs[1], alpha=0.2) plt.savefig(result_filename + "_before.pdf", format="pdf", bbox_inches="tight") for d in range(3): self.scat_basis_vectors[d].set_offsets(np.array([self.X_basis[-1][d], self.mu_g_t[-1][d]]).T) self.rgp_mean_plot[d].set_data(self.X_query[d], self.y_query[-1][d]) self.fill_between_plots[d].remove() self.fill_between_plots[d] = self.ax[d].fill_between(self.X_query[d].reshape(-1), self.y_query[-1][d].reshape(-1) - 2*self.std_query[-1][d], self.y_query[-1][d].reshape(-1) + 2*self.std_query[-1][d], color=self.cs[1], alpha=0.2) X_sample_array = np.array([float(self.X_sample[j][d]) for j in range(len(self.X_sample))]).reshape(-1,1) y_sample_array = np.array([float(self.y_sample[j][d]) for j in range(len(self.y_sample))]).reshape(-1,1) self.scat_samples[d].set_offsets(np.concatenate((X_sample_array, y_sample_array), axis=1)) print(f'Saving to {result_filename + "_after.pdf"}') plt.savefig(result_filename + "_after.pdf", format="pdf", bbox_inches="tight") def prepare_rgp_before_after_figure(self): animation.writer = animation.writers['ffmpeg'] plt.ioff() # Turn off interactive mode to hide rendering animations # Color scheme convert from [0,255] to [0,1] self.cs = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] plt.style.use('fast') sns.set_style("whitegrid") gs = gridspec.GridSpec(1, 3) self.fig = plt.figure(figsize=(10,6), dpi=100) labels = ['x', 'y', 'z'] self.ax = [None]*3 self.scat_basis_vectors = [None]*3 self.scat_samples = [None]*3 self.rgp_mean_plot = [None]*3 self.fill_between_plots = [None]*3 for d in range(3): self.ax[d] = self.fig.add_subplot(gs[d]) self.scat_samples[d] = self.ax[d].scatter([], [], marker='.', s=4, color=self.cs[1], label='Samples') self.scat_basis_vectors[d] = self.ax[d].scatter([], [], marker='o', color=self.cs[2], label='Basis Vectors $X$') self.rgp_mean_plot[d], = self.ax[d].plot([], [], '--', color=self.cs[0], label='$\mathrm{E}[\mathrm{g}(x)]$') self.fill_between_plots[d] = self.ax[d].fill_between([], [], [], color=self.cs[3], alpha=0.2, label="$2 \mathrm{std}$") self.ax[d].set_xlim(self.x_lim[d]) self.ax[d].set_ylim(self.y_lim[d]) self.ax[d].set_xlabel('$v_{' + labels[d]+ '} [ms^{-1} ]$') self.ax[d].set_ylabel( '$\hat{a}_{' + labels[d] + '} [ms^{-2} ]$') #self.ax[d].legend() #self.ax[d].set_title(f'RGP basis vectors in {labels[d]}') plt.tight_layout(pad=4, w_pad=0.5) self.fig.legend(labels=['Samples', 'Basis Vectors', '$\mathrm{E}[\mathrm{g}(x)]$', '$2 \cdot$std'], bbox_to_anchor=(0.5, 1), fancybox=True, shadow=True, ncol=5, loc='upper center', fontsize='large') def prepare_rgp_before_after_data(self): print("Preparing data...") # Calculates how many datapoints to skip to get the desired number of frames last = len(self.data_dict['x_odom']) - 1 self.X_basis = self.data_dict['rgp_basis_vectors'][::last] self.mu_g_t = self.data_dict['rgp_mu_g_t'][::last] self.C_g_t = self.data_dict['rgp_C_g_t'][::last] self.theta = self.data_dict['rgp_theta'][::last] self.X_sample = self.data_dict['v_body'][:] self.y_sample = self.data_dict['a_drag'][:] n_dims = 3 n_samples = 2 self.y_query = [None]*n_samples self.std_query = [None]*n_samples x_min = [100000]*n_dims x_max = [-100000]*n_dims for d in range(n_dims): for i in range(n_samples): x_min[d] = min(x_min[d], min(self.X_basis[i][d])) x_max[d] = max(x_max[d], max(self.X_basis[i][d])) self.X_query = [np.linspace(x_min[d], x_max[d], 100) for d in range(n_dims)] print("Predicting...") pbar = tqdm(total=n_samples) v_list = [(min(self.X_basis[i][d]), max(self.X_basis[i][d])) for d in range(len(self.X_basis[i]))] n_list = [len(self.X_basis[i][d]) for d in range(len(self.X_basis[i]))] # Before self.rgpe = GPEnsemble.fromrange(v_list, n_list, self.theta[i][0]) self.y_query[0], self.std_query[0] = self.rgpe.predict(self.X_query, std=True) # After self.rgpe = GPEnsemble.frombasisvectors(self.X_basis[-1], self.mu_g_t[-1], self.C_g_t[-1], self.theta[-1]) self.y_query[-1], self.std_query[-1] = self.rgpe.predict(self.X_query, std=True) y_min = 100000 y_max = -100000 for d in range(n_dims): for i in range(n_samples): y_min = min(y_min, min(min(self.mu_g_t[i][d]), min(self.y_query[i][d]), min(self.y_sample[i][d]), -2*min(self.std_query[i][d]))) y_max = max(y_max, max(max(self.mu_g_t[i][d]), max(self.y_query[i][d]), max(self.y_sample[i][d]), 2*max(self.std_query[i][d]))) y_lim_dif = y_max-y_min self.x_lim = [(x_min[d], x_max[d]) for d in range(n_dims)] self.y_lim = [(y_min - np.sign(y_lim_dif)*y_lim_dif/10, y_max + np.sign(y_lim_dif)*y_lim_dif/10) for d in range(n_dims)] @staticmethod def rms(x, axis=0): return np.sqrt(np.mean(x**2, axis=axis)) def plot_data(self, filepath, show=True, save=True): x_world = np.stack(self.data_dict['x_odom'], axis=0) x_world_ref = np.stack(self.data_dict['x_ref'], axis=0) w = np.stack(self.data_dict['w_odom'], axis=0) t = np.stack(self.data_dict['t_odom'], axis=0) t_cpu = np.stack(self.data_dict['t_cpu'], axis=0) cost = np.stack(self.data_dict['cost_solution'], axis=0) v_norm = np.linalg.norm(x_world[:,7:10], axis=1) v_ref_norm = np.linalg.norm(x_world_ref[:,7:10], axis=1) e_pos_ref = x_world[:,0:3] - x_world_ref[:,0:3] #rms_pos_ref = np.sqrt(np.mean((e_pos_ref)**2, axis=1)) rms_pos_ref = self.rms(e_pos_ref, 1) e_quat_ref = x_world[:,3:7] - x_world_ref[:,3:7] #rms_quat_ref = np.sqrt(np.mean((e_quat_ref)**2, axis=1)) rms_quat_ref = self.rms(e_quat_ref, 1) e_vel_ref = x_world[:,7:10] - x_world_ref[:,7:10] #rms_vel_ref = np.sqrt(np.mean((e_vel_ref)**2, axis=1)) rms_vel_ref = self.rms(e_vel_ref, 1) e_rate_ref = x_world[:,10:13] - x_world_ref[:,10:13] #rms_rate_ref = np.sqrt(np.mean((e_rate_ref)**2, axis=1)) rms_rate_ref = self.rms(e_rate_ref, 1) rms_total_ref = np.sqrt(np.mean((x_world - x_world_ref)**2, axis=1)) data = {'v_x': x_world[:,7], 'v_y': x_world[:,8], 'v_z': x_world[:,9], 'v_norm': v_norm, \ 'e_x': e_pos_ref[:,0], 'e_y': e_pos_ref[:,1], 'e_z': e_pos_ref[:,2], 'rms_pos': rms_pos_ref } df = pd.DataFrame(data) # Color scheme convert from [0,255] to [0,1] self.cs_u = [[x/256 for x in (8, 65, 92)], \ [x/256 for x in (204, 41, 54)], \ [x/256 for x in (118, 148, 159)], \ [x/256 for x in (232, 197, 71)]] self.cs_rgb = [[x/256 for x in (205, 70, 49)], \ [x/256 for x in (105, 220, 158)], \ [x/256 for x in (102, 16, 242)], \ [x/256 for x in (7, 59, 58)]] plt.style.use('fast') sns.set_style("whitegrid") fig = plt.figure(figsize=(20, 10)) #gs = gridspec.GridSpec(3, 4, width_ratios=[1, 1, 1], height_ratios=[1, 1, 1, 1]) gs = gridspec.GridSpec(3, 4, width_ratios=[1, 1, 1, 1], height_ratios=[1, 1, 1]) ax = [None]*12 ax[0] = plt.subplot(gs[0, 0]) ax[1] = plt.subplot(gs[0, 1]) ax[2] = plt.subplot(gs[0, 2]) ax[3] = plt.subplot(gs[0, 3]) ax[4] = plt.subplot(gs[1, 0]) ax[5] = plt.subplot(gs[1, 1]) ax[6] = plt.subplot(gs[1, 2]) ax[7] = plt.subplot(gs[1, 3]) ax[8] = plt.subplot(gs[2, 0]) ax[9] = plt.subplot(gs[2, 1]) ax[10] = plt.subplot(gs[2, 2]) ax[11] = plt.subplot(gs[2, 3]) ax[0].plot(t, x_world[:,0], label='x', color=self.cs_rgb[0]) ax[0].plot(t, x_world[:,1], label='y', color=self.cs_rgb[1]) ax[0].plot(t, x_world[:,2], label='z', color=self.cs_rgb[2]) ax[0].plot(t, x_world_ref[:,0], label='x_ref', color=self.cs_rgb[0], linestyle='dashed') ax[0].plot(t, x_world_ref[:,1], label='y_ref', color=self.cs_rgb[1], linestyle='dashed') ax[0].plot(t, x_world_ref[:,2], label='z_ref', color=self.cs_rgb[2], linestyle='dashed') ax[0].set_xlabel('Time [s]') ax[0].set_ylabel('Position [m]') ax[0].set_title('Position') ax[1].plot(t, x_world[:,3], label='qw', color=self.cs_rgb[0]) ax[1].plot(t, x_world[:,4], label='qx', color=self.cs_rgb[1]) ax[1].plot(t, x_world[:,5], label='qy', color=self.cs_rgb[2]) ax[1].plot(t, x_world[:,6], label='qz', color=self.cs_rgb[3]) ax[1].plot(t, x_world_ref[:,3], label='qw_ref', color=self.cs_rgb[0], linestyle='dashed') ax[1].plot(t, x_world_ref[:,4], label='qx_ref', color=self.cs_rgb[1], linestyle='dashed') ax[1].plot(t, x_world_ref[:,5], label='qy_ref', color=self.cs_rgb[2], linestyle='dashed') ax[1].plot(t, x_world_ref[:,6], label='qz_ref', color=self.cs_rgb[3], linestyle='dashed') ax[1].set_xlabel('Time [s]') ax[1].set_ylabel('Quaternion') ax[1].set_title('Orientation') ax[2].plot(t, x_world[:,7], label='vx', color=self.cs_rgb[0]) ax[2].plot(t, x_world[:,8], label='vy', color=self.cs_rgb[1]) ax[2].plot(t, x_world[:,9], label='vz', color=self.cs_rgb[2]) ax[2].plot(t, x_world_ref[:,7], label='vx_ref', color=self.cs_rgb[0], linestyle='dashed') ax[2].plot(t, x_world_ref[:,8], label='vy_ref', color=self.cs_rgb[1], linestyle='dashed') ax[2].plot(t, x_world_ref[:,9], label='vz_ref', color=self.cs_rgb[2], linestyle='dashed') ax[2].plot(t, v_norm, label='v_norm', color=self.cs_rgb[3]) ax[2].plot(t, v_ref_norm, label='v_ref_norm', color=self.cs_rgb[3], linestyle='dashed') ax[2].set_title('Velocity') ax[2].set_xlabel('Time [s]') ax[2].set_ylabel('Velocity [m/s]') ax[3].plot(t, x_world[:,10], label='wx', color=self.cs_rgb[0]) ax[3].plot(t, x_world[:,11], label='wy', color=self.cs_rgb[1]) ax[3].plot(t, x_world[:,12], label='wz', color=self.cs_rgb[2]) ax[3].plot(t, x_world_ref[:,10], label='wx_ref', color=self.cs_rgb[0], linestyle='dashed') ax[3].plot(t, x_world_ref[:,11], label='wy_ref', color=self.cs_rgb[1], linestyle='dashed') ax[3].plot(t, x_world_ref[:,12], label='wz_ref', color=self.cs_rgb[2], linestyle='dashed') ax[3].set_title('Angular Velocity') ax[3].set_xlabel('Time [s]') ax[3].set_ylabel('Angular Velocity [rad/s]') ax[4].plot(t, e_pos_ref[:,0], label='e_x', color=self.cs_rgb[0]) ax[4].plot(t, e_pos_ref[:,1], label='e_y', color=self.cs_rgb[1]) ax[4].plot(t, e_pos_ref[:,2], label='e_z', color=self.cs_rgb[2]) ax[4].plot(t, rms_pos_ref, label="rms", color=self.cs_rgb[3]) ax[4].set_title(f"RMS Position Error, Total: {self.rms(rms_pos_ref, 0)*1e3:.2f}mm") ax[4].set_xlabel('Time [s]') ax[4].set_ylabel('RMS Position Error [m]') ax[4].legend() ax[5].plot(t, rms_quat_ref, label='rms', color=self.cs_rgb[0]) ax[5].set_title(f'RMS Quaternion Error') ax[5].set_xlabel('Time [s]') ax[5].set_ylabel('RMS Quaternion Error [m/s]') ax[6].plot(t, e_vel_ref[:,0], label='e_vx', color=self.cs_rgb[0]) ax[6].plot(t, e_vel_ref[:,1], label='e_vy', color=self.cs_rgb[1]) ax[6].plot(t, e_vel_ref[:,2], label='e_vz', color=self.cs_rgb[2]) ax[6].plot(t, rms_vel_ref, label='rms', color=self.cs_rgb[3]) ax[6].set_title(f'RMS Velocity Error, Total: {self.rms(rms_vel_ref, 0)*1000:.2f}mm/s') ax[6].set_xlabel('Time [s]') ax[6].set_ylabel('RMS Velocity Error [m/s]') ax[6].legend() cov = df.cov() matrix = np.triu(cov).T #breakpoint() #features1=list(['cat1','cat2','cat3']) #features2=list(['Cat1', 'Cat2','num1','num2']) #cov = df.loc[['v_x', 'v_y', 'v_z', 'v_norm']].cov(df.loc[['e_x', 'e_y', 'e_z', 'rms_pos']]) #cov = df['v_x', 'v_y', 'v_z', 'v_norm'].cov(df['e_x', 'e_y', 'e_z', 'rms_pos']) sns.heatmap(cov, xticklabels=cov.columns, yticklabels=cov.columns, ax=ax[7], mask=matrix) ax[7].set_title(f'Covariance Matrix') ''' ax[7].plot(t, e_rate_ref[:,0], label='e_vx', color=self.cs_rgb[0]) ax[7].plot(t, e_rate_ref[:,1], label='e_vy', color=self.cs_rgb[1]) ax[7].plot(t, e_rate_ref[:,2], label='e_vz', color=self.cs_rgb[2]) ax[7].plot(t, rms_rate_ref, label='rms', color=self.cs_rgb[3]) ax[7].set_title(f'RMS Angular Velocity Error') ax[7].set_xlabel('Time [s]') ax[7].set_ylabel('RMS Angular Velocity Error [rad/s]') ax[7].legend() ''' ax[8].scatter(x_world[:,7], e_pos_ref[:,0], s=4, label='e_vx', color=self.cs_rgb[0]) ax[8].scatter(x_world[:,8], e_pos_ref[:,1], s=4, label='e_vy', color=self.cs_rgb[1]) ax[8].scatter(x_world[:,9], e_pos_ref[:,2], s=4, label='e_vz', color=self.cs_rgb[2]) ax[8].scatter(v_norm, rms_pos_ref, s=4, label='rms', color=self.cs_rgb[3]) ax[8].set_xlabel('Velocity [m/s]') ax[8].set_ylabel('Position Error [m]') ax[8].set_title('Position error as a function of velocity') ax[8].legend((f'x: {cov["v_x"]["e_x"]:2f}', f'y: {cov["v_y"]["e_y"]:2f}', f'z: {cov["v_z"]["e_z"]:2f}')) ax[9].plot(t, w[:,0], label='u1', color=self.cs_u[0]) ax[9].plot(t, w[:,1], label='u2', color=self.cs_u[1]) ax[9].plot(t, w[:,2], label='u3', color=self.cs_u[2]) ax[9].plot(t, w[:,3], label='u4', color=self.cs_u[3]) ax[9].set_xlabel('Time [s]') ax[9].set_ylabel('Control Input') ax[9].set_title('Control Input') avg_cpu = np.mean(t_cpu) std_cpu = np.std(t_cpu) ax[10].plot(t, t_cpu[:]*1e3, label='t_cpu', color=self.cs_rgb[0]) ax[10].plot(t, np.ones_like(t)*avg_cpu*1e3, label='avg_cpu', color=self.cs_rgb[1]) ax[10].set_xlabel('Time [s]') ax[10].set_ylabel('CPU Time [ms]') ax[10].set_title(f'MPC CPU Time, Avg: {avg_cpu*1e3:.2f}ms, STD: {std_cpu*1e3:.2f}') ax[11].plot(t, cost[:], label='solution_cost', color=self.cs_rgb[0]) ax[11].set_xlabel('Time [s]') ax[11].set_ylabel('Solution Cost') ax[11].set_title('Solution Cost') plt.tight_layout() if save: print(f"Saving plot to {filepath}") plt.savefig(filepath, format="pdf", bbox_inches="tight") # Show needs to come after savefig because it clears the figure if show: plt.show() if __name__ == '__main__': dir_path = os.path.dirname(os.path.realpath(__file__)) simulation = 'gazebo_simulation' simulation = 'python_simulation' trajectory_filename = os.path.join(dir_path, '..', 'outputs', simulation, 'data', 'simulated_trajectory.pkl') result_animation_filename = os.path.join(dir_path, '..', 'outputs', simulation, 'animations', 'my_animation.mp4') result_plot_filename = os.path.join(dir_path, '..', 'outputs', simulation, 'img', 'trajectory.pdf') visualiser = Visualiser(trajectory_filename) visualiser.create_animation(result_animation_filename, 100, True) #visualiser.plot_data(result_plot_filename)
import { LightModeOutlined, DarkModeOutlined, Menu as MenuIcon, Search, SettingsOutlined, } from "@mui/icons-material"; import FlexBetween from "../FlexBetween"; import { AppBar, IconButton, InputBase, Toolbar, useTheme, } from "@mui/material"; import { useProSidebar } from "react-pro-sidebar"; import { useDispatch } from "react-redux"; import { setTheme } from "../../features/global/globalSlice"; import Profile from "./userProfile/Profile"; import Messages from "./messages/Messages"; import Notifications from "./notifications/Notifications"; const Navbar = () => { const dispatch = useDispatch(); const theme = useTheme(); const { collapseSidebar, toggleSidebar } = useProSidebar(); return ( <AppBar sx={{ background: theme.palette.bgColor.main, boxShadow: "none", }} position="sticky" > <Toolbar sx={{ justifyContent: "space-between" }}> {/* LEFT SIDE */} <FlexBetween> {/* Side bar collapse sidebar button */} <IconButton sx={{ mr: "10px", display: { xs: "none", md: "flex" } }} onClick={() => { collapseSidebar(); }} > <MenuIcon sx={{ fontSize: "25px", color: theme.palette.primary.main }} /> </IconButton> {/* Toggle sidebar button */} <IconButton sx={{ mr: "10px", display: { md: "none" } }} onClick={() => { collapseSidebar(true); toggleSidebar(); }} > <MenuIcon sx={{ fontSize: "25px", color: theme.palette.primary.main }} /> </IconButton> {/* Search input */} <FlexBetween backgroundColor={theme.palette.light.main} borderRadius="9px" gap="3rem" p="0.1rem 1.5rem" sx={{ display: { xs: "none", sm: "flex", }, }} > <InputBase placeholder="Search..." /> <IconButton> <Search /> </IconButton> </FlexBetween> </FlexBetween> {/* RIGHT SIDE */} <FlexBetween gap="1.5rem"> <IconButton onClick={() => dispatch(setTheme())}> {theme.palette.mode === "dark" ? ( <DarkModeOutlined sx={{ fontSize: "25px", color: theme.palette.primary.main }} /> ) : ( <LightModeOutlined sx={{ fontSize: "25px", color: theme.palette.primary.main }} /> )} </IconButton> <IconButton sx={{ display: { xs: "none", sm: "flex", }, }} > <SettingsOutlined sx={{ fontSize: "25px", color: theme.palette.primary.main, }} /> </IconButton> <Notifications /> <Messages /> <Profile /> </FlexBetween> </Toolbar> </AppBar> ); }; export default Navbar;
import React from "react"; import PropTypes from "prop-types"; import classnames from "classnames"; const styles = {}; const Tooltip = ({ children, className, boxClassName, content, placement }) => { const [side, position] = placement.split("-"); return ( <div className={classnames(styles.tooltip, className)}> {children} <div className={classnames( boxClassName, styles.tooltipBox, styles[side], styles[position] )} > {content} </div> </div> ); }; Tooltip.defaultProps = { className: null, boxClassName: null, placement: "bottom" }; Tooltip.propTypes = { className: PropTypes.string, boxClassName: PropTypes.string, content: PropTypes.node.isRequired, placement: PropTypes.oneOf([ "bottom-end", "bottom-start", "bottom", "left-end", "left-start", "left", "right-end", "right-start", "right", "top-end", "top-start", "top" ]) }; export default Tooltip;
"use client"; import React, { useState, useEffect } from 'react'; import axios from 'axios'; interface User { id: number; name: string; email: string; } interface UpdateUserProps { refreshUsers: () => void; } export default function UpdateUser({ refreshUsers }: UpdateUserProps) { const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000'; const [users, setUsers] = useState<User[]>([]); const [updateUser, setUpdateUser] = useState({ id: '', name: '', email: '' }); useEffect(() => { const fetchData = async () => { try { const response = await axios.get(`${apiUrl}/users`); setUsers(response.data.reverse()); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); const handleUpdateUser = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); try { await axios.put(`${apiUrl}/users/${updateUser.id}`, { name: updateUser.name, email: updateUser.email }); setUpdateUser({ id: '', name: '', email: '' }); setUsers( users.map((user) => { if (user.id === parseInt(updateUser.id)) { return { ...user, name: updateUser.name, email: updateUser.email }; } return user; }) ); } catch (error) { console.error('Error updating user:', error); } await refreshUsers(); }; return ( <div className="mt-4 bg-white/30 p-12 shadow-xl ring-1 ring-gray-900/5 rounded-lg backdrop-blur-lg max-w-xl mx-auto w-full"> <div className="flex justify-between items-center mb-4"> <div className="space-y-1"> <h2 className="text-xl font-semibold text-gray-100">Update user</h2> </div> </div> <div className="divide-y divide-gray-900/5"> <form onSubmit={handleUpdateUser} className='text-sm'> <input placeholder="User ID" value={updateUser.id} onChange={(e) => setUpdateUser({ ...updateUser, id: e.target.value })} className="mb-2 w-full p-2 border rounded" /> <input placeholder="New Name" value={updateUser.name} onChange={(e) => setUpdateUser({ ...updateUser, name: e.target.value })} className="mb-2 w-full p-2 border rounded" /> <input placeholder="New Email" value={updateUser.email} onChange={(e) => setUpdateUser({ ...updateUser, email: e.target.value })} className="mb-2 w-full p-2 border rounded" /> <button type="submit" className="mt-4 w-full p-2 text-white tracking-tight font-semibold bg-blue-600 rounded-md hover:bg-blue-500"> Update User </button> </form> </div> </div> ); };
import numpy as np from mpl_toolkits.mplot3d.art3d import Poly3DCollection class ProjectionObject: def __init__(self, coordinate=[0, 0, 0], size=1): self.vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]) * size + np.array(coordinate) self.faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [2, 3, 7, 6], [1, 2, 6, 5], [0, 3, 7, 4]] def get_center(self): min_coords = np.min(self.vertices, axis=0) max_coords = np.max(self.vertices, axis=0) center = (min_coords + max_coords) / 2 return center def translate_object(self, translation_vector): self.vertices += translation_vector def scale_object(self, scale_factor): center = self.get_center() self.vertices = center + scale_factor * (self.vertices - center) def get_projection_vertices_with_vector(self, direction_vectors_normalized:np.ndarray): # Find the intersection points of direction vectors and the XY plane vector_scale_value = -self.vertices[:, 2] / direction_vectors_normalized[:, 2] projection_vertices = self.vertices + vector_scale_value[:, np.newaxis] * direction_vectors_normalized return projection_vertices def plot_object(self, ax): cube = Poly3DCollection([self.vertices[face] for face in self.faces], alpha=0.25, edgecolor='black', label='Original object') ax.add_collection3d(cube) ax.scatter3D(*self.vertices.T, color='red') def plot_projection(self, ax, projection_vertices): polygon = Poly3DCollection([projection_vertices[face] for face in self.faces], alpha=0.5, edgecolor='black', label='Projection') ax.add_collection3d(polygon) def plot_light_source(self, ax, light): ax.scatter(*light, color='g', label='Light source') def get_projection_vertices(self, light=[0, 0, 8], projection_choice='parallel', translation_vector=None, scale_factor=None): self.light = np.array(light) if scale_factor is not None: self.scale_object(scale_factor) if translation_vector is not None: self.translate_object(translation_vector) projection_vertices = None if projection_choice == 'orthographic': projection_vertices = self.vertices.copy() projection_vertices[:,2] = 0 elif projection_choice == 'oblique': direction_vectors = self.get_center() - self.light direction_vectors_normalized = direction_vectors / np.linalg.norm(direction_vectors, keepdims=True) direction_vectors_normalized = np.tile(direction_vectors_normalized, (self.vertices.shape[0], 1)) projection_vertices = self.get_projection_vertices_with_vector(direction_vectors_normalized) elif projection_choice == 'perspective': direction_vectors = self.vertices - self.light direction_vectors_normalized = direction_vectors / np.linalg.norm(direction_vectors, axis=1, keepdims=True) projection_vertices = self.get_projection_vertices_with_vector(direction_vectors_normalized) return projection_vertices if __name__ == "__main__": cube = ProjectionObject(coordinate=[1, 1, 1], size=2) projection_vertices = cube.get_projection_vertices(projection_choice='orthographic')
package mail import ( "fmt" "testing" "time" "github.com/spf13/viper" ) func TestSendEmailWithAttachment_with_body(t *testing.T) { smtpHost, smtpPort, smtpUsername, smtpPassword, emailFrom, emailTo := getSmtpConfigFromEnv(t) fileName := fmt.Sprintf("hello-%d.txt", time.Now().Unix()) fileData := []byte(fmt.Sprintf("Hello World! %d\n", time.Now().Unix())) err := SendEmailWithAttachment( smtpHost, smtpPort, smtpUsername, smtpPassword, emailFrom, emailTo, "go test: TestSendEmailWithAttachment_with_body", "text body\nO.\n\n", fileName, fileData, ) if err != nil { t.Errorf("error: %v", err) } } func TestSendEmailWithAttachment_without_body(t *testing.T) { smtpHost, smtpPort, smtpUsername, smtpPassword, emailFrom, emailTo := getSmtpConfigFromEnv(t) fileName := fmt.Sprintf("hello-%d.txt", time.Now().Unix()) fileData := []byte(fmt.Sprintf("Hello World! %d\n", time.Now().Unix())) err := SendEmailWithAttachment( smtpHost, smtpPort, smtpUsername, smtpPassword, emailFrom, emailTo, "go test: TestSendEmailWithAttachment_without_body", "", fileName, fileData, ) if err != nil { t.Errorf("error: %v", err) } } func getSmtpConfigFromEnv(t *testing.T) (string, int, string, string, string, string) { viper.SetConfigFile(".env") if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); !ok { t.Fatalf("Error reading .env file: %v\n", err) } } viper.AutomaticEnv() viper.BindEnv("SMTP_HOST") viper.BindEnv("SMTP_PORT") viper.BindEnv("SMTP_USERNAME") viper.BindEnv("SMTP_PASSWORD") smtpHost := viper.GetString("SMTP_HOST") if smtpHost == "" { t.Fatal("SMTP_HOST not set") } smtpPort := viper.GetInt("SMTP_PORT") if smtpPort == 0 { t.Fatal("SMTP_PORT not set") } smtpUsername := viper.GetString("SMTP_USERNAME") if smtpUsername == "" { t.Fatal("SMTP_USERNAME not set") } smtpPassword := viper.GetString("SMTP_PASSWORD") if smtpPassword == "" { t.Fatal("SMTP_PASSWORD not set") } emailFrom := viper.GetString("EMAIL_FROM") if emailFrom == "" { t.Fatal("EMAIL_FROM not set") } emailTo := viper.GetString("EMAIL_TO") if emailTo == "" { t.Fatal("EMAIL_TO not set") } return smtpHost, smtpPort, smtpUsername, smtpPassword, emailFrom, emailTo }
# DotJoshJohnson.Pipelines A simple utility library for building and invoking pipelines similar to the ASP.NET Core middleware pipeline. ## Getting Started ### Quick and Dirty 1. Install `DotJoshJohnson.Pipelines` via NuGet. 2. Build a pipeline. ```csharp using DotJoshJohnson.Pipelines; // ... // var pipeline = new PipelineBuilder<PipelineContext>() .Use(async (context, cancellationToken, next) => { // TODO: do work await next(context, cancellationToken); }) .Use(async (context, cancellationToken, next) => { // TODO: do more work await next(context, cancellationToken); }) .Build(); ``` 4. Invoke your pipeline! ```csharp // continued from step 2 // var context = new PipelineContext(); await pipeline.Invoke(context); ``` ### Using Pipeline Components Instead of adding delegates directly to your pipeline, you can add components, which are classes that implement `IPipelineComponent<TContext>`. ```csharp using DotJoshJohnson.Pipelines; using DotJoshJohnson.Pipelines.Components; // ... // public class MyCustomComponent : IPipelineComponent<PipelineContext> { public async Task Invoke(PipelineContext context, PipelineInvocationDelegate<PipelineContext> next, CancellationToken cancellationToken) { // TODO: do work here await next(context, cancellationToken); // TODO: maybe do work here as well } } // ... // var pipeline = new PipelineBuilder<PipelineContext>() .Use<MyCustomComponent>() .Build(); ``` When it comes time to invoke your component, it will be "activated", which just means an instance of that class will be requested by the pipeline. The default activator just uses `Activator.CreateInstance<TComponent>()` to get a new instance of your component. You can implement your own activator (`IPipelineComponentActivator`) if you'd like or use an extension such as `DotJoshJohnson.Pipelines.MicrosoftDependencyInjection` that provides one for you. If you're writing your own activator, be sure to tell the builder about it by calling `WithActivator()` on your pipeline builder. Note that this method must be called before any components are added ot the pipeline. ### Custom Pipeline Context The `PipelineContext` object you've seen thus far is simply included for convenience. You can use it as-is, extend it via inheritance, or use a totally different class. There is no requirement to use or extend `PipelineContext`. ### Dependency Injection If you are using `Microsoft.Extensions.DependencyInjection`, I recommend pulling in `DotJoshJohnson.Pipelines.MicrosoftDependencyInjection`. This package provides two extensions to `IServiceCollection`. **Note that if you are using pipeline components, you must register each component with the DI container.** **Using AddPipeline** ```csharp using DotJoshJohnson.Pipelines; using Microsoft.Extensions.DependencyInjection; // ... // var services = new ServiceCollection(); // DON'T FORGET THIS STEP services.AddTransient<MyCustomComponent>(); services.AddPipeline<PipelineContext>(p => { p.Use(async (context, cancellationToken, next) => { // TODO: do work! await next(context, cancellationToken); }); p.Use<MyCustomComponent>(); }); var serviceProvider = services.BuildServiceProvider(); var pipeline = serviceProvider.GetRequiredService<IPipeline<PipelineContext>>(); await pipeline.Invoke(new()); ``` **Using AddNamedPipeline** ```csharp using DotJoshJohnson.Pipelines; using Microsoft.Extensions.DependencyInjection; // ... // var services = new ServiceCollection(); // DON'T FORGET THIS STEP services.AddTransient<MyCustomComponent>(); services.AddNamedPipeline<PipelineContext>("MyPipeline", p => { p.Use(async (context, cancellationToken, next) => { // TODO: do work! await next(context, cancellationToken); }); p.Use<MyCustomComponent>(); }); var serviceProvider = services.BuildServiceProvider(); var pipeline = serviceProvider.GetRequiredService<INamedPipeline>().Get<PipelineContext>("MyPipeline"); await pipeline.Invoke(new()); ``` **Using AddEventHandler** The `AddEventHandler` method can be used to add code that runs at specific points in the pipeline invocation chain. Specifically, you can run code before a comopnent is invoked, after a component succeeds, fails, or after component invocation (regardless of result). This allows you to add repetitive tasks such as logging in one place instead of duplicating the logic across multiple components. ```csharp ```
from abc import ABC, abstractmethod from datetime import datetime class Transaction(ABC): @abstractmethod def create_account(self, account): pass class Deposit(Transaction): def __init__(self, amount): self.amount = amount self.timestamp = datetime.now() def create_account(self, account): account.deposit(self.amount) account.add_transaction(self) def __str__(self): return f"{self.timestamp.strftime('%Y-%m-%d %H:%M:%S')} - Deposited R$ {self.amount}" class Withdrawal(Transaction): def __init__(self, amount): self.amount = amount self.timestamp = datetime.now() def create_account(self, account): account.withdraw(self.amount) account.add_transaction(self) def __str__(self): return f"{self.timestamp.strftime('%Y-%m-%d %H:%M:%S')} - Withdrew R$ {self.amount}" class Client: def __init__(self, address): self.address = address self.accounts = [] def do_transaction(self, account, transaction): transaction.create_account(account) def add_account(self, account): self.accounts.append(account) def list_accounts(self): return self.accounts class PhysicalPerson(Client): def __init__(self, cpf, name, birthdate, address): super().__init__(address) self.cpf = cpf self.name = name self.birthdate = birthdate def __str__(self): return f"Name: {self.name}, CPF: {self.cpf}, Address: {self.address}" class Account: def __init__(self, number, client, agency="0001"): self.balance = 0 self.number = number self.agency = agency self.client = client self.__history = [] def balance(self): return self.balance def new_account(self, client, number): return Account(number, client) def withdraw(self, amount): if self.balance >= amount: self.balance -= amount return True else: print("Insufficient funds.") return False def deposit(self, amount): self.balance += amount return True def add_transaction(self, transaction): self.__history.append(transaction) def get_history(self): return self.__history class CurrentAccount(Account): def __init__(self, number, client, withdraw_limit, withdrawals_limit): super().__init__(number, client) self.withdraw_limit = withdraw_limit self.withdrawals_limit = withdrawals_limit def display_menu(): print("\n1. Create User") print("2. Create Account") print("3. Deposit") print("4. Withdraw") print("5. Statements") print("6. List Users") print("7. Exit") def main(): users = [] while True: display_menu() option = input("Choose an option: ") if option == "1": name = input("Enter user's name: ") cpf = input("Enter user's CPF: ") birth_date = input("Enter user's birth date (YYYY-MM-DD): ") address = input("Enter user's address: ") user = PhysicalPerson(cpf, name, birth_date, address) users.append(user) print("User created successfully.") elif option == "2": cpf = input("Enter user's CPF: ") found_user = None for user in users: if user.cpf == cpf: found_user = user break if found_user: number = input("Enter account's number: ") account = Account(number, found_user) found_user.add_account(account) print("Account created successfully.") else: print("User not found.") elif option == "3": cpf = input("Enter user's CPF: ") account_number = input("Enter account number: ") amount = float(input("Enter the amount to deposit: ")) found_user = None for user in users: if user.cpf == cpf: for account in user.accounts: if account.number == account_number: transaction = Deposit(amount) user.do_transaction(account, transaction) print("Deposit successful.") break break elif option == "4": cpf = input("Enter user's CPF: ") account_number = input("Enter account number: ") amount = float(input("Enter the amount to withdraw: ")) found_user = None for user in users: if user.cpf == cpf: for account in user.accounts: if account.number == account_number: if account.withdraw(amount): transaction = Withdrawal(amount) user.do_transaction(account, transaction) print("Withdrawal successful.") break break elif option == "5": cpf = input("Enter user's CPF: ") account_number = input("Enter account number: ") found_user = None for user in users: if user.cpf == cpf: for account in user.accounts: if account.number == account_number: print(f"Account balance: {account.balance}") print("Transaction history:") for transaction in account.get_history(): print(transaction) break break elif option == "6": print("\nUsers:") for user in users: print(user) elif option == "7": print("Exiting the system...") break else: print("Invalid option. Please try again.") if __name__ == "__main__": main()
import { ApiProperty } from '@nestjs/swagger'; import { Type, } from 'class-transformer'; import { IsNotEmpty, Length, IsEmail, IsOptional, ValidateNested, Matches, } from 'class-validator'; import { CreateAddressDto } from 'src/addresses/dto/create-address.dto'; import { passwordRegex } from 'src/common/constants'; export class RegisterUserDTO { @ApiProperty() @IsNotEmpty() @Length(3, 64) firstName: string; @ApiProperty() @IsNotEmpty() @Length(3, 64) lastName: string; @ApiProperty() @IsNotEmpty() @Length(3, 64) username: string; @ApiProperty({ type: String, description: `${passwordRegex}`, }) // @Matches(passwordRegex, { message: 'Weak password' }) @IsNotEmpty() @Length(6, 32) password: string; @ApiProperty() @IsNotEmpty() @IsEmail() email: string; @ApiProperty() @IsNotEmpty() @Length(6, 32) phoneNumber: string; @ApiProperty() @IsOptional() @Length(4, 32) referralCode: string; @ApiProperty({ required: false }) @IsOptional() photo?: any; @ApiProperty({ type: CreateAddressDto, isArray: true }) @ValidateNested({ each: true }) @Type(() => CreateAddressDto) addresses: CreateAddressDto[]; }
/* Copyright 2008-2016 INSA Lyon, CoReNum, ENS-Lyon * * This file is part of libcrn. * * libcrn 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 3 of the License, or * (at your option) any later version. * * libcrn 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 libcrn. If not, see <http://www.gnu.org/licenses/>. * * file: CRNDiscreteHMM.cpp * \author Jean DUONG, Yann LEYDIER */ #include <CRNi18n.h> #include <stdio.h> #include <CRNException.h> #include <CRNMath/CRNMatrixDouble.h> #include <CRNMath/CRNSquareMatrixDouble.h> #include <CRNAI/CRNDiscreteHMM.h> #include <CRNProtocols.h> using namespace crn; DiscreteHMM::DiscreteHMM(DiscreteHMM&&) noexcept = default; DiscreteHMM& DiscreteHMM::operator=(DiscreteHMM&&) noexcept = default; /*! * Copy constructor * * \param[in] h another HMM */ DiscreteHMM::DiscreteHMM(const DiscreteHMM &h) { nbStates = h.GetNbStates(); nbSymbols = h.GetNbSymbols(); stateTransitionProbability = CloneAs<SquareMatrixDouble>(*h.GetStateTransitionProbability()); stateGivenSymbolProbability = CloneAs<MatrixDouble>(*h.GetStateGivenSymbolProbability()); firstStateProbability = CloneAs<MatrixDouble>(*h.GetFirstStateProbability()); } /*! * Constructor * * \param[in] nstates number of states for HMM * \param[in] nsymbs number of symbols for HMM */ DiscreteHMM::DiscreteHMM(int nstates, int nsymbs): nbStates(nstates), nbSymbols(nsymbs) { double InvNbStates = 1.0 / double(nbStates); double InvNbSymbols = 1.0 / double(nbSymbols); stateTransitionProbability = std::make_shared<SquareMatrixDouble>(nbStates, InvNbStates); stateGivenSymbolProbability = std::make_shared<MatrixDouble>(nbStates, nbSymbols, InvNbSymbols); firstStateProbability = std::make_shared<MatrixDouble>(nbSymbols, 1, InvNbSymbols); } /*! * Destructor */ DiscreteHMM::~DiscreteHMM() { } /*! * Set the state transition probability matrix. A copy of the matrix is made. * * \param[in] a the new state transition probability matrix */ void DiscreteHMM::SetStateTransitionProbability(const SquareMatrixDouble& a) { stateTransitionProbability = CloneAs<SquareMatrixDouble>(a); nbStates = a.GetRows(); } /*! * Set the state given symbol probability matrix. A copy of the matrix is made. * * \param[in] b the new state given symbol probability matrix */ void DiscreteHMM::SetStateGivenSymbolProbability(const MatrixDouble& b) { stateGivenSymbolProbability = CloneAs<MatrixDouble>(b); nbStates = b.GetRows(); nbSymbols = b.GetCols(); } /*! * Set the first state probability matrix. A copy of the matrix is made. * * \param[in] p the new first state probability matrix */ void DiscreteHMM::SetFirstStateProbability(const MatrixDouble& p) { firstStateProbability = CloneAs<MatrixDouble>(p); nbStates = p.GetRows(); } /*! * Check if model is valid * * \return true if the model is valid, false else */ bool DiscreteHMM::IsValid() const { bool status = false; if (stateTransitionProbability && stateGivenSymbolProbability && firstStateProbability) { if ((stateTransitionProbability->GetRows() == nbStates) && (stateTransitionProbability->GetCols() == nbStates) && (stateGivenSymbolProbability->GetRows() == nbStates) && (stateGivenSymbolProbability->GetCols() == nbSymbols) && (firstStateProbability->GetRows() == nbSymbols) && (firstStateProbability->GetCols() == 1)) { status = true; } } return status; } /*! * Check if two models are equal * * \param[in] other the other HMM * * \return true if models are equal, false else */ bool DiscreteHMM::operator==(const DiscreteHMM &other) const { return (*other.GetStateTransitionProbability() == *stateTransitionProbability) && (*other.GetStateGivenSymbolProbability() == *stateGivenSymbolProbability) && (*other.GetFirstStateProbability() == *firstStateProbability); } /*! * Forward function in Viterbi approximation * * \param[in] observed the observed sequence * * \return the forward probability matrix */ UMatrixDouble DiscreteHMM::alpha(const MatrixInt& observed) const { size_t i, j, t; size_t N = nbStates; size_t T = observed.GetCols(); UMatrixDouble FWD = std::make_unique<MatrixDouble>(T, N, 0.0); // Just some convenient short variable names to fit literature and make it easier to handle ! =) SSquareMatrixDouble A = stateTransitionProbability; SMatrixDouble B = stateGivenSymbolProbability; SMatrixDouble P = firstStateProbability; // First alpha for each state. for (i = 0; i < N; i++) { FWD->At(0, i) = P->At(i, 0) * B->At(i, observed.At(0, 0)); } // Iteration. for (t = 0; t < T - 1; t++) { for (j = 0; j < N; j++) { double Sum = 0.0; for (i = 0; i < N; i++) { Sum += FWD->At(t, i) * A->At(i, j); } FWD->At(t + 1, j) = Sum * B->At(j, observed.At(t + 1, 0)); } } return std::forward<UMatrixDouble>(FWD); } /*! * Backward function in Viterbi approximation * * \param[in] observed the observed sequence * * \return the backward probability matrix */ UMatrixDouble DiscreteHMM::beta(const MatrixInt& observed) const { size_t i,j; size_t N = nbStates; size_t T = observed.GetCols(); UMatrixDouble BKD = std::make_unique<MatrixDouble>(T, N, 0.0); SSquareMatrixDouble A = stateTransitionProbability; SMatrixDouble B = stateGivenSymbolProbability; // Last beta for each state. for (i = 0; i < N; i++) { BKD->At(T - 1, i) = 1.0; } // Iteration. for (int t = int(T) - 2; t >= 0; t--) { for (i = 0; i < N; i++) { double Sum = 0.0; for (j = 0; j < N; j++) { Sum += A->At(i, j) * B->At(j, observed.At(t+1, 0)) * BKD->At(t + 1, j); } BKD->At(t, i) = Sum; } } return std::forward<UMatrixDouble>(BKD); } /*! * Probability estimation for a given observation sequence * * \param[in] observed the observed sequence * * \return the a priori probability of the observed sequence */ double DiscreteHMM::SequenceProbability(const MatrixInt& observed) const { size_t k; size_t N = nbStates; size_t T = observed.GetCols(); SMatrixDouble Alpha = alpha(observed); double P = 0.0; for (k = 0; k < N; k++) { P += Alpha->At(T - 1, k); } return P; } /*! * Viterbi procedure to estimate the best state chain given an observation chain * * \param[in] observed the observed sequence * * \return the most likely state sequence corresponding to the observed sequence */ UMatrixInt DiscreteHMM::MakeViterbi(const MatrixInt& observed) const { size_t i, j, k; size_t T = observed.GetRows(); size_t N = nbStates; SSquareMatrixDouble A = stateTransitionProbability; SMatrixDouble B = stateGivenSymbolProbability; SMatrixDouble P = firstStateProbability; SMatrixDouble delta = std::make_shared<MatrixDouble>(T, N, 0.0); SMatrixInt phi = std::make_shared<MatrixInt>(T, N); // Setup. for (i = 0; i < N; i++) { delta->At(0, i) = P->At(i, 0) * B->At(i, observed.At(0, 0)); phi->At(0, i) = 0; } // Recursion. for (size_t t = 1; t < T; t++) { // New delta values. double NewDelta = 0.0; double MaxDelta = 0.0; size_t Index = 0; for (j = 0; j < N; j++) { for (i = 0; i < N; i++) { NewDelta = delta->At(t - 1, i) * A->At(i, j); if (NewDelta > MaxDelta) { MaxDelta = NewDelta; Index = i; } } delta->At(t, j) = MaxDelta * B->At(j, observed.At(t, 0)); phi->At(t, j) = int(Index); } } // Backtracking. UMatrixInt Path = std::make_unique<MatrixInt>(T, 1); size_t CurrentState; SMatrixDouble LastDelta = std::make_shared<MatrixDouble>(N, 1, 0.0); for (k = 0; k < N; k++) { LastDelta->At(k, 0) = delta->At(T - 1, k); } CurrentState = LastDelta->ArgmaxInColumn(0); Path->At(T - 1, 0) = int(CurrentState); for (int t = int(T) - 2; t >= 0; t--) { CurrentState = phi->At(t + 1, CurrentState); Path->At(t, 0) = int(CurrentState); } return std::forward<UMatrixInt>(Path); } /*! * HMM model training with Baum-Welch procedure. Training with one observation sequence. * * \param[in] observed the observed sequence as a line matrix * \param[in] maxIter the maximum number of iterations */ void DiscreteHMM::BaumWelchSingle(const MatrixInt& observed, size_t maxIter) { size_t Count = 1; bool Continue = true; while (Continue) { SDiscreteHMM H = CloneAs<DiscreteHMM>(*this); size_t i, j, k, t; size_t N = nbStates; size_t K = nbSymbols; size_t T = observed.GetCols(); SquareMatrixDouble A = *stateTransitionProbability; MatrixDouble B = *stateGivenSymbolProbability; MatrixDouble P = *firstStateProbability; UMatrixDouble Alpha(alpha(observed)); UMatrixDouble Beta(beta(observed)); SMatrixDouble Gamma = std::make_shared<MatrixDouble>(T, N, 0.0); std::vector<SSquareMatrixDouble> Xi(T); for (size_t date = 0; date < T; date++) { Xi[date] = std::make_shared<SquareMatrixDouble>(N, 0.0); } // Compute sequence probability via Alpha. double Prob = 0.0; for (k = 0; k < N; k++) { Prob += Alpha->At(T - 1, k); } // Computation for Xi and Gamma. // for (t = 0; t < T - 1; t++) { for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double z = (Alpha->At(t, i) * A.At(i, j) * B.At(j, observed.At(t + 1, 0)) * Beta->At(t + 1, j)) / Prob; Xi[t]->At(i, j) = z; Gamma->IncreaseElement(t, i, z); } } } // Last gamma vector (cf. Rabiner & Juang). for (i = 0; i < N; i++) { double alpha = Alpha->At(T - 1, i); double beta = Beta->At(T - 1, i); double g = alpha * beta / Prob; Gamma->IncreaseElement(T - 1, i, g); } // Re-estimation. // // Re-estimation for P. P = Gamma->MakeRow(0); // Re-estimation for A. A.SetAll(0.0); SMatrixDouble InvScales = std::make_shared<MatrixDouble>(N, 1, 0.0); for (t = 0; t < T - 1; t++) { for (i = 0; i < N; i++) { InvScales->IncreaseElement(i, 0, Gamma->At(t, i)); for (j = 0; j < N; j++) { A.IncreaseElement(i, j, Xi[t]->At(i, j)); } } } Xi.clear(); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double v = A.At(i, j); A.At(i, j) = v / InvScales->At(i, 0); } } // Re-estimation for B. for (j = 0; j < N; j++) { for (k = 0; k < K; k++) { double Numerator = 0.0; double Denominator = 0.0; for (t = 0; t < T; t++) { double g = Gamma->At(t, j); if (observed.At(t, 0) == int(k)) { Numerator += g; } Denominator += g; } B.At(j, k) = Numerator / Denominator; } } firstStateProbability = CloneAs<MatrixDouble>(P); stateTransitionProbability = CloneAs<SquareMatrixDouble>(A); stateGivenSymbolProbability = CloneAs<MatrixDouble>(B); // End for Baum-Welch step. // Count++; Continue = !((*this == *H) || (Count > maxIter)); } // XXX I forgot if this thing is still useful !!! //this.updateCumuls(); } /*! * HMM model training with Baum-Welch procedure. Training with many observation sequences. * * \param[in] observationSet the observed sequences. Each sequence is a line of the matrix. * \param[in] maxIter maximal number of iterations */ void DiscreteHMM::BaumWelchMultiple(const MatrixInt& observationSet, size_t maxIter) { size_t Count = 1; bool Continue=true; size_t i, j, k, m, n, t; size_t N = nbStates; size_t M = nbSymbols; size_t nbPatterns = observationSet.GetRows(); while (Continue) { SDiscreteHMM H = CloneAs<DiscreteHMM>(*this); SSquareMatrixDouble A = stateTransitionProbability; SMatrixDouble B = stateGivenSymbolProbability; SMatrixDouble P = firstStateProbability; SMatrixDouble CumulNumeratorA = std::make_shared<MatrixDouble>(N, N, 0.0); SMatrixDouble CumulNumeratorB = std::make_shared<MatrixDouble>(N, M, 0.0); SMatrixDouble CumulDenominatorA = std::make_shared<MatrixDouble>(N, N, 0.0); SMatrixDouble CumulDenominatorB = std::make_shared<MatrixDouble>(N, M, 0.0); SMatrixDouble CumulP = std::make_shared<MatrixDouble>(N, 1, 0.0); // Loop over all sequences. // for (k = 0; k < nbPatterns; k++) { MatrixInt Sample = observationSet.MakeRowAsColumn(k); size_t T = Sample.GetRows(); UMatrixDouble Alpha(alpha(Sample)); UMatrixDouble Beta(beta(Sample)); double Prob = 0.0; for (i = 0; i < N; i++) { Prob += Alpha->At(T - 1, i); } std::vector<SSquareMatrixDouble> Xi; std::vector<SMatrixDouble> Gamma; // Computation for Xi and Gamma. // for (t = 0; t < T - 1; t++) { SSquareMatrixDouble xi = std::make_shared<SquareMatrixDouble>(N); SMatrixDouble gamma = std::make_shared<MatrixDouble>(N, 1, 0.0); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double z = (Alpha->At(t, i)* A->At(i, j)* B->At(j, Sample.At(t + 1, 0))* Beta->At(t + 1, j)) / Prob; xi->At(i, j) = z; gamma->IncreaseElement(i, 0, z); } } Xi.push_back(xi); Gamma.push_back(gamma); } // Last gamma vector. { SMatrixDouble gamma = std::make_shared<MatrixDouble>(N, 1, 0.0); double Denominator = 0.0; for (i = 0; i < N; i++) { double alpha = Alpha->At(T - 1, i); double beta = Beta->At(T - 1, i); Denominator += alpha * beta; } for (i = 0; i < N; i++) { double alpha=Alpha->At(T - 1, i); double beta=Beta->At(T - 1, i); gamma->At(i, 0) = (alpha * beta) / Denominator; } Gamma.push_back(gamma); } // Accumulation. // // Accumulation for A. for (m = 0; m < N; m++) { for (n = 0; n < N; n++) { for (t = 0; t < T - 1; t++) { CumulNumeratorA->IncreaseElement(m, n, Xi[t]->At(m, n)); CumulDenominatorA->IncreaseElement(m, n, Gamma[t]->At(m, 0)); } } } // Accumulation for B; for (n = 0; n < N; n++) { for (m = 0; m < M; m++) { for (t = 0; t < T; t++) { double g = Gamma[t]->At(n, 0); if (Sample.At(t, 0) == int(m)) { CumulNumeratorB->IncreaseElement(n, m, g); } CumulDenominatorB->IncreaseElement(n, m, g); } } } // Accumulation for P. for (n = 0; n < N; n++) { CumulP->IncreaseElement(n, 0, Gamma[0]->At(n, 0)); } } // Levinson's re-estimation. // for (m = 0; m < N; m++) { for (n = 0; n < N; n++) { if (A->At(m, n) != 0.0) { A->At(m, n) = CumulNumeratorA->At(m, n) / CumulDenominatorA->At(m, n); } } } for (n = 0; n < N; n++) { for (m = 0; m < M; m++) { if (B->At(n,m) != 0.0) { B->At(n, m) = CumulNumeratorB->At(n, m) / CumulDenominatorB->At(n, m); } } } *CumulP *= 1.0 / double(nbSymbols); for (n = 0; n < N; n++) { P->At(n, 0) = CumulP->At(n, 0); } // Maintain consistency. // //forceConsistency(); // End for Baum-Welch step. // Count++; Continue = !((*this == *H) || (Count > maxIter)); } // ??? /* this.updateCumuls(); this.firstStateProbabilityCumul.display(); this.stateTransitionProbabilityCumul.display(); this.stateGivenSymbolProbabilityCumul.display(); */ } /*! * Sets probability matrix to a have a sum equals to one. */ void DiscreteHMM::forceConsistency() { size_t N = nbStates; size_t K = nbSymbols; SSquareMatrixDouble A = stateTransitionProbability; SMatrixDouble B = stateGivenSymbolProbability; // Sum over each row in A should be 1. for (size_t l = 0; l < N; l++) { double Cumul=0.0; for (size_t c = 0; c < N; c++) { Cumul += A->At(l, c); } if (Cumul != 1.0) { for (size_t c = 0; c < N; c++) { double a = A->At(l, c)/Cumul; A->At(l, c) = a; } } } // Sum over row line in B should be 1. for (size_t l = 0; l < N; l++) { double Cumul = 0.0; for (size_t c = 0; c < K; c++) { Cumul += B->At(l, c); } if (Cumul != 1.0) { for (size_t c = 0; c < K; c++) { double b = B->At(l,c)/Cumul; B->At(l, c) = b; } } } } /*! * Dump a summary to a string * * \return a string containing a summary of the model */ String DiscreteHMM::ToString() const { String s; s += U"Discrete HMM : "; s += String(nbStates); s += U" states "; s += String(nbSymbols); s += U"symbols\n\nState transion probability\n\n"; s += stateTransitionProbability->ToString(); s += U"\nState given symbol probability\n\n"; s += stateGivenSymbolProbability->ToString(); s += U"\nFirst state probability\n\n"; s += firstStateProbability->ToString(); return s; } CRN_BEGIN_CLASS_CONSTRUCTOR(DiscreteHMM) Cloner::Register<DiscreteHMM>(); CRN_END_CLASS_CONSTRUCTOR(DiscreteHMM)
package com.Employee.Employee.controller; import com.Employee.Employee.Employee; import com.Employee.Employee.Service.EmployeeService; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping @Operation(summary = "Get all Employees") @ResponseStatus(HttpStatus.OK) public ResponseEntity<Page<Employee>> getAllEmployees( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "5") int size, @RequestParam(defaultValue = "id") String sortBy) { Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy)); Page<Employee> employees = employeeService.getAllEmployees(pageable); return ResponseEntity.ok().body(employees); } @GetMapping("/{id}") @Operation(summary = "Get Employees by ID") @ResponseStatus(HttpStatus.OK) public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) { return employeeService.getEmployeeById(id) .map(employee -> ResponseEntity.ok().body(employee)) .orElse(ResponseEntity.notFound().build()); } @PostMapping @Operation(summary = "Create employee") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Employee> createEmployee(@Valid @RequestBody Employee employee) { return ResponseEntity.status(HttpStatus.CREATED).body(employeeService.addEmployee(employee)); } @PutMapping("/{id}") @Operation(summary = "Update Employee") @ResponseStatus(HttpStatus.OK) public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails) { return ResponseEntity.ok().body(employeeService.updateEmployee(id, employeeDetails)); } @DeleteMapping("/{id}") @Operation(summary = "Delete employee") @ResponseStatus(HttpStatus.OK) public ResponseEntity<?> deleteEmployee(@PathVariable Long id) { employeeService.deleteEmployee(id); return ResponseEntity.ok().build(); } }
package com.ikang.idata.search.search.javaTest; import jodd.util.function.Consumers; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; /** * @author <a href="mailto:minxin.fan@ikang.com">minxin.fan</a> * @description ${description} * @date 2022/4/2 */ @Slf4j public class PersonTest { public PersonTest() { } private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } private static void IOMethod() throws IOException { char c; // 使用 System.in 创建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("输入字符, 按下 'q' 键退出。"); // 读取字符 do { c = (char) br.read(); System.out.println(c); } while (c != 'q'); //------------------------------------分割线-------------------------------------------------------- // 使用 System.in 创建 BufferedReader BufferedReader brOne = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do { str = brOne.readLine(); System.out.println(str); } while (!str.equals("end")); //------------------------------------分割线-------------------------------------------------------- try { byte bWrite[] = { 11, 21, 3, 40, 5 }; OutputStream os = new FileOutputStream("test.txt"); for (int x = 0; x < bWrite.length; x++) { os.write(bWrite[x]); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for (int i = 0; i < size; i++) { System.out.print((char) is.read() + " "); } is.close(); } catch (IOException e) { log.error(e.getMessage(), e); } //------------------------------------分割线-------------------------------------------------------- File f = new File("a.txt"); FileOutputStream fop = new FileOutputStream(f); // 构建FileOutputStream对象,文件不存在会自动新建 OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk writer.append("中文输入"); // 写入到缓冲区 writer.append("\r\n"); // 换行 writer.append("English"); // 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入 writer.close(); // 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉 fop.close(); // 关闭输出流,释放系统资源 FileInputStream fip = new FileInputStream(f); // 构建FileInputStream对象 InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); // 构建InputStreamReader对象,编码与写入相同 StringBuffer sb = new StringBuffer(); while (reader.ready()) { sb.append((char) reader.read()); // 转成char加到StringBuffer对象中 } System.out.println(sb.toString()); reader.close(); // 关闭读取流 fip.close(); // 关闭输入流,释放系统资源 String dirname = "/tmp/user/java/bin"; File d = new File(dirname); // 现在创建目录 d.mkdirs(); String dirnameOne = "/tmp"; File f1 = new File(dirnameOne); if (f1.isDirectory()) { System.out.println("目录 " + dirnameOne); String s[] = f1.list(); for (int i = 0; i < s.length; i++) { File fOne = new File(dirnameOne + "/" + s[i]); if (fOne.isDirectory()) { System.out.println(s[i] + " 是一个目录"); } else { System.out.println(s[i] + " 是一个文件"); } } } else { System.out.println(dirnameOne + " 不是一个目录"); } /** * 目录 /tmp * bin 是一个目录 * lib 是一个目录 * demo 是一个目录 * test.txt 是一个文件 * README 是一个文件 * index.html 是一个文件 * include 是一个目录 */ // 这里修改为自己的测试目录 File folder = new File("/tmp/java/"); deleteFolder(folder); } // 删除文件及目录 public static void deleteFolder(File folder) { File[] files = folder.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { deleteFolder(f); } else { f.delete(); } } } folder.delete(); } //静态方法 Optional.of() //为指定的值创建一个指定非 null 值的 Optional。 @org.junit.jupiter.api.Test public void ofTest(){ //传入正常值 正常返回一个Optional对象 Optional<String> optional= Optional.of("加油"); System.out.println(optional); // //传入null值 则会报 NullPointerException // Optional optional1= Optional.of(null); // System.out.println(optional1); } //静态方法 Optional.ofNullable() //为指定的值创建一个 Optional 对象,如果指定的参数为 null,不抛出异常,直接则返回一个空的 Optional 对象。 @org.junit.jupiter.api.Test public void ofNullAbleTest(){ //传入正常值 正常返回一个Optional对象 Optional<String> optional= Optional.ofNullable("嘿呀"); System.out.println(optional); //传入null值 正常返回Optional 对象 Optional optional1= Optional.ofNullable(null); System.out.println(optional1); } //对象方法 isPresent() //如果值存在则方法会返回 true,否则返回 false。 @org.junit.jupiter.api.Test public void isPresentTest(){ //传入正常值 正常返回一个Optional对象 并使用isPresent方法 Optional optional= Optional.ofNullable("嘿呦"); System.out.println("传入正常值" + optional.isPresent()); //结果 true //传入null值 正常返回Optional 对象 Optional optional1= Optional.ofNullable(null); System.out.println("传入正常值" + optional1.isPresent()); //结果 false } //对象方法 get() //如果 Optional 有值则将其返回,否则抛出 NoSuchElementException 异常。 @org.junit.jupiter.api.Test public void getTest(){ //传入正常值 正常返回一个Optional对象 并使用get方法 Optional optional= Optional.ofNullable("嘿呦"); System.out.println("传入正常值" + optional.get()); //结果 传入正常值嘿呦 //传入null值 正常返回Optional 对象 Optional optional1= Optional.ofNullable(null); System.out.println("传入正常值" + optional1.get()); //结果 java.util.NoSuchElementException: No value present } //对象方法 ifPresent() // 如果值存在则使用该值调用 consumer , 否则不做任何事情。 //该方法 ifPresent(Consumer<? super T> consumer) 中参数接收的是 Consumer 类,它包含一个接口方法 accept(),该方法能够对传入的值进行处理,但不会返回结果。这里传入参数可以传入 Lamdda 表达式或 Consumer 对象及实现 Consumer 接口的类的对象。 @org.junit.jupiter.api.Test public void ifPresentTest(){ //创建Optional 对象 然后调用Optional 对象的ifPresent 方法 传入Lambda 表达式 Optional optional= Optional.ofNullable("向目标前进"); optional.ifPresent((value) -> System.out.println("optional 的值为" + value)); //结果 向目标前进 //创建Optional 对象 调用Optional对象的ifPresent方法 传入实现Consumer匿名 Optional optional1= Optional.ofNullable("加油呀"); Consumer<String> consumer = new Consumers(){ @Override public void accept(Object value){ System.out.println("Optional 的值为" + value); } }; optional1.ifPresent(consumer); //结果 加油呀 } //对象方法 orElse() //如果该值存在就直接返回, 否则返回指定的其它值。 // orElse 方法实现很简单,就是使用三目表达式对传入的参数值进行 null 验证,即 value != null ? value : other; 如果为 null 则返回 true,否则返回 false。 @org.junit.jupiter.api.Test public void orElseTest(){ //传入正常的参数 获取一个Optional 对象 并使用orElse方法设置默认值 Optional optional = Optional.ofNullable("三生三世"); Object deFaultValue = optional.orElse("默认值"); System.out.println("如果值不为空" + deFaultValue); //结果 三生三世 //传入null参数 获取一个Optional对象 并使用orElse方法设置默认值 Optional optional1 = Optional.ofNullable(null); Object deFaultValue1 = optional1.orElse("默认值"); System.out.println("如果值为空" + deFaultValue1); //结果 默认值 } // https://blog.csdn.net/weixin_36380516/article/details/113361959?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164887835416780357237329%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164887835416780357237329&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-2-113361959.142^v5^pc_search_result_cache,157^v4^control&utm_term=Optional.ofNullable&spm=1018.2226.3001.4187 //orElseGet() //orElseGet 方法和 orElse 方法类似,都是在 Optional 值为空时,返回一个默认操作,只不过 orElse 返回的是默认值,而 orElseGet 是执行 lambda 表达式,然后返回 lambda 表达式执行后的结果。 @org.junit.jupiter.api.Test public void orElseGetTest(){ //传入正常参数 获取一个Optional 对象 并使用orElse方法 设置默认值 Optional optional = Optional.ofNullable("新的一周"); Object object = optional.orElseGet(() -> { String defaultVal = "执行逻辑和生成默认值"; return defaultVal; }); System.out.println("输出值为" + object); //传入null参数 获取一个Optional对象 并使用orElse方法设置默认值 Optional optional1 = Optional.ofNullable(null); Object object1 = optional1.orElseGet(() -> { String defaultVal = "执行逻辑和生成默认值"; return defaultVal; }); System.out.println("输出值为" + object1); /** * 打印结果 * object 新的一周 * object1 执行逻辑和生成默认值 */ } //orElseThrow() //orElseThrow 方法其实就是判断创建 Optional 时传入的参数是否为 null,如果是非 null 则返回传入的值,否则抛出 异常。 @org.junit.jupiter.api.Test public void orElseThrowTest(){ //传入正常参数 获取一个Optional对象 并使用orElseThrow方法 Optional optional = Optional.ofNullable("加油加油"); try { Object elseThrow = optional.orElseThrow(() -> { System.out.println("执行逻辑,然后抛出异常"); return new RuntimeException("抛出异常"); }); System.out.println("输出值为 " + elseThrow); } catch (Throwable throwable) { throwable.printStackTrace(); } //传入null参数 获取一个Optional 对象 并使用orElseThrow 方法 Optional optional1 = Optional.ofNullable(null); try { Object elseThrow1 = optional1.orElseThrow(() -> { System.out.println("执行逻辑,然后抛出异常"); return new RuntimeException("抛出异常"); }); System.out.println("输出值为 " + elseThrow1); } catch (Throwable throwable) { throwable.printStackTrace(); } /** * 打印结果 * elseThrow 加油加油 * elseThrow1 抛出异常并报错 */ } // 创建一个用户类,使用 Optional 操作用户对象,获取其 name 参数,结合 Optional 的 map 方法获取值,进行观察: class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } //使用 Optional 的 map 方法对值处理: // @org.junit.jupiter.api.Test // public void orElseTest1() { // //创建一个对象 设置名字属性而不设置性别 这时候性别为null // Test.User user = new Test.User("测试名称"); // Test.User user1 = new Test.User(null); // // //使用Optional存储User对象 // Optional<Test.User> optionalUser = Optional.ofNullable(user); // Optional<Test.User> optionalUser1 = Optional.ofNullable(user1); // // //获取对象的name属性值 // String name = optionalUser.map(Test.User::getName).orElse("未填写"); // String name1 = optionalUser1.map(Test.User::getName).orElse("未填写"); // // //输出结果 // System.out.println("获取的名称 " + name); // System.out.println("获取的名称 " + name1); // // /** // * 打印结果 // * name 测试名称 // * name1 未填写 // */ // //通过上面两个示例观察到,通过 Optional 对象的 map 方法能够获取映射对象中的属,创建 Optional 对象,并以此属性充当 Optional 的值,结合 orElse 方法,如果获取的属性的值为空,则设置个默认值。 // } //对象方法 flatMap() // flatMap 方法和 map 方法类似,唯一的不同点就是 map 方法会对返回的值进行 Optional 封装,而 flatMap 不会,它需要手动执行 Optional.of 或 Optional.ofNullable 方法对 Optional 值进行封装。 @org.junit.jupiter.api.Test public void flatMapTest() { //创建一个map 对象 Map<String, String> userMap = new HashMap<>(); userMap.put("name", "jiayou"); userMap.put("sex", "nan"); //传入Map对象参数 获取一个Optional对象 Optional<Map<String, String>> optional = Optional.of(userMap); //使用Optionalde flatMap方法 获取Map中的name属性值,然后通过获取的值手动创建一个新的Optional对象 Optional optional1 = optional.flatMap(value -> Optional.ofNullable(value.get("name"))); System.out.println("获取的Optional 的值" + optional1.get()); /** * 打印结果 * jiayou */ } } }
/** * This file is part of dHealth dApps Framework shared under LGPL-3.0 * Copyright (C) 2022-present dHealth Network, All rights reserved. * * @package dHealth dApps Framework * @subpackage Backend * @author dHealth Network <devs@dhealth.foundation> * @license LGPL-3.0 */ // external dependencies import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Model } from "mongoose"; // internal dependencies import { Documentable } from "../../common/concerns/Documentable"; import { Transferable } from "../../common/concerns/Transferable"; import { Queryable, QueryParameters } from "../../common/concerns/Queryable"; import { StatisticsDTO } from "./StatisticsDTO"; import { StatisticsDataType } from "./StatisticsDataType"; /** * @class Activity * @description This class defines the **exact** fields that are * stored in the corresponding MongoDB documents. It should be * used whenever database *documents* are being handled or read * for the `activities` collection. * <br /><br /> * Note that this class uses the generic {@link Transferable} trait to * enable a `toDTO()` method on the model. * * @todo Timestamp fields should be **numbers** to avoid timezone issues. * @since v0.3.2 */ @Schema({ timestamps: true, }) export class Statistics extends Transferable<StatisticsDTO> { /** * This field contains the *mongo collection name* for entries * that are stored using {@link AccountIntegrationDocument} or the model * {@link AccountIntegrationModel}. * <br /><br /> * Note that this field **is not** part of document properties * and used only internally to perform queries that refer to * an individual collection name, e.g. `$unionWith`. * * @access public * @var {string} */ public collectionName = "statistics"; /** * The type of this statistics schema. Depends on the * data type it would take a different * specific value. * <br /><br /> * This field is **required** and *not indexed*. * * @example `"leaderboard"` * @access public * @var {string} */ @Prop({ required: true, index: true }) public readonly type: string; /** * The period format of this statistics schema. Depends on the * sub-statistics scheduler it would take a different * specific value. * Currently there are 3 types of periods: * | value | description | * |---------|----------------| * | "D" | occurs daily | * | "W" | occurs weekly | * | "M" | occurs monthly | * <br /><br /> * This field is **required** and *not indexed*. * * @example `"M"` * @access public * @var {string} */ @Prop({ required: true }) public readonly periodFormat: "D" | "W" | "M"; /** * The period string representation of this schema. * Currently there are 3 types of periods: * | name | description | example | example explained * |---------|----------------|-------------|-------------------------- * | daily | occurs daily | "20220130" | period occuring between 0:00 AM 30/01/2022 and 0:00 AM Jan 30 2022 * | weekly | occurs weekly | "202201-02" | period occuring between monday and sunday the second week of Jan 2022 * | monthly | occurs monthly | "202201" | period occuring between the 1st and 31st of Jan 2022 * <br /><br /> * This field is **required** and *indexed*. * * @example `"20220130"` * @access public * @var {string} */ @Prop({ required: true, type: String, index: true }) public readonly period: string; /** * The account's **address**. An address typically refers to a * human-readable series of 39 characters, starting either with * a `T`, for TESTNET addresses, or with a `N`, for MAINNET addresses. * <br /><br /> * This field is **required** and *indexed*. * * @access public * @readonly * @var {string} */ @Prop({ required: true, type: String, index: true }) public readonly address: string; /** * The position of the user of this schema. This reflects * the position in terms of total rewards (token) amount * this user's address has received. * <br /><br /> * This field is **required** and *indexed*. * * @example `123456` * @access public * @var {number} */ @Prop({ required: true, index: true, nullable: true }) public readonly position?: number; /** * The total amount of tokens that the address of this schema * has received. Amount is in absolute format. * <br /><br /> * This field is **required** and *not indexed*. * * @example `123456` * @access public * @var{number} */ @Prop({ required: true, nullable: true }) public readonly amount?: number; /** * The data attached to this statistics document. This can contain * any object literal that is defined using one of: * - {@link UserStatisticsFields}: Consists of a user statistic fields definition. * - `ObjectLiteral`: e.g. `{ just: "a value" }`. * <br /><br /> * This field is **optional** and *not indexed*. * * @example `123456` * @access public * @var {number} */ @Prop({ required: false, nullable: true, type: Object }) public data?: StatisticsDataType; /** * The document's creation timestamp. This field **does not** reflect the * date of creation of an integration but rather the date of creation of the * cached database entry. * <br /><br /> * This field is **required** and *indexed*. * * @access public * @readonly * @var {Date} */ @Prop({ index: true }) public readonly createdAt?: Date; /** * The document's update timestamp. This field **does not** reflect the * date of update of an integration but rather the date of update of the * cached database entry. * <br /><br /> * This field is **optional** and *not indexed*. * * @access public * @readonly * @var {Date} */ @Prop() public readonly updatedAt?: Date; /** * This method implements a specialized query format to query items * individually, as documents, in the collection: `account_integrations`. * * @access public * @returns {Record<string, unknown>} The individual document data that is used in a query. */ public get toQuery(): Record<string, unknown> { const query: Record<string, any> = {}; if (undefined !== this.type) query["type"] = this.type; if (undefined !== this.period) query["period"] = this.period; if (undefined !== this.address) query["address"] = this.address; if (undefined !== this.position) query["position"] = this.position; return query; } /** * This *static* method populates a {@link StatisticsDTO} object from the * values of a {@link StatisticsDocument} as presented by mongoose queries. * * @access public * @static * @param {StatisticsDocument} doc The document as received from mongoose. * @param {StatisticsDTO} dto The DTO object that will be populated with values. * @returns {StatisticsDTO} The `dto` object with fields set. */ public static fillDTO( doc: StatisticsDocument, dto: StatisticsDTO, ): StatisticsDTO { dto.type = doc.type; dto.periodFormat = doc.periodFormat; dto.period = doc.period; dto.address = doc.address; dto.position = doc.position; dto.amount = doc.amount; dto.data = doc.data; return dto; } } /** * @type StatisticsDocument * @description This type is used to interface entities of the * `statistics` collection with *mongoose* and permits to * instanciate objects representing these entities. * <br /><br /> * e.g. alongside {@link StatisticsSchema}, we also define * `StatisticsDocument` which is a mixin that comprises of * {@link Statistics} and this `Documentable` class. * <br /><br /> * In class {@link Queryable}, the first generic accepted * permits to use *documents* that are typed with this, to filter * results in a documents query. * * @since v0.3.2 */ export type StatisticsDocument = Statistics & Documentable; /** * @class StatisticsModel * @description This class defines the **model** or individual * **document** for one collection ("schema"). This class can * be *automatically* injected in services using the `@InjectModel` * decorator of `nestjs/mongoose`. * <br /><br /> * @example Injecting and using the `StatisticsModel` * ```typescript * import { InjectModel } from "@nestjs/mongoose"; * import { Statistics, StatisticsModel } from "./StatisticsSchema"; * * class MyStatisticsService { * public constructor( * @InjectModel(Statistics.name) private readonly model: StatisticsModel * ) * * public addEntry(data: Record<string, any>) { * return this.model.create(data); * } * } * ``` * * @since v0.3.2 */ export class StatisticsModel extends Model<StatisticsDocument> {} /** * @class StatisticsQuery * @description This class augments {@link Queryable} objects enabling * *statistics* to be queried **by any fields.** * <br /><br /> * The main purpose of this class shall be to perform queries against * the `statistics` collection. * * @since v0.3.2 */ export class StatisticsQuery extends Queryable<StatisticsDocument> { /** * Copy constructor for pageable queries in `account_integrations` collection. * * @see Queryable * @param {StatisticsDocument|undefined} document The *document* instance (defaults to `undefined`) (optional). * @param {QueryParameters|undefined} queryParams The query parameters including as defined in {@link QueryParameters} (optional). */ public constructor( document?: StatisticsDocument, queryParams: QueryParameters = undefined, ) { super(document, queryParams); } } /** * @export StatisticsSchema * @description This export creates a mongoose schema using the custom * {@link Statistics} class and should be used mainly when *inferring* the * type of fields in a document for the corresponding collection. * * @since v0.3.2 */ export const StatisticsSchema = SchemaFactory.createForClass(Statistics); // This call to **loadClass** on the schema object enables instance // methods on the {@link Statistics} class to be called when the model gets // instanciated by `mongoose` directly, e.g. as the result of a query. StatisticsSchema.loadClass(Statistics, true);
// // LocalStorage.swift // LOARANG-MVVM // // Created by 최최성균 on 2022/08/02. // import RealmSwift final class LocalStorage { private let realm: Realm init(realm: Realm) { self.realm = realm } func mainUser() -> MainUser? { guard let mainUserDTO = realm.objects(MainUserDTO.self).first else { return nil } return mainUserDTO.convertedInfo } func bookmarkUsers() -> [BookmarkUser] { let bookmarkList = realm.objects(BookmarkUserDTO.self) let bookmarkUsers: [BookmarkUser] = bookmarkList.map { return $0.convertedInfo } return bookmarkUsers } func recentUsers() -> [RecentUser] { let recentUserList = realm.objects(RecentUserDTO.self) let recentUsers: [RecentUser] = recentUserList.map { return $0.convertedInfo } return recentUsers.reversed() } func addBookmarkUser(_ user: BookmarkUser) throws { let bookmarkUsers = realm.objects(BookmarkUserDTO.self) guard bookmarkUsers.count < 20 else { throw LocalStorageError.overBookmakr } do { try realm.write { realm.add(user.convertedInfo) } } catch { throw LocalStorageError.addBookmarkError } } func updateBookmarkUser(_ user: BookmarkUser) throws { do { try realm.write { realm.add(user.convertedInfo, update: .modified) } } catch { throw LocalStorageError.updateBookmarkError } } func deleteBookmarkUser(_ name: String) throws { let bookmarkList = realm.objects(BookmarkUserDTO.self) guard let bookmarkUserDTO = bookmarkList.filter({ $0.name == name }).first else { throw LocalStorageError.deleteBookmarkError } do { try realm.write { realm.delete(bookmarkUserDTO) } } catch { throw LocalStorageError.deleteBookmarkError } } func changeMainUser(_ user: MainUser) throws { do { try realm.write { realm.add(user.convertedInfo, update: .modified) } } catch { throw LocalStorageError.changeMainUserError } } func addRecentUser(_ user: RecentUser) throws { let recentUserList = realm.objects(RecentUserDTO.self) if recentUserList.count > 14 { guard let lastUser = recentUserList.first else { return } do { try realm.write { realm.delete(lastUser) } } } do { try deleteRecentUser(user.name) } catch {} do { try realm.write { realm.add(user.convertedInfo) } } catch { throw LocalStorageError.addRecentUserError } } func deleteRecentUser(_ name: String) throws { let recentUserList = realm.objects(RecentUserDTO.self) guard let recentUserDTO = recentUserList.filter({ $0.name == name }).first else { throw LocalStorageError.deleteRecentUserError } do { try realm.write { realm.delete(recentUserDTO) } } catch { throw LocalStorageError.deleteRecentUserError } } func clearRecentUsers() throws { let recentUserList = realm.objects(RecentUserDTO.self) do { try realm.write { realm.delete(recentUserList) } } catch { throw LocalStorageError.deleteRecentUserError } } }
import React, { useEffect, useState } from 'react' import { Navbar, Container, Nav, Badge } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import { productSearch } from '../Redux/Slices/productSlice' function Header({insideHome}) { const dispatch = useDispatch() const [wishlistCount,setWishlistCount] = useState(0) const [cartCount,setCartCount] = useState(0) const wishlist = useSelector(state=>state.wishlistSlice.wishlist) const cart = useSelector(state=>state.cartReducer) useEffect(()=>{ setWishlistCount(wishlist?.length) setCartCount(cart?.length) },[wishlist,cart]) return ( <Navbar style={{zIndex:'1'}} expand="lg" className="bg-primary position-fixed top-0 w-100 mb-3"> <Container> <Navbar.Brand ><Link to={'/'} style={{textDecoration:'none',color:'white',fontWeight:'bold'}}><i class="fa-solid fa-truck-fast me-2"></i>G-Kart</Link></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ms-auto"> { insideHome&&<Nav.Link className='me-lg-5'> <input onChange={e=>dispatch(productSearch(e.target.value.toLowerCase()))} style={{width:'400px'}} type="text" className="form-control" placeholder='Search products!!!'/> </Nav.Link>} <Nav.Link className='btn rounded'> <Link to={'/wishlist'} className='d-flex align-items-center' style={{textDecoration:'none',color:'white',fontWeight:'bold'}}> <i className="fa-solid fa-heart text-danger me-2"></i> Wishlist <Badge className='ms-2 rounded' bg="light"> {wishlistCount} </Badge> </Link> </Nav.Link> <Nav.Link className='btn rounded ms-5'> <Link to={'/cart'} className='d-flex align-items-center' style={{textDecoration:'none',color:'white',fontWeight:'bold'}}> <i className="fa-solid fa-cart-shopping text-warning me-2"></i> Cart <Badge className='ms-2 rounded' bg="light"> {cartCount} </Badge> </Link> </Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ) } export default Header
package constants import ( "fmt" "math" "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/k-orolevsk-y/resale-bot/internal/bot/entities" ) // USER KEYBOARDS func MainKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Акции"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Б/У устройства"), tgbotapi.NewKeyboardButton("Новые устройства"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Трейд-ин"), tgbotapi.NewKeyboardButton("Ремонт"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Связаться с менеджером"), ), ) } func SalesKeyboard(products []entities.Product) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, product := range products { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } name := fmt.Sprintf("%s - %s", product.Model, product.Additional) keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(name)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Главное меню"))) return keyboard } func CategoryKeyboard(categories []entities.Category) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, category := range categories { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(category.Name)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Главное меню"))) return keyboard } func ProducersKeyboard(producers []string) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, producer := range producers { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(producer)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Назад к категориям"))) return keyboard } func ProductsKeyboard(products []entities.Product) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, product := range products { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } name := fmt.Sprintf("%s - %s", product.Model, product.Additional) keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(name)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Назад к категориям"))) return keyboard } func ProductKeyboard(botName string, product *entities.Product) tgbotapi.InlineKeyboardMarkup { reservation := fmt.Sprintf("reservation:%s", product.ID) share := fmt.Sprintf(" - посмотри на товар в этом боте.\n\nhttps://t.me/%s?start=product_%s", botName, product.ID) return tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Забронировать", reservation), tgbotapi.NewInlineKeyboardButtonSwitch("Поделиться", share), ), ) } func CategoryRepairKeyboard(categories []string) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, category := range categories { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(category)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Главное меню"))) return keyboard } func ModelsRepairKeyboard(models []string) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, model := range models { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(model)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Назад к списку производителей"))) return keyboard } func RepairsKeyboard(repairs []entities.Repair) tgbotapi.ReplyKeyboardMarkup { keyboard := tgbotapi.NewReplyKeyboard() for _, repair := range repairs { name := fmt.Sprintf("%s - %.2f ₽", repair.Name, repair.Price) keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton(name))) } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Назад к списку производителей"))) return keyboard } func RepairKeyboard(repair *entities.Repair) tgbotapi.InlineKeyboardMarkup { repairData := fmt.Sprintf("repair:%s", repair.ID) return tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Отправить заявку на ремонт", repairData), ), ) } // MANAGER KEYBOARDS func ManagerKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Пользователи"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Каталог"), tgbotapi.NewKeyboardButton("Ремонты"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Главное меню"), ), ) } func ManagerUserKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Список бронирований"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Сменить статус блокировки"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Сменить статус прав менеджера"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель менеджера"), ), ) } func ManagerCatalogKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Забронированные товары"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Категории"), tgbotapi.NewKeyboardButton("Товары"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель менеджера"), ), ) } func ManagerCatalogCategoriesKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Создать новую категорию"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Список категорий"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель каталога"), ), ) } func ManagerCatalogProductsKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Добавить новый товар"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Список товаров"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель каталога"), ), ) } func ManagerRepairsKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Добавить новый ремонт"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Список ремонтов"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель менеджера"), ), ) } func ManagerNewCategory() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerNewCategoryType() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Новые"), tgbotapi.NewKeyboardButton("Б/У"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerNewProductCategory(categories []entities.Category) tgbotapi.ReplyKeyboardMarkup { var row int keyboard := tgbotapi.NewReplyKeyboard() for i, category := range categories { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } var name string if category.Type == 0 { name = fmt.Sprintf("%s [Новые]", category.Name) } else { name = fmt.Sprintf("%s [Б/У]", category.Name) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(name)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Отмена"))) return keyboard } func ManagerNewProductArrString(arr []string) tgbotapi.ReplyKeyboardMarkup { if len(arr) < 1 { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } var row int keyboard := tgbotapi.NewReplyKeyboard() for i, elem := range arr { if len(keyboard.Keyboard) <= row { keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow()) } keyboard.Keyboard[row] = append(keyboard.Keyboard[row], tgbotapi.NewKeyboardButton(elem)) if (i+1)%2 == 0 { row++ } } keyboard.Keyboard = append(keyboard.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Отмена"))) return keyboard } func ManagerSkip() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Пропустить"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerEmpty() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Убрать"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerExit() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerNewProductIsSale() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Да"), tgbotapi.NewKeyboardButton("Нет"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Отмена"), ), ) } func ManagerCategoryKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить название"), tgbotapi.NewKeyboardButton("Изменить тип"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Удалить"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель категорий"), ), ) } func ManagerReservationKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить статус"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель каталога"), ), ) } func ManagerProductKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить категорию"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить производителя"), tgbotapi.NewKeyboardButton("Изменить модель"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить атрибуты"), tgbotapi.NewKeyboardButton("Изменить описание"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить цену"), tgbotapi.NewKeyboardButton("Изменить скидку"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить статус акции"), tgbotapi.NewKeyboardButton("Изменить фото"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Удалить"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель товаров"), ), ) } func ManagerRepairKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить производителя"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить модель"), tgbotapi.NewKeyboardButton("Изменить название"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Изменить описание"), tgbotapi.NewKeyboardButton("Изменить цену"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Удалить"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Вернуться в панель ремонтов"), ), ) } func ManagerReservationEditKeyboard(reservation *entities.Reservation) tgbotapi.ReplyKeyboardMarkup { kb := tgbotapi.NewReplyKeyboard() if reservation.Completed != -1 { kb.Keyboard = append(kb.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Отменён"))) } if reservation.Completed != 0 { kb.Keyboard = append(kb.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Рассматривается"))) } if reservation.Completed != 1 { kb.Keyboard = append(kb.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Выполнен"))) } kb.Keyboard = append(kb.Keyboard, tgbotapi.NewKeyboardButtonRow(tgbotapi.NewKeyboardButton("Назад"))) return kb } func PaginationKeyboard(data string, countItems, offset, countOnPage int) tgbotapi.InlineKeyboardMarkup { kb := tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow(), ) if offset > 0 { kbData := fmt.Sprintf("%s:%d", data, offset-countOnPage) kb.InlineKeyboard[0] = append(kb.InlineKeyboard[0], tgbotapi.NewInlineKeyboardButtonData("<-", kbData)) } else { kb.InlineKeyboard[0] = append(kb.InlineKeyboard[0], tgbotapi.NewInlineKeyboardButtonData("|", "noData")) } currentPage := (offset / countOnPage) + 1 maxPage := int(math.Ceil(float64(countItems) / float64(countOnPage))) mainText := fmt.Sprintf("%d / %d", currentPage, maxPage) kb.InlineKeyboard[0] = append(kb.InlineKeyboard[0], tgbotapi.NewInlineKeyboardButtonData(mainText, "noData")) if countItems > (offset + countOnPage) { kbData := fmt.Sprintf("%s:%d", data, offset+countOnPage) kb.InlineKeyboard[0] = append(kb.InlineKeyboard[0], tgbotapi.NewInlineKeyboardButtonData("->", kbData)) } else { kb.InlineKeyboard[0] = append(kb.InlineKeyboard[0], tgbotapi.NewInlineKeyboardButtonData("|", "noData")) } return kb }
package com.osho.blog.serviceimpl; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.osho.blog.entities.Category; import com.osho.blog.entities.Post; import com.osho.blog.entities.User; import com.osho.blog.exceptions.ResourceNotFoundException; import com.osho.blog.payloads.PostDto; import com.osho.blog.payloads.PostResponse; import com.osho.blog.repositories.CategoryRepo; import com.osho.blog.repositories.PostRepo; import com.osho.blog.repositories.UserRepo; import com.osho.blog.services.PostService; @Service public class PostServiceImpl implements PostService { @Autowired private PostRepo postRepo; @Autowired private ModelMapper modelMapper; @Autowired private UserRepo userRepo; @Autowired private CategoryRepo categoryRepo; @Override public PostDto createPost(PostDto postDto, Integer userId, Integer categoryId) { // TODO Auto-generated method stub User user = this.userRepo.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "Id", userId)); Category category = this.categoryRepo.findById(categoryId) .orElseThrow(() -> new ResourceNotFoundException("Category", "Id", categoryId)); Post post = this.modelMapper.map(postDto, Post.class); post.setImageName("default.png"); post.setAddDate(new Date()); post.setUser(user); post.setCategory(category); Post newPost = this.postRepo.save(post); return this.modelMapper.map(newPost, PostDto.class); } @Override public PostDto updatePost(PostDto postDto, Integer postId) { // TODO Auto-generated method stub Post post = this.postRepo.findById(postId) .orElseThrow(() -> new ResourceNotFoundException("Post", "Id", postId)); post.setTitle(postDto.getTitle()); post.setContent(postDto.getContent()); post.setImageName(postDto.getImageName()); Post newPost = this.postRepo.save(post); return this.modelMapper.map(newPost, PostDto.class); } @Override public void deletePost(Integer postId) { // TODO Auto-generated method stub Post post = this.postRepo.findById(postId) .orElseThrow(() -> new ResourceNotFoundException("Post", "Id", postId)); this.postRepo.delete(post); } @Override public PostResponse getAllPosts(Integer pageNumber,Integer pageSize,String sortBy) { // TODO Auto-generated method stub Pageable p = PageRequest.of(pageNumber, pageSize,Sort.by(sortBy)); Page<Post> page = this.postRepo.findAll(p); List<Post> posts = page.getContent(); List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(post, PostDto.class)) .collect(Collectors.toList()); PostResponse postResponse = new PostResponse(); postResponse.setContent(postDtos); postResponse.setPageNumber(page.getNumber()); postResponse.setPageSize(page.getSize()); postResponse.setTotalElements(page.getTotalElements()); postResponse.setTotalPages(page.getTotalPages()); postResponse.setLastPage(page.isLast()); return postResponse; } @Override public PostDto getPostById(Integer postId) { // TODO Auto-generated method stub Post post = this.postRepo.findById(postId) .orElseThrow(() -> new ResourceNotFoundException("Post", "Id", postId)); ; return this.modelMapper.map(post, PostDto.class); } @Override public List<PostDto> getPostByCategory(Integer categoryId) { // TODO Auto-generated method stub Category category = this.categoryRepo.findById(categoryId) .orElseThrow(() -> new ResourceNotFoundException("Category", "Id", categoryId)); List<Post> posts = this.postRepo.findByCategory(category); List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(post, PostDto.class)) .collect(Collectors.toList()); return postDtos; } @Override public List<PostDto> getPostByUser(Integer userId) { // TODO Auto-generated method stub User user = this.userRepo.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "Id", userId)); List<Post> posts = this.postRepo.findByUser(user); List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(post, PostDto.class)) .collect(Collectors.toList()); return postDtos; } @Override public List<PostDto> searchPosts(String keyword) { // TODO Auto-generated method stub List<Post> posts = this.postRepo.findByTitleContaining(keyword); List<PostDto>postDtos = posts.stream().map((post)->this.modelMapper.map(post, PostDto.class)).collect(Collectors.toList()); return postDtos; } }
import { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { useFormik } from "formik"; import * as Yup from "yup"; import { Alert, Box, Button, Dialog, DialogContent, DialogContentText, DialogTitle, IconButton, MenuItem, Paper, Skeleton, TextField, Typography, } from "@mui/material"; import SaveIcon from "@mui/icons-material/Save"; import DoDisturbIcon from "@mui/icons-material/DoDisturb"; import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos"; import DeleteIcon from "@mui/icons-material/Delete"; import AddCardIcon from "@mui/icons-material/AddCard"; import CreditCardIcon from "@mui/icons-material/CreditCard"; import { CreditCard } from "../../components/creditCard/CreditCard"; import { startAddingNewCard, startDeletingCard, } from "../../store/user/userThunks"; const months = [ { value: 1, text: "Enero" }, { value: 2, text: "Febrero" }, { value: 3, text: "Marzo" }, { value: 4, text: "Abril" }, { value: 5, text: "Mayo" }, { value: 6, text: "Junio" }, { value: 7, text: "Julio" }, { value: 8, text: "Agosto" }, { value: 9, text: "Septiembre" }, { value: 10, text: "Octubre" }, { value: 11, text: "Noviembre" }, { value: 12, text: "Diciembre" }, ]; const years = [ { value: 23, text: "2023" }, { value: 24, text: "2024" }, { value: 25, text: "2025" }, { value: 26, text: "2026" }, { value: 27, text: "2027" }, { value: 28, text: "2028" }, { value: 29, text: "2029" }, { value: 30, text: "2030" }, { value: 31, text: "2031" }, { value: 32, text: "2032" }, ]; const numberRegex = /^\d*$/; const nameRegex = /[a-zA-Z]$/; export const CardsPage = () => { const { cards, isLoading } = useSelector((state) => state.user); const dispatch = useDispatch(); const navigate = useNavigate(); const [open, setOpen] = useState(false); const [rotateCard, setRotateCard] = useState(false); const { getFieldProps, handleSubmit, handleReset, errors, touched, values } = useFormik({ initialValues: { number: "", name: "", expiryMonth: "", expiryYear: "", cvc: "", }, validationSchema: Yup.object({ number: Yup.string() .required("Campo requerido") .length(16, "Completa el número") .matches(numberRegex, "No es un númro válido"), name: Yup.string() .required("Campo requerido") .matches(nameRegex, "No es un nombre válido") .min(3, "Mínimo 3 caracteres") .max(30, "Máximo 30 caracteres"), expiryMonth: Yup.number().required("Campo requerido"), expiryYear: Yup.number().required("Campo requerido"), cvc: Yup.string() .required("Campo requerido") .matches(numberRegex, "No es un cvc válido") .min(3, "Mínimo 3 caracteres"), }), onSubmit: (values, { resetForm }) => { const newCard = { ...values, }; dispatch(startAddingNewCard(newCard)); handleCloseForm(); resetForm(); }, onReset: () => { handleCloseForm(); }, }); const handleRotateBackCard = () => { setRotateCard(true); }; const handleRotateFrontCard = () => { setRotateCard(false); }; const handleOpenForm = () => { setOpen(true); }; const handleCloseForm = () => { setOpen(false); }; return ( <Box sx={{ minHeight: "80vh" }}> <IconButton sx={{ marginBlock: 1 }} onClick={() => navigate(-1)}> <ArrowBackIosIcon /> </IconButton> <Box sx={{ margin: "10px auto 50px auto", maxWidth: 720 }}> <Typography sx={{ fontSize: "18px", fontWeight: "bolder", mb: 2 }}> Tarjetas </Typography> <Paper sx={{ padding: 2, display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 2, backgroundColor: "white.main", }} > <Box sx={{ display: "flex", flexDirection: "column", gap: 1, width: "100%", }} > {isLoading ? ( <> <Skeleton variant="rectangular" width={"100%"} height={84} /> <Skeleton variant="rectangular" width={"100%"} height={84} /> <Skeleton variant="rectangular" width={"100%"} height={84} /> </> ) : cards.length < 1 ? ( <Alert severity="info" variant="filled"> No tienes ninguna tarjeta, agregá una </Alert> ) : ( cards.map((card) => { return ( <Box sx={{ width: "100%", padding: 2, display: "flex", gap: 1, borderRadius: "10px", border: "1px solid #adadad", }} key={card.id} > <Box> <CreditCardIcon /> </Box> <Box sx={{ display: "flex", flexDirection: "column", gap: 1, width: "100%", }} > <Typography> Terminada en {card.number.split("").splice(12)} </Typography> <Box> <Typography sx={{ textTransform: "capitalize", fontSize: "12px", color: "GrayText", }} > Vencimiento:{" "} {card.expiryMonth < 10 ? `0${card.expiryMonth}` : card.expiryMonth} /{card.expiryYear} </Typography> </Box> </Box> <IconButton onClick={() => dispatch(startDeletingCard(card.id))} sx={{ height: "max-content", color: "primary.main" }} title="Eliminar" aria-label="Eliminar Direccion" > <DeleteIcon /> </IconButton> </Box> ); }) )} </Box> <Button startIcon={<AddCardIcon />} sx={{ marginBlock: 1 }} onClick={handleOpenForm} > Agregar nueva tarjeta </Button> <Dialog open={open}> <DialogTitle>Nueva Tarjeta</DialogTitle> <DialogContent> <DialogContentText> No utilices tu información verdadera, este sitio web es un proyecto personal </DialogContentText> <CreditCard number={values.number} name={values.name} expiryMonth={values.expiryMonth} expiryYear={values.expiryYear} cvc={values.cvc} rotateCard={rotateCard} /> <Box component={"form"} onSubmit={handleSubmit} onReset={handleReset} sx={{ display: "flex", flexDirection: "column", gap: 2, marginBlock: 2, width: "100%", maxWidth: "500px", }} > <Box sx={{ display: "flex", gap: 1, flexDirection: { xs: "column", sm: "row" }, }} > <TextField label="Número de la tarjeta" variant="outlined" fullWidth inputProps={{ maxLength: 16, }} {...getFieldProps("number")} error={errors.number && touched.number} helperText={touched.number && errors.number} /> <TextField label="Nombre del titular" variant="outlined" fullWidth {...getFieldProps("name")} error={errors.name && touched.name} helperText={touched.name && errors.name} /> </Box> <Box sx={{ display: "flex", gap: 1, flexDirection: { xs: "column", sm: "row" }, }} > <TextField label="Mes de vencimiento" variant="outlined" fullWidth select {...getFieldProps("expiryMonth")} error={errors.expiryMonth && touched.expiryMonth} helperText={touched.expiryMonth && errors.expiryMonth} > {months.map((month) => { return ( <MenuItem key={month.value} value={month.value}> {month.text} </MenuItem> ); })} </TextField> <TextField label="Año de vencimiento" variant="outlined" fullWidth select {...getFieldProps("expiryYear")} error={errors.expiryYear && touched.expiryYear} helperText={touched.expiryYear && errors.expiryYear} > {years.map((year) => { return ( <MenuItem key={year.value} value={year.value}> {year.text} </MenuItem> ); })} </TextField> </Box> <TextField label="CVC" variant="outlined" fullWidth inputProps={{ maxLength: 3, }} onMouseEnter={handleRotateBackCard} onMouseLeave={handleRotateFrontCard} {...getFieldProps("cvc")} error={errors.cvc && touched.cvc} helperText={touched.cvc && errors.cvc} /> <Box sx={{ display: "flex", flexDirection: { xs: "column", sm: "row", gap: "10px" }, justifyContent: "flex-end", }} > <Button type="submit" variant="contained" endIcon={<SaveIcon />} > Guardar </Button> <Button variant="outlined" type="reset" endIcon={<DoDisturbIcon />} > Cancelar </Button> </Box> </Box> </DialogContent> </Dialog> </Paper> </Box> </Box> ); };
import { Body, Controller, Get, Param, ParseUUIDPipe, Post, UsePipes, ValidationPipe, } from '@nestjs/common'; import { DogsService } from './dogs.service'; import { createDogDto } from '../common/dtos/dogsDto/create-dog.dto'; @Controller('dogs') export class DogsController { constructor( private readonly dogsService: DogsService ){} @Get() getAllDogs() { return this.dogsService.findAll(); } @Get(':id') getDogById(@Param('id', ParseUUIDPipe) id: string){ return this.dogsService.findOne(id); } @Post() @UsePipes(ValidationPipe) createDog(@Body() createDogsDto: createDogDto){ return this.dogsService.create(createDogsDto); } }
<?php namespace CCETC\DirectoryBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class SignupFormType extends ListingFormType { protected $classPath; protected $container; protected $registrationSetting; /** * @param string $classPath The Listing class name */ public function __construct($classPath, $container) { $this->classPath = $classPath; $this->container = $container; $this->registrationSetting = $this->container->getParameter('ccetc_directory.registration_setting'); } public function buildForm(FormBuilderInterface $builder, array $options) { $builder = parent::buildForm($builder, $options); if($this->registrationSetting != "none") { if($this->registrationSetting == "optional") $passwordRequired = false; else $passwordRequired = true; $builder ->add('password1', 'password', array('required' => $passwordRequired, 'label' => 'Account Password', 'property_path' => false)) ->add('password2', 'password', array('required' => $passwordRequired, 'label' => 'Verify Password', 'property_path' => false)) ; } } // NOTE: this still needs to appear here, even though it's in the parent class... Not sure why, but the form doesn't treat the data as an object when handling public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => $this->classPath, 'timed_spam' => true, 'honeypot' => true, )); } public function getFieldsets() { $fieldsets = parent::getFieldsets(); if($this->registrationSetting != "none") { $fieldsets['Basic Information'][] = 'password1'; $fieldsets['Basic Information'][] = 'password2'; } return $fieldsets; } public function getName() { return 'ccetc_directory_signup'; } }
import React, { forwardRef, useState } from 'react'; import styled, { css } from 'styled-components'; import VisibilityIcon from 'images/visibility.svg'; import VisibilityOffIcon from 'images/visibility_off.svg'; import { TextSpanStyle } from 'styles/styles'; import { LabelStyle, InputStyle, ContainerIcon, ContainerInput, iconStyle, } from './InputUIStyled'; import { ReactComponent as Send } from 'images/send.svg'; const VisibilityIconStyle = styled(VisibilityIcon)` ${iconStyle}; `; const VisibilityOffIconStyle = styled(VisibilityOffIcon)` ${iconStyle}; `; export const InputUI = forwardRef((props, ref) => { const { type, label, id, name, helperText, error, fullWidth, disabled, register, width, icon, value, onChange, onFocus, readOnly, defaultValue, placeholder, small, hidden, labelSize, AutoComplete, fg, onClick, customIcon, cleareApperance = false, } = props; const InputComponent = getInputComponent(type); return ( <LabelStyle fullWidth={fullWidth} fg={fg} width={width} labelSize={labelSize} hidden={hidden} > {label} <ContainerInput> <InputComponent ref={ref} type={type || 'text'} disabled={disabled} name={name} register={register} error={error} icon={icon} value={value} onChange={onChange} onFocus={onFocus} readOnly={readOnly ? true : false} defaultValue={defaultValue} placeholder={placeholder} small={small} id={id} autoComplete={AutoComplete} onClick={onClick} cleareApperance={cleareApperance} /> {helperText && ( <TextSpanStyle color='#7a7a7a' size={12}> {helperText} </TextSpanStyle> )} <TextSpanStyle color='red' size={12}> {error?.message && error.message} </TextSpanStyle> {customIcon && customIcon} </ContainerInput> </LabelStyle> ); }); const getInputComponent = (type) => { switch (type) { case 'password': return InputPassword; default: return InputCustom; } }; const InputPassword = forwardRef((props, ref) => { const { type, disabled, name, register, error, value, onChange, small, id } = props; const [currentType, setCurrentType] = useState(type); const showPassword = () => { setCurrentType(currentType === 'password' ? 'text' : 'password'); }; return ( <ContainerIcon> <InputStyle ref={ref} type={currentType} disabled={disabled} name={name} {...register} error={error} value={value} onChange={onChange} $small={small} id={id} /> {currentType === 'password' ? ( <VisibilityOffIconStyle onClick={showPassword} /> ) : ( <VisibilityIconStyle onClick={showPassword} /> )} </ContainerIcon> ); }); const InputCustom = forwardRef((props, ref) => { const { type, id, name, disabled, register, error, icon, value, onChange, onBlur, onFocus, readOnly, defaultValue, placeholder, small, AutoComplete, onClick, cleareApperance, } = props; return ( <ContainerIcon error={error}> <InputStyle error={error} ref={ref} type={type} disabled={disabled} name={name} {...register} icon={Boolean(icon)} value={value} onChange={onChange} onFocus={onFocus} readOnly={readOnly} defaultValue={defaultValue} placeholder={placeholder} $small={small} id={id} autoComplete={AutoComplete && 'off'} onClick={onClick} $cleareApperance={cleareApperance} /> {icon && iconVariant[icon]} </ContainerIcon> ); }); const SendStyle = styled(Send)` ${iconStyle}; `; const iconVariant = { send: <SendStyle />, };
<template> <nav class="flex" aria-label="Breadcrumb"> <ol role="list" class="flex items-center space-x-4"> <li> <div> <button @click="redirectToPage('dashboard')" class="text-gray-400 hover:text-gray-500" v-if="pages"> <HomeIcon class="h-5 w-5 flex-shrink-0" aria-hidden="true" /> <span class="sr-only">Home</span> </button> <button @click="redirectToPage('dashboard')" class="text-indigo-500 hover:text-indigo-600" v-else> <HomeIcon class="h-5 w-5 flex-shrink-0" aria-hidden="true" /> <span class="sr-only">Home</span> </button> </div> </li> <li v-for="page in pages" :key="page.name"> <div class="flex items-center"> <ChevronRightIcon class="h-5 w-5 flex-shrink-0 text-gray-400" aria-hidden="true" /> <button type="button" @click="redirectToPage(page.href)" :class="page.current ? 'font-semibold text-indigo-500 hover:text-indigo-600' : 'font-normal'" class="ml-4 text-sm font-medium text-gray-500 hover:text-gray-700" :aria-current="page.current ? 'page' : undefined">{{ page.name }} </button> </div> </li> </ol> </nav> </template> <script setup lang="ts"> import { ChevronRightIcon, HomeIcon } from '@heroicons/vue/20/solid'; import { Breadcrumb } from '@/types/breadcrumb'; import { router } from '@inertiajs/vue3'; const props = defineProps({ breadcrumbs: Array<Breadcrumb>, }); function redirectToPage(href: string) { router.get(route(href)); } const pages = props.breadcrumbs; </script>
import 'package:flutter/material.dart'; class LoginTextFormField { static loginTextFormField( { // required bool themeFlag, required TextEditingController textEditingController, required String hintText, required bool obscureText, required Icon prefixIcon, String? Function(String?)? validator, Function(String)? onChanged, required ThemeData themeData}) { return TextFormField( enableInteractiveSelection: true, onTapOutside: (event) { FocusManager.instance.primaryFocus?.unfocus(); }, controller: textEditingController, validator: validator, obscureText: obscureText, style: TextStyle( color: themeData.colorScheme.onPrimary, // fontFamily: AppFonts.contax, ), onChanged: onChanged, decoration: InputDecoration( prefixIcon: prefixIcon, fillColor: themeData.colorScheme.primary, filled: true, enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: themeData.colorScheme.shadow), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: themeData.colorScheme.shadow)), hintText: hintText, hintStyle: TextStyle(color: themeData.hintColor)), ); } }
import moment from 'moment'; import 'moment/locale/es'; moment.locale('es'); import { useAssets } from 'vStore/assets'; import { useOverlays, setDay, setRoom, setDayRoom } from 'vStore/overlays'; import { useRef, useState } from 'preact/hooks'; export default function Days({ showDay = () => {} }) { const { rooms } = useAssets(); var stays = []; rooms?.forEach((room) => { room.stays && stays.push(...room.stays); }); const minDay = moment.min(...stays.map((stay) => moment(stay.range[0]))); const maxDay = moment.max(...stays.map((stay) => moment(stay.range[1]))); return ( <div style="display:flex;flex-direction:column;overflow-y:hidden;max-height:100%;"> <div style="padding:5px;background:rgb(15,15,15); border-bottom:2px solid rgb(60,60,60); filter: drop-shadow(0 0 0.4rem rgba(5,5,5,0.95)); z-index:1; " > <b style="padding:5px;">{'📅 CALENDARIO'}</b> <div style="padding:5px; padding-right:25px; display:flex;position:sticky;top:0px;z-index:1000;" > <b style="flex:1;">{'DIA'}</b> <b style="flex:1;">{'CAMAS DISPONIBLES'}</b> </div> </div> <div style="overflow-y:auto;"> {[...Array(maxDay.diff(minDay, 'days') + 1).keys()] .reverse() .map((diff) => { var totalShared = 0; var totalPrivate = 0; var totalPrivatePartial = 0; const day = moment(minDay).add(diff, 'days').format('YYYY-MM-DD'); const fromToday = moment(day).fromNow(); const daysFromToday = moment(day).diff( moment().format('YYYY-MM-DD'), 'days' ); var checkins = 0; var checkouts = 0; var p_checkins = 0; var p_checkouts = 0; rooms?.map((room) => { const thing = []; room.stays?.forEach((stay) => { const fromStart = moment(stay.range[0]).diff(day, 'days'); const toEnd = moment(stay.range[1]).diff(day, 'days'); if (fromStart < 0 && toEnd > 0) { thing.push(stay); } else { fromStart == 0 && checkins++; toEnd == 0 && checkouts++; fromStart == 0 && !stay.checkin && p_checkins++; toEnd == 0 && !stay.checkout && p_checkouts++; } }); const availableLocations = room.info.locations - thing.length; // console.log('avail', availableLocations); if (availableLocations > 0) { !room.info.isPrivate ? (totalShared += availableLocations) : availableLocations == room.info.locations ? (totalPrivate += availableLocations) : (totalPrivatePartial += availableLocations); } }); return ( <div style={`${ daysFromToday == 0 ? 'background:rgb(62,180,137);color:black;position:sticky;top:0px;bottom:0px;' : '' };padding:0px;border-bottom:solid 2px rgba(100,100,100,0.6);" `} onClick={() => { setDayRoom(day, 'all'); // overlayByDay.current.open(); }} > <div style="padding:3px;background:rgba(50,50,50,0.1);display:flex;gap:10px;border-bottom:2px solid rgba(20,20,20,0.3);"> <div style="flex:1;">{`IN: ${checkins}`}</div> <div style="flex:1;">{`OUT: ${checkouts}`}</div> <div style="flex:1;"> {p_checkins > 0 && daysFromToday <= 0 && `⚠️ IN: ${p_checkins}`} </div> <div style="flex:1;"> {p_checkouts > 0 && daysFromToday <= 0 && `⚠️ OUT: ${p_checkouts}`} </div> </div> <div style="padding:5px;display:flex;"> <div style="flex:1;"> {`${day} `} <div> <b> {daysFromToday == 0 ? 'HOY' : daysFromToday == 1 ? 'MAÑANA' : daysFromToday == 2 ? 'PASADO MAÑANA' : daysFromToday == -1 ? 'AYER' : daysFromToday == -2 ? 'ANTEAYER' : ''} </b> {` ${moment(day).format('dddd').toUpperCase()}`} </div> <div>{`${fromToday}`}</div> </div> {true && ( <div style="flex:1;"> <div>{totalShared + ' compartidas'}</div> <div> {totalPrivate + ' privadas'}</div> <div>{totalPrivatePartial + ' privadas parciales'}</div> </div> )} </div> </div> ); })} </div> </div> ); }
// const persona = { // nombre: 'Freddy' // }; //console.log(persona.nombre); //notación de corchetes //console.log(persona['nombre']); // persona.apellido = 'Kruger'; // console.log(persona); // persona['apellido'] = 'Kruger'; // //console.log(persona); // persona.edad = 15; // //console.log(persona); // persona.saludar = function(nombre){ // console.log(`Hola ${nombre}`); // }; // //persona.saludar('Rafita'); // const {nombre, saludar, apellido} = persona; // console.log(apellido,'destructuring'); // const personajes = ['item1', 'item2','item3']; // const [] = personajes; //CON OBJETOS function newKoders() { let exitFlag = false; let dbKoders =[]; let numKoders = 0; do{ let initialData = prompt('¿Cuántos koders guardarás?: \n X para salir'); if (initialData === 'X' || initialData === 'x') { console.log('¡Hasta pronto!'); exitFlag = true; }else{ numKoders = Number(initialData); if(numKoders > 10){ console.log(`¡${numKoders}!. Debes estar bromeando, intenta nuevamente...`); }else if(numKoders > 5 && numKoders <=10){ console.log(`¡${numKoders}!. Aún es demasiado, intenta con 5 o menos...`); }else if(numKoders >=1 && numKoders <= 5){ for(let i=1;i<=numKoders;i++){ const nameKoder = prompt('Ingresa el nombre completo del Koder: ' + i).trim(); let dividedName = nameKoder.split(' '); let first = dividedName[0].charAt(0).toUpperCase(); let second = dividedName[1].charAt(0).toUpperCase(); let buildData = { id:i, nombre:dividedName[0], apellidos:dividedName[1], iniciales:`(${first}${second})` }; dbKoders.push(buildData); } exitFlag = true; }else{ console.log(`Datos inválidos, intenta nuevamente...`); } } }while(exitFlag != true); if(dbKoders.length === 0){ return `Sin datos de salida`; }else{ return dbKoders; } } //console.log(newKoders());
package com.example.jetpack.architecturecomponent.uilibs.lifecycle import android.app.Activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.* import com.example.jetpack.R /** * */ class HandlerLifeCircle1Activity : Activity(), LifecycleOwner { private lateinit var lifecycleRegistry: LifecycleRegistry override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_handler_life_circle1) lifecycleRegistry = LifecycleRegistry(this) lifecycleRegistry.currentState = Lifecycle.State.CREATED lifecycle.addObserver(LifecycleEventObserver { lifecycleOwner: LifecycleOwner, event: Lifecycle.Event -> println("HandlerLifeCircle1Activity event-----${event}()----currentState----${lifecycleOwner.lifecycle.currentState}") }) } public override fun onStart() { super.onStart() lifecycleRegistry.currentState = Lifecycle.State.STARTED } override fun onResume() { super.onResume() lifecycleRegistry.currentState = Lifecycle.State.RESUMED } override fun onPause() { super.onPause() lifecycleRegistry.currentState = Lifecycle.State.STARTED } override fun onStop() { super.onStop() lifecycleRegistry.currentState = Lifecycle.State.CREATED } override fun onDestroy() { super.onDestroy() lifecycleRegistry.currentState = Lifecycle.State.DESTROYED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } }
package com.green.ziptest import android.graphics.Color import android.os.Bundle import android.text.format.Formatter import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.lang.StringBuilder import java.util.zip.ZipEntry import java.util.zip.ZipInputStream class MainActivity : AppCompatActivity() { private lateinit var text: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) text = findViewById(R.id.text) findViewById<Button>(R.id.open_test).setOnClickListener { openZip("windows.zip") } findViewById<Button>(R.id.open_yii).setOnClickListener { openZip("yii.zip") } } private fun openZip(file: String) { val color = obtainStyledAttributes(intArrayOf(com.google.android.material.R.attr.colorOnSurface)).getColor(0, Color.MAGENTA) text.setTextColor(color) text.text = "Loading..." assets.open(file).use { inputStream -> val sb = StringBuilder() sb.appendLine("*** $file\n") try { val zip = ZipInputStream(inputStream) while (true) { val entry: ZipEntry = zip.nextEntry ?: break val content = Formatter.formatFileSize(this, entry.size) sb.appendLine("${entry.name}: $content") } val color = obtainStyledAttributes(intArrayOf(android.R.attr.colorPrimary)).getColor(0, Color.MAGENTA) text.setTextColor(color) } catch (e: Exception) { val color = obtainStyledAttributes(intArrayOf(android.R.attr.colorError)).getColor(0, Color.MAGENTA) text.setTextColor(color) sb.append(e.message) } text.text = sb.toString() } } }
# 제대로-파는-html-css https://www.inflearn.com/course/%EC%A0%9C%EB%8C%80%EB%A1%9C-%ED%8C%8C%EB%8A%94-html-css # note 강의홈 : https://www.yalco.kr/lectures/html-css/ # 온라인 에디터 JSFiddle : https://jsfiddle.net/ CodePen : https://codepen.io/ HTML CSS JavaScript : https://html-css-js.com/ # Section 0. 인트로 # Section 1. <갖다 놓는> HTML ## 제목과 본문 ! + `Tab` : HTML 기본틀 생성 ## 종류와 중요도에 따른 태그 ## strong 태그 vs. em 태그 비교 https://developer.mozilla.org/ko/docs/Web/HTML/Element/strong#%3Cem%3E_vs._%3Cstrong%3E strong : 중요한 내용 em : 강세 ## 첨자 태그 sup : 지수, 서수 sub : 각주, 변수, 화학식 ## 밑줄 태그와 취소선 태그 u : 철자 오류 표시 s : 더 이상 유효하지 않은 정보 표시 ## 인용된 콘텐츠 문자 entity name 목록 보기 : https://html.spec.whatwg.org/multipage/named-characters.html blockquote : 비교적 긴 인용문에 사용 cite : 저작물의 출처 표기, 속성/태그 둘 다 사용가능 q : 비교적 짧은 인용문에 사용 mark : 인용문 중 하이라이트 또는 사용자 행동과 연관된 곳 표시 abbr : 준말/머릿글자 표시 ```html <p> <strong>abbr</strong> 태그를 사용하여<abbr title="HyperText Markup Language">HTML</abbr>을 표기한 문단입니다. 소스 보기로 코드륵 확인해부세요! </p> ``` ## ul, ol, li 웹 상에서 나열되는 모든 요소들을 표현 ul : unordered list ol : ordered list li : 목록 아이템, ul, ol 의 1촌 자식은 오직 li 만 가능 ## dl, dt, dd dt 와 dd 는 n:n 관계가 가능 dt : 용어 dd : 정의 ## 이미지 넣기 ```html <img src="(이미지 파일 경로)" alt="(대체 텍스트)" title="(툴팁 텍스트)"> ``` - src : 원본파일 경로, 절대경로 또는 상대경로 - alt : 대체 텍스트 스크린 리더, 원본파일 무효시 - title : 툴팁 alt의 대체제나 반복이 되어서는 안됨 - width : 너비 픽셀 단위의 정수 - height : 높이 픽셀 단위의 정수 ## 무료 이미지 사이트 Pixabay : https://pixabay.com/ Unsplash : https://unsplash.com/ ## 맵 기능 ```html <img src="./map.png" alt="맵" usemap="#image-map"> <map name="image-map"> <area target="_blank" alt="Google" title="Google" href="https://www.google.com" coords="141,140,96" shape="circle"> <area target="_blank" alt="Apple" title="Apple" href="https://www.apple.com" coords="332,50,510,227" shape="rect"> <area target="_blank" alt="Microsoft" title="Microsoft" href="https://www.microsoft.com" coords="650,51,598,139,650,229,751,228,802,141,753,52" shape="poly"> </map> ``` 오늘날에는 잘 사용되지 않음 이미지 맵 생성사이트 : https://www.image-map.net/ ## 테이블 <h3>⚠️ <code>&lt;table&gt;</code>은 <strong>표</strong> 용도로만 사용할 것! - <em><s>레이아웃</s></em></h3> - `<table>` : 테이블 - `<caption>` : 표 설명 또는 제목 선택사항 - `<tr>` : 테이블의 행 - `<td>` : 테이블의 데이터 셀 - `<thead>` : 테이블의 헤더 부분, tbody : 앞에 와야 함 - `<tbody>` : 테이블의 본문 본 내용을 담음 - `<tfoot>` : 테이블의 푸터 부분 - `<tbody>` : 뒤에 와야 함 - `<th>` : 열 또는 행의 헤더 scope 속성으로 row, col 중 선택 - colspan : 열 병합 - rowspan : 행 병합 - `<colgroup>` : 표에 열을 묶어서 속성 부여, <caption>보다 뒤, 그 외 요소보다 앞에 와야 함 - `<col>` : 열의 묶음, span 속성으로 열 수 지정 ## 링크 자막 달기 : https://www.easy-subtitle.com/ target 속성값 - _self : 현재 창 기본 - _blank : 새 창, 텍스트나 내부 이미지의 alt 등으로 명시 필요 - _parent : 부모 프레임, `<iframe>` 사용시 - _top : 최상위 프레임, `<iframe>` 사용시 ## address ```html <h1>Contacts</h1> <address> 웹사이트 주소: <a href="https://www.yalco.kr">yalco.kr</a> <br> 오피스: 전산시 개발구 코딩동 123번길 45 <br> 전화 <a href="tel:010-1234-5678">010-1234-5678</a> <br> 이메일: <a href="mailto:yalco@kakao.com">yalco@kakao.com</a> </address> ``` ## 입력받기 `id` 는 페이지마다 고유한 속성이어야 함 <table> <thead> <tr> <th align="left">태그</th> <th align="left">설명</th> <th align="left">비고</th> </tr> </thead> <tbody> <tr> <td align="left"><code>&lt;form&gt;</code></td> <td align="left">정보를 제출하기 위한 태그들을 포함</td> <td align="left"><code>autocomplete</code> 속성: 자동완성 여부 (기본: <code>on</code>)</td> </tr> <tr> <td align="left"><code>&lt;input&gt;</code></td> <td align="left">입력을 받는 요소</td> <td align="left"><code>type</code> 속성을 통해 다양화</td> </tr> <tr> <td align="left"><code>&lt;label&gt;</code></td> <td align="left">인풋 요소마다의 라벨</td> <td align="left"><code>for</code> 속성값을 인풋 요소의 <code>id</code>와 연결. 인풋의 <strong>클릭 영역 확장</strong></td> </tr> <tr> <td align="left"><code>&lt;button&gt;</code></td> <td align="left">버튼</td> <td align="left"><code>type</code> 속성에 <code>submit</code>(제출), <code>reset</code>(초기화), <code>button</code>(기본 동작 없음)</td> </tr> <tr> <td align="left"><code>&lt;fieldset&gt;</code></td> <td align="left">폼 태그 내 입력요소와 라벨들을 그룹화</td> <td align="left"><code>disabled</code> 속성: 포함된 입력요소 비활성화</td> </tr> <tr> <td align="left"><code>&lt;legend&gt;</code></td> <td align="left">필드셋 요소의 제목 또는 설명</td> <td align="left"></td> </tr> </tbody> </table> ## input input : https://developer.mozilla.org/ko/docs/Web/HTML/Element/Input ## 시간 관련 타입 <p>👉 <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local" target="_blank">datetime-local</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/month" target="_blank">month</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time" target="_blank">time</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/week" target="_blank">week</a> </p> ## datalist select 와 유사한데, 입력도 받을 수 있음 ```html <datalist id="jobs"> <option value="학생"></option> <option value="디자이너"></option> <option value="퍼블리셔"></option> <option value="개발자"></option> </datalist> ``` ## pre HTML 내에 입력한 그대로 보이는 태그, ASCII art 사용 시 등에 사용 ## div, span # Section 2. <꾸미는> CSS ```css /* 모든 요소 선택 */ * { font-weight: bold; color: darkorange; } /* 같은 선택자의 경우 뒤에 오는 것이 우선순위 높음 */ * { color: plum; } /* 태그 선택자 */ p { color: olivedrab; } /* class 선택자 */ /* 태그보다 우선순위 높음 */ /* 페이지상의 여러 요소가 같은 class를 가질 수 있음 */ .blue { color: lightblue; } /* 다른 선택자에 이어붙일 수 있음(태그, 클래스 등...) */ /* 선택자는 구체적일수록 우선순위 높음 */ p.blue { color: slateblue; } .blue.dark { color: mediumblue; } p.blue.dark { color: darkblue; } /* id 선택자 */ /* class보다 우선순위 높음 */ /* id는 페이지상에서 요소마다 고유해야 함 */ #red { color: tomato; } /* 그룹 선택자 */ span, .dark, #red { text-decoration: underline; } ``` ```css /* 자손 결합자 */ .outer li { color: olivedrab; } /* 자식(1촌 자손) 결합자 */ .outer > li { color: dodgerblue; } .outer > li li { text-decoration: underline; } /* 뒤따르는 모든 동생들 결합자 */ .starter ~ li { font-style: italic; } /* 뒤따르는 바로 다음 동생 결합자 */ .starter + li { font-weight: bold; } /* 첫 번째, 마지막 요소 가상 클래스 */ ol li:first-child, ol li:last-child { color: yellowgreen; } /* ~가 아닌 요소 가상 클래스 */ .outer > li:not(:last-child) { text-decoration: line-through; } ul:not(.outer) li { font-weight: bold; } /* ~번째 요소 가상 클래스 */ /* #, #n, #n+#, odd, even 등 시도해보기 */ ol li:nth-child(3) { font-weight: bold; color: deeppink; } /* 마우스오버 가상 클래스 */ li:hover { font-weight: bold; color: blue; } ``` https://flukeout.github.io/ ## font-size px는 절대값으로서 픽셀 단위입니다. 100%는 1em으로, 이들은 부모 요소와의 상대적 크기를 나타내죠. rem은 html 요소와의 상대적 크기를 가지므로, 요소의 중첩에 영향을 받지 않습니다. pt는 1인치/72로, 프린트할 컨텐츠에 사용됩니다. ## color https://developer.mozilla.org/ko/docs/Web/CSS/color_value https://www.google.com/search?q=color+picker&oq=color+picker&aqs=chrome..69i57.144j0j4&sourceid=chrome&ie=UTF-8 ## 인라인요소와 블록요소 | | inline | block | inline-block | |----------------------|------------------|---------------|--------------| | 기본 너비 | 컨텐츠만큼 | 부모의 너비만큼 | 컨텐츠만큼 | | width, height 속성 | 무시 | 적용 | 적용 | | 가로공간 차지 | 공유 | 독점 | 공유 | | margin 속성 ( 바깥쪽 여백 ) | 가로만 적용 | 모두 적용 (상하 상쇄) | 모두 적용 | | adding 속성 ( 안쪽 여백 ) | 가로만 적용, 세로는 배경색만 | 모두적용 | 모두 적용 | ## border 맨 마지막줄 제외한 border-bottom 지정 ```html <ul> <li>ul 아이템 1</li> <li>ul 아이템 2</li> <li>ul 아이템 3</li> <li>ul 아이템 4</li> <li>ul 아이템 5</li> </ul> ``` ```css ul > li:not(:last-child) { border-bottom : solid 1px black; } ``` ## positon https://www.yalco.kr/@html-css/2-9/ static은 기본값으로, 전적으로 페이지의 흐름을 따르며 top, bottom, left, right, z-index 속성의 영향을 받지 않습니다. static 으로 선언되면 자식요소의 기준이 될 수 없습니다. relative 값은 원래 위치를 기준으로 top~right 속성값이 적용되도록 합니다. 요소의 위치는 이동하지만 요소가 차지하는 공백의 위치는 유지됩니다. absolute 값은 static이 아닌 첫 부모 요소를 기준으로 top~right을 사용하여 위치를 조정할 수 있습니다. 요소는 페이지의 문서 흐름에서 벗어나, 자리를 차지하지 않게 됩니다.(위의 바깥쪽 div는 포지션이 relative로 되어 있습니다.) fixed는 부모 요소가 아닌 viewport를 기준으로 위치를 지정합니다. 스크롤에 영향을 받지 않으므로, 다이얼로그 팝업처럼 움직이지 않는 요소들에 유용하게 사용될 수 있습니다. sticky는 요소가 스크롤로 이동할 수 있는 공간을 top~right 속성으로 제한할 수 있습니다. ## flex layout https://www.yalco.kr/@html-css/2-11/ display를 flex로 지정하면 플렉스 방식으로 자식 요소들을 배치하게 됩니다. inline-flex는 해당 컨테니어 요소를 인라인으로 만든다는 차이가 있습니다. flex-direction은 내부 요소(아이템)들을 어느 축(가로 또는 세로)을 이 값에 따라 justify-content, align-items, align-content 등의 속성들이 작용할 방향이 결정됩니다. flex-wrap은 내부 요소의 갯수 X 길이가 컨테이너를 넘어갈 때 이들을 여러 줄에 걸쳐 나열할지 여부를 정합니다. justify-content는 메인 축에서 아이템들을 정렬할 방식을 정합니다. flex-start(end)는 row(column)-reverse의 영향을 받는다는 점에서 start(end)와 다릅니다. flex-가 붙은 것을 사용하세요. align-items는 수직 축(메인 축의 반대)에서 아이템들을 정렬할 방식을 정합니다. wrap으로 아이템이 여러 줄이 되면 align-content를 사용해서 보다 다양한 방식으로 정렬할 수 있습니다. gap 속성으로는 아이템간에 간격을 줄 수 있으며 두 개의 값을 넣어서 가로 간격과 세로 간격을 다르게 지정하는 것도 가능합니다. # Section 3. HTML 더 깊이 알아보기 ## 상단의 태그들 https://developer.mozilla.org/ko/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML ## 모두가 이용할 수 있는 웹사이트 https://nuli.navercorp.com/ 눈에는 안보이지만 스크린리더에서는 보이도록 할 수 있음 ```html <img src="./sr-only.png" alt=""> <p class="sr-only"> 노트북으로 뭔가 공부하고 있는 아이의 독백: 코딩을 배우면 아마 굶지는 않을거랬어. </p> <dl> <dt class="sr-only">분야</dt> <dd>프로그래밍</dd> <dt class="sr-only">종류</dt> <dd>스티커</dd> <dt class="sr-only">디자이너</dt> <dd>얄코</dd> <dt class="sr-only">제작년도</dt> <dd>2021</dd> </dl> ``` ```css .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } ``` 페이지네이션 처리 ```html <div class="page-buttons"> <button aria-label="이전 페이지로">◀</button> <button aria-label="1번째 페이지로 (현재 페이지)" class="current">1</button> <button aria-label="2번째 페이지로">2</button> <button aria-label="3번째 페이지로">3</button> <button aria-label="4번째 페이지로">4</button> <button aria-label="5번째 페이지로">5</button> <button aria-label="다음 페이지로">▶</button> </div> ``` 눈에는 보이지만 스크린리더에 감추기 role, aria-label ```html <div class="example"> <span aria-hidden="true">😀</span> 반갑습니다! </div> <p> 이모지나 SVG 요소 등을 스크린 리더에게만 감추고 싶다면 <br> <strong>aria-hidden</strong> 속성을 <em>true</em>로 만들어줍니다. </p> <br> <div class="example"> I <span role="img" aria-label="love">❤️</span> CODING! </div> <p> 특정 정보를 나타내는 이모지나 SVG 요소 등을 <br> 스크린 리더가 특정 텍스트로 읽도록 하려면 <br> <strong>role</strong> 속성으로 이미지임을 명시하고 <br> <strong>aria-label</strong> 속성에 값을 넣습니다. </p> ``` figure, figcaption ```html <figure> <img src="./sr-only.png" alt=""> <figcaption class="sr-only"> 노트북으로 뭔가 공부하고 있는 아이의 독백: 코딩을 배우면 아마 굶지는 않을거랬어. </figcaption> </figure> <br> <figure> <pre> ,d888a ,d88888888888ba. ,88"I) d a88']8i a88".8"8) `"8888:88 " _a8' .d8P' PP .d8P'.8 d) "8:88:baad8P' ,d8P' ,ama, .aa, .ama.g ,mmm d8P' 8 .8' 88):888P' ,d88' d8[ "8..a8"88 ,8I"88[ I88' d88 ]IaI" d8[ a88' dP "bm8mP8'(8'.8I 8[ d88' `" .88 ,88I ]8' .d'.8 88' ,8' I[ ,88P ,ama ,ama, d8[ .ama.g [88' I8, .d' ]8, ,88B ,d8 aI (88',88"8) d8[ "8. 88 ,8I"88[ ]88 `888P' `8888" "88P"8m" I88 88[ 8[ dP "bm8m88[.8I 8[ ]88, _,,aaaaaa,_ I88 8" 8 ]P' .d' 88 88' ,8' I[ `888a,. ,aadd88888888888bma. )88, ,]I I8, .d' )88a8B ,d8 aI "888888PP"' `8""""""8 "888PP' `888P' `88P"88P"8m" </pre> <figcaption class="sr-only"> 코카콜라 로고를 표현한 아스키 아트 </figcaption> </figure> ``` 웹 접근성 직군별 교육 : https://nuli.navercorp.com/education ## 용도에 따른 태그 사용하기 https://www.yalco.kr/@html-css-scoop/3-3/ 시맨틱 태그가 무엇인가요? - HTML5의 여러 태그들은 그 자체로 어떤 의미를 지닙니다. 이번 시간에 배울, 왼쪽 사이드바에 나열된 태그들은 기능적으로는 div 태그와 동일하지만 각각의 종류 자체가 페이지에서 해당 요소가 갖는 의미와 역할을 나타내죠. ## 가독성을 위한 이름 짓기 BEM : Block Element Modifier https://en.bem.info/ https://9elements.com/bem-cheat-sheet/ class 명의 부적절한 사례 ```css .card { /* ... */ } .card .thumb { /* ... */ } .card .thumb .image { /* ... */ } .card .body .title { /* ... */ } .card .body .list { /* ... */ } .card .body .list .list-item { /* ... */ } .card .body .list .list-item.special { /* ... */ } ``` BEM 으로 class 를 명명한 사례 ```css .card { /* ... */ } .card__thumb { /* ... */ } .card__image { /* ... */ } .card__title { /* ... */ } .card__list { /* ... */ } .card__list-item { /* ... */ } .card__list-item--special { /* ... */ } ``` Block 의 크기를 정의하는 것이 중요함 ## 기타 미디어 https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg https://www.shapedivider.app/ https://app.haikei.app/ # CSS 더 깊이 알아보기 ## 반복, 공통되는 스타일 다른 css 파일 import 하기 ```css @import url(./shared.css); ``` CSS 변수 선언하기 ```css /* 특정 요소에서만 사용될 수 있는 변수 */ u { --not-good: wavy underline orange; --wrong: wavy underline red; } .wrong { --warn: yellow; } /* 모든 요소들에서 사용될 수 있는 변수 */ :root { --font-small: 8px; --font-normal: 16px; --font-large: 24px; --font-x-large: 32px; --font-xx-large: 40px; --font-xxx-large: 48px; --font-w-normal: 400; --font-w-bold: 600; --font-w-extrabold: 900; --color-main: #FF4200; --color-sub: #865A55; --color-text: #49281C; } ``` 변수 사용하기 ```css @import url(./common.css); body { margin: 0; padding: 24px; } .not-good { text-decoration: var(--not-good); } .wrong { text-decoration: var(--wrong); } /* 스코프에 지정된 변수가 없을 경우 대안 값을 넣을 수도 있습니다. */ u { background-color: var(--warn, lightblue); } h1 { font-size: var(--font-x-large); } p { font-size: var(--font-large); color: var(--color-text); } ``` 컬러 조합 사이트 https://mycolor.space/ http://paletton.com/ https://colorhunt.co/ https://gradienthunt.com/ ## 선택자 심화 ### 특성 선택자 ```css /* 속성 값을 기준으로 선택 */ a[href="https://www.yalco.kr"] { color: #ff4e00; font-weight: bold; } /* 특정 속성이 있는 요소 선택 */ input[disabled]+label { color: lightgray; text-decoration: line-through; } /* 속성값이 특정 텍스트를 포함하는 요소 */ span[class*="item"] { text-decoration: underline; } /* 속성값이 특정 텍스트로 시작하는 요소 */ span[class^="fruit"] { color: tomato; } span[class^="vege"] { color: olivedrab; } /* 속성값이 특정 텍스트로 끝나는 요소 */ span[class$="-1"] { font-weight: bold; } ``` 특성 선택자 https://developer.mozilla.org/ko/docs/Web/CSS/Attribute_selectors ### 가상 클래스 1 ```css /* 마우스오버 */ a:hover { background-color: yellow; } /* 클릭중 */ a:active { background-color: aqua; } /* 체크된 것 */ input[type=radio]:checked+label { color: tomato; font-weight: bold; } /* 활성화된 것 */ input[type=radio]:enabled+label { text-decoration: underline; } /* 비활성화된 것 */ input[type=radio]:disabled+label { color: lightgray; text-decoration: line-through; } ``` ### 가상 클래스 2 ```css /* 인풋 등이 클릭되어 포커스된(입력을 받는) 상태 */ input[type="text"]:focus { /* border 밖의 선 (박스 요소가 아님) */ outline: 2px solid dodgerblue; } /* 필수 입력요소 */ input:required { border-color: orangered; } /* 값이 유효한 입력요소 */ input[type="email"]:valid { border-color: green; } /* 값이 무효한 입력요소 */ input[type="email"]:not(:valid) { border-color: purple; } [class*="focus"]:focus { outline: 2px solid deeppink; } .tab-focus:focus, .no-focus:focus { outline: none; } /* 탭으로 포커스된 요소에 적용 */ /* 브라우저 지원 확인 */ [class*="tab-focus"]:focus-visible { outline: 2px solid dodgerblue; } ``` ### 가상 클래스 3 ```css /* 부모 요소 내 첫 번째 ~요소 */ b:first-of-type { text-decoration: overline; } /* 부모 요소 내 마지막 ~요소 */ i:last-of-type { text-decoration: line-through; } /* 부모 요소 내 N번째 ~요소 */ b:nth-of-type(2) { text-decoration: underline; } /* 부모 요소 내 유일한 ~요소 */ div :only-of-type { text-decoration: overline line-through underline; } /* 부모 요소 내 종류 무관 유일한 요소 (독자) */ div :only-child { text-decoration: wavy underline tomato; } ``` 의사 클래스 https://developer.mozilla.org/ko/docs/Web/CSS/Pseudo-classes ### 가상 요소 ```css li.later::after { content: '다음 강좌'; margin-left: 0.6em; padding: 0.16em 0.36em; font-size: 0.72em; font-weight: bold; color: white; background-color: darkmagenta; border-radius: 0.2em; } /* 바로 앞에 가상의 요소 추가 */ li::before { content: ''; display: inline-block; margin: 0 0.4em; width: 0.8em; height: 0.8em; background-image: url(./check.png); background-size: contain; } /* 선택 영역 가상 요소 */ .orange::selection { background-color: orange; } .dark::selection { color: lightgreen; background-color: #222; } /* 플레이스홀더 가상 요소 */ input:required::placeholder { color: darkred; background-color: yellow; } ``` 의사 요소 : https://developer.mozilla.org/ko/docs/Web/CSS/Pseudo-elements ## 상속과 리셋 상속되는 속성이 있음 ### inherit 스스로의 값을 포기하고 부모로부터 받은 상속값을 적용 https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance#inherited_properties https://developer.mozilla.org/ko/docs/Web/CSS/inherit ### initial 브라우저가 부여한 값을 포기하고 각 속성의 기본값을 적용 https://developer.mozilla.org/ko/docs/Web/CSS/initial ### unset 상속되는 값이 있다면 inherit, 없다면 initial처럼 작동 ### revert unset과 같지만, 상속받지 않은 값을 초기값으로 되돌리지는 않음 ### all 속성 대부분의 속성을 inherit, initial, unset, revert값으로 지정할 수 있음 브라우저에서 지정한 기본값을 비우고 원하는 스타일로 초기화하는데 유용 ```html <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../pretty.css"> <link rel="stylesheet" href="./common.css"> <style> .parent { color: slateblue; } button:not(:first-of-type) { all: unset; } button:last-child { padding: 0.6em 1em; background-color: white; border: 2px solid #ddd; border-radius: 0.4em; cursor: pointer; box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.16); } </style> <title>hcs-04-03-06</title> </head> <body> <h1>all 속성</h1> <p> 대부분의 속성을 <em>inherit</em>, <em>initial</em>, <em>unset</em>, <em>revert</em>값으로 지정할 수 있습니다. <br> 브라우저에서 지정한 기본값을 비우고 원하는 스타일로 초기화하는데 유용합니다. </p> <div class="parent"> <span class="class-label">.parent</span> 파랑 글자색이 적용된 div <br><br> <button>all unset 적용 전 버튼</button> <br><br> <button>all unset 적용 후 버튼</button> <br><br> <button>all unset 적용 후 스타일 추가</button> </div> </body> </html> ``` ### CSS Reset https://meyerweb.com/eric/tools/css/reset/ https://necolas.github.io/normalize.css/ https://elad.medium.com/the-new-css-reset-53f41f13282e ## 벤더 프리픽스 Vendor Prefixes 각 브라우저에서 제공하는 css 속성 아직 표준화되지 않은 CSS 속성들에 사용 | 접두사 | 브라우저 | |-------------|--------------| | -webkit- | 사파리, 크롬, 오페라 | | -moz- | 파이어폭스 | |-ms- | 엣지, 익스플로러 | |-o- | 구버전 오페라 | ```css .element { -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -ms-transition: all 4s ease; -o-transition: all 4s ease; transition: all 4s ease; /* 접두사가 붙지 않은 속성은 맨 마지막줄에 붙일 것(공식 속성을 마지막에 읽을 수 있도록) */ } ``` ```css .element { background: -webkit-gradient(linear, left top, left bottom, from(white), to(black)); background: -o-linear-gradient(top, white, black); background: linear-gradient(to bottom, white, black); } ``` 벤더 프리픽스가 붙은 css 로 바꿔주는 사이트 https://autoprefixer.github.io/ ```css .element { width: 100vw; break-after: auto; tab-size: 4; writing-mode: horizontal-tb; } ``` ## 서체와 웹폰트 ### font-family 속성 ```css body { font-family: AppleSDGothicNeo-Regular,'Malgun Gothic','맑은 고딕',dotum,'돋움',sans-serif; } ``` serif : 삐침이 있음 sans-serif : 삐침이 없음 https://developer.mozilla.org/ko/docs/Web/CSS/font-family ### CSS 폰트의 한계 사용자의 컴퓨터에 있는 폰트만 실질 적용 가능 맥 사용자, 윈도우 사용자간 탑재 폰트 차이 일관성 유지 어려움 ### 웹 폰트 서버에 저장된 서체를 사용자의 컴퓨터에서 사용할 수 있도록 함 https://fonts.google.com/ https://noonnu.cc/ ### 웹폰트를 직접 배포 폰트를 다운받아서 fonts 폴더에 넣기 폰트명을 선언하고 사용 ```css @font-face { font-family: "MyNotoSans"; src: url(./fonts/NotoSansKR-Regular.otf); } ``` ## 테이블 스타일링 테이블 관련 요소들의 display에는 각각의 역할에 맞는 특수한 내부 속성들이 기본적으로 부여됩니다. https://developer.mozilla.org/ko/docs/Web/CSS/display#%EB%82%B4%EB%B6%80%EC%A0%81 이 외에도 display 속성에는 이 강좌에서 직접 다루지 않은 다양한 값들이 있습니다. ## 텍스트 심화 ### vertical-align 속성 https://developer.mozilla.org/ko/docs/Web/CSS/vertical-align#values_(inline_elements%EC%97%90%EC%84%9C) https://developer.mozilla.org/ko/docs/Web/CSS/vertical-align#values_(table_cells%EC%97%90%EC%84%9C) ### white-space 속성 https://developer.mozilla.org/ko/docs/Web/CSS/white-space ### text-overflow 속성 텍스트 줄임표 ... 표현하기 ```html <div style="text-overflow: ellipsis;"> 텍스트가 상자의 너비를 넘어갈 때 어떻게 표시될지를 지정합니다. </div> ``` ```css div { margin: 8px; padding: 16px; width: 360px; border: 2px solid lightgray; overflow: hidden; white-space: nowrap; } ``` overflow 는 hidden 또는 scroll 로, white-space 는 nowrap 으로 지정해야 합니다. ## Float 속성 float 속성에 left 또는 right 값을 주면 매우 독특한 형태와 기능을 갖게 됩니다. 먼저, 해당 요소는 '붕 뜬' 상태가 되어서, 나란히 배치된 요소들 가운데 자리를 차지하지 않게 됩니다. 때문에 다음에 오는 블록 요소들이 자리에서 밀려나지 않고, 그 아래로 들어가버리게 되죠. 그러면서도 특이하게도, 텍스트 등의 인라인 요소들은 float 요소들에 밀려나게 됩니다. 그리고 다른 float된 요소들 또한 마찬가지죠. 또한 해당 요소가 인라인일 경우 블록과 같은 속성을 갖게 되어, CSS로 높이와 너비 등을 적용할 수 있게 됩니다. 물론 float 상태가 되므로 자리는 같은 float끼리만 차지하게 되죠. clear 속성을 이전의 float 요소들과 같이, 또는 both로 적용하면 그들 밑으로 들어가지 않고 아래로 빠져나오게 됩니다. 이전 형제들에 적용된 float의 효과를 해제하는데 clear 속성을 사용한다고 기억하시면 좋습니다. 과거에 float은 페이지 레이아웃을 잡는데 다양하게 활용되었습니다. 그러나 오늘날에는 flex 등 더 좋은 방식들이 사용되기 때문에 사라져가는 추세입니다. ## Grid 레이아웃 ### 부모 적용 속성들 display : gird grid-template-columns : 열을 gird template 지정 단위 fr : 비율 gird-templete-rows : 행에 grid template 지정 gap : 아이템간의 간격 grid-auto-rows : 아이템의 높이 justify-items : gird 안에 아이템을 기본축을 따라 정렬 align-items : gird 안의 아이템을 보조축을 따라 정렬 ### 자식 적용 속성들 grid-column : 아이템이 차지하는 열 영역의 크기 grid-rows : 아이템이 차지하는 행 영역의 크기 justify-self : 아이템을 기본축을 따라 정렬 align-self : gird 안의 아이템을 보조축을 따라 정렬 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout ## 변형과 애니메이션 ### transform 속성 transform 속성은 주위 요소들에 영향을 끼치지 않으면서 요소의 모습을 바꿈 https://developer.mozilla.org/ko/docs/Web/CSS/transform ### transition 속성 transiton 속성은 CSS 값이 달라질 때 요소에 어떤 효과로 반영될지 지정합니다. 속성, 지속시간, 시간함수, 지연시간 순으로 값을 넣을 수 있습니다. 주의! 적용할 CSS 속성이 이미 기존값이 적용되어 있어야 동작합니다. 슬라이드 효과 https://developer.mozilla.org/ko/docs/Web/CSS/transition https://cubic-bezier.com/#.17,.67,.83,.67 ### animation 속성 animation 속성을 사용하면 자바스크립트 없이 요소에 애니메이션을 적용할 수 있습니다. https://developer.mozilla.org/en-US/docs/Web/CSS/animation ## 반응형 웹 ### 적응형 웹 vs 반응형 웹 || 적응형 | 반응형 | |---|---|---| |설명 |화면 크기 따라 다른 페이지를 보여줌| 화면 크기에 따라 요소들을 변화시킴| |예시 |네이버 |애플| |장점 |각 화면 크기에 집중하여 작업 가능 |하나의 페이지로 여러 크기에 대응 가능| |단점 |페이지를 두 개를 만들어야 함 |컨텐츠가 복잡할 경우 작업하기 어려움| ### 미디어 쿼리 ```html <main> <section> <h1>여러 화면크기로 살펴보세요!</h1> <div class="mobile">스마트폰</div> <div class="low-tablet">저해상도 태블릿</div> <div class="port-tablet">태블릿 세로</div> <div class="low-pc">저해상도 PC</div> <div class="high-pc">일반 PC</div> </section> </main> ``` ```css body { margin: 0; } section { display: flex; flex-direction: column; height: 100vh; color: white; align-items: center; justify-content: center; } div { display: none; font-size: 1.4em; } /* 스마트폰 */ @media (max-width: 480px) { section { background-color: tomato; } .mobile { display: inherit; } } /* 저해상도 태블릿 */ @media (min-width: 481px) and (max-width: 767px) { section { background-color: olivedrab; } .low-tablet { display: inherit; } } /* 태블릿 세로 화면 */ @media (min-width: 768px) and (max-width: 1024px) { section { background-color: darkorchid; } .port-tablet { display: inherit; } } /* 태블릿 가로 및 저해상도 노트북, PC 화면 */ @media (min-width: 1025px) and (max-width: 1280px) { section { background-color: darkorange; } .low-pc { display: inherit; } } /* 일반 노트북, PC 화면 */ @media (min-width: 1281px) { section { background-color: slateblue; } .high-pc { display: inherit; } } /* or 조건 사용 */ @media (max-width: 480px), (min-width: 1281px) { div { color: yellow; } } ``` ## 기타 속성들 ### clip과 clip-path 속성 ```css .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } ``` https://developer.mozilla.org/en-US/docs/Web/CSS/clip https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path ### scroll-snap scroll-snap-type 부모 요소에 스크롤 스냅할 방향( x | y | both )과 방식( proximity | mandatory )을 설정 - proximity: 스냅할 위치에 가까울 때 스냅 - mandatory: 항상 가까운 방향으로 스냅 scroll-snap-align 자식 요소에 스크롤 스냅될 기준선을 지정합니다. ### aspect-ratio 박스 요소의 가로 세로 비율을 지정 ### backdrop-filter 적용된 요소의 영역만큼, 그 뒤에 있는 요소에 필터를 적용합니다. -webkit- 벤더 프리픽스와 함께 사용합니다. ## 프레임워크와 라이브러리 이용하기 ### 유명 프론트엔드 프레임워크들 Bootstrap : https://getbootstrap.com/ UIkit : https://getuikit.com/ Materialize : https://materializecss.com/ Bulma : https://bulma.io/ ### 아이콘 라이브러리 Font Awesome : https://fontawesome.com/ Goodle Fonts Icons : https://fonts.google.com/icons ```html <?xml version="1.0" encoding="utf-8"?> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 48 48" style="enable-background:new 0 0 48 48;" xml:space="preserve"> <!-- 아래에 색상값과 d값을 넣으세요! --> <path style="fill: #000000;" d="" /> </svg> ``` # 파이널 프로젝트 05-practice 참조 # 참고 https://www.inflearn.com/course/%EC%A0%9C%EB%8C%80%EB%A1%9C-%ED%8C%8C%EB%8A%94-html-css
from flask import Flask, render_template, request, url_for, redirect, flash, send_from_directory from werkzeug.security import generate_password_hash, check_password_hash from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user app = Flask(__name__) app.config['SECRET_KEY'] = 'secret-key-goes-here' # CONNECT TO DB app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' db = SQLAlchemy() db.init_app(app) login_manager = LoginManager() login_manager.init_app(app) # CREATE TABLE IN DB @login_manager.user_loader def load_user(user_id): return db.get_or_404(User, user_id) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000)) # with app.app_context(): # db.create_all() @app.route('/') def home(): return render_template("index.html", logged_in=current_user.is_authenticated) @app.route('/register', methods=["GET", "POST"]) def register(): if request.method == "POST": email = request.form.get("email") res = db.session.execute(db.select(User).where(User.email == email)) user = res.scalar() if user: flash("You have already signed uup with that email, log in instead!") return redirect(url_for('login')) hash_and_salted_pwd = generate_password_hash( request.form.get("password"), method="pbkdf2:sha256", salt_length=8) new_user = User( email=request.form.get("email"), name=request.form.get("name"), password=hash_and_salted_pwd ) db.session.add(new_user) db.session.commit() login_user(new_user) return render_template(url_for("secrets"), name=request.form.get("name")) return render_template("register.html", logged_in=current_user.is_authenticated) @app.route('/login', methods=["GET", "POST"]) def login(): if request.method == "POST": email = request.form.get("email") password = request.form.get("password") res = db.session.execute(db.select(User).where(User.email == email)) user = res.scalar() if not user: flash("That email does not exist, please try again") return redirect(url_for("login")) elif not check_password_hash(user.password, password): flash("Password incorrect! try again") return redirect(url_for('login')) else: login_user(user) print(f"from login{current_user.is_authenticated}") return redirect(url_for('secrets')) print(current_user.is_authenticated) return render_template("login.html", logged_in=current_user.is_authenticated) @app.route('/secrets') @login_required def secrets(): return render_template("secrets.html", logged_in=True) @app.route('/logout') def logout(): logout_user() return redirect(url_for('home')) @app.route('/download') @login_required def download(): return send_from_directory('static', as_attachment=True, path='files/cheat_sheet.pdf') if __name__ == "__main__": app.run(debug=True)
//include library #include<iostream> using namespace std; //making of linked list class Node{ public: //declaring datadata int data; //pointers next and previous Node * next; Node * prev; //const to make values to null Node(){ next=NULL; prev=NULL; } }; class Dlinkedlist{ public: Node * head; Dlinkedlist(){ head=NULL; } void insert(int val){ //create node Node * temp=new Node; temp->data=val; //for empty node and if not applying conditions if(head==NULL){ head = temp; } else{ Node * current=head; while(current->next!=NULL) current=current->next; current->next=temp; temp->prev=current; } } //for inserting at specific position void insertAt(int val,int pos){ Node *current=head; int i=1; while(i<pos-1){ i++; current=current->next; } Node *temp= new Node; temp->data=val; temp->next=current->next; current->next=temp; temp->prev=current; temp->next->prev=temp; } //for excluding at the ends void delete1(){ Node * current=head; while(current->next->next!=NULL){ current=current->next; } Node * tail=current->next; current->next=NULL; delete tail; } //for deleting at specific positioin void deleteat(int pos){ Node * current=head; int i=1; while(i<pos-1){ current=current->next; i++; } Node * temp=current->next; current->next=current->next->next; current->next->prev=current; delete temp; } //to count the items void countitems(){ Node* current=head; int i=1; while(current->next!=NULL){ current=current->next; i++; } cout<<"The number of items are "<<i<<endl; } //for displaying void display(){ Node *current= head; Node *last; //to print in order while (current!=NULL){ cout<<current->data<<"->"; // bring last to end of list using curr last=current; current=current->next; } cout<<"NULL"; cout<<endl; // print in reverse order while(last!=NULL){ cout<<last->data<<"->"; last=last->prev; } cout<<"NULL"; cout<<endl; } }; //declaring main function int main(){ Dlinkedlist L1; L1.insert(10); L1.insert(11); L1.insert(12); L1.insert(14); L1.insert(15); L1.insert(16); L1.insert(17); L1.display(); L1.insertAt(13,4); L1.display(); L1.delete1(); L1.display(); L1.deleteat(5); L1.display(); L1.countitems(); //closing the function return 0; }