text
stringlengths
184
4.48M
use std::path::PathBuf; use crate::config; pub struct ServiceConfig { pub data_dir: PathBuf, pub repos_path: PathBuf, pub data_path: PathBuf, pub internal_path: PathBuf, pub secrets: config::secrets::Secrets, pub tokens: config::permissions::Tokens, pub projects_store: config::projects::ProjectsStore, } impl std::fmt::Debug for ServiceConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ServiceConfig") .field("data_dir", &self.data_dir) .field("repos_path", &self.repos_path) .field("data_path", &self.data_path) .field("internal_path", &self.internal_path) .field("secrets", &self.secrets) .field("tokens", &self.tokens) .field("projects_store", &"<dynamic object>") .finish() } } pub enum ActionEvent { ConfigReloaded, ProjectReloaded { project_id: String, }, DirectCall { project_id: String, trigger_id: String, }, UpdateRepos { project_id: String, repos: Vec<String>, }, } impl ServiceConfig { pub fn check_allowed<S: AsRef<str>>( &self, token: Option<S>, action: config::permissions::ActionType, ) -> bool { self.tokens.check_allowed(token, action) } } pub use dyn_obj::DynServiceConfig; mod dyn_obj { use std::path::PathBuf; use crate::config; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize)] pub struct DynServiceConfig { pub secrets: Option<config::secrets::DynSecrets>, pub internal_path: PathBuf, pub repos_path: PathBuf, pub data_path: PathBuf, } impl From<&super::ServiceConfig> for DynServiceConfig { fn from(config: &super::ServiceConfig) -> Self { Self { secrets: Some((&config.secrets).into()), internal_path: config.internal_path.clone(), repos_path: config.repos_path.clone(), data_path: config.data_path.clone(), } } } } pub mod raw { use crate::config; use dynconf::*; use serde::{Deserialize, Serialize}; use anyhow::Result; const DEFAULT_REPOS_PATH: &str = "repos"; const DEFAULT_DATA_PATH: &str = "data"; const DEFAULT_INTERNAL_PATH: &str = "internal"; const DEFAULT_DATA_DIR_EXPR: &str = "${~/.uci}"; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ServiceConfig { data_dir: Option<util::DynPath>, secrets: Option<util::Dyn<config::secrets::raw::Secrets>>, tokens: Option<util::Dyn<config::permissions::raw::Tokens>>, projects_store: util::Dyn<ProjectsStore>, } #[derive(Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] enum ProjectsStore { Static { projects: util::Dyn<util::Lazy<config::static_projects::raw::Projects>>, }, } #[async_trait::async_trait] impl util::DynValue for ServiceConfig { type Target = super::ServiceConfig; async fn load(self, state: &mut State) -> Result<Self::Target> { // ${~/.uci} -> <home>/.uci let default_data_dir = eval_string(state, DEFAULT_DATA_DIR_EXPR).await?; let data_dir = self .data_dir .load(state) .await? .unwrap_or_else(|| default_data_dir.into()); let internal_path = data_dir.join(DEFAULT_INTERNAL_PATH); let repos_path = data_dir.join(DEFAULT_REPOS_PATH); let data_path = data_dir.join(DEFAULT_DATA_PATH); state.mutate_global(config::utils::wrap_dyn_f(|mut dynconf| { dynconf.config = Some(super::DynServiceConfig { secrets: None, internal_path: internal_path.clone(), repos_path: repos_path.clone(), data_path: data_path.clone(), }); Ok(dynconf) }))?; let secrets = self.secrets.load(state).await?.unwrap_or_default(); state.mutate_global(config::utils::wrap_dyn_f(|mut dynconf| { dynconf.config.as_mut().unwrap().secrets = Some((&secrets).into()); Ok(dynconf) }))?; let tokens = self.tokens.load(state).await?.unwrap_or_default(); let projects_store = self.projects_store.load(state).await?; Ok(super::ServiceConfig { data_dir, repos_path, data_path, internal_path, secrets, tokens, projects_store, }) } } #[async_trait::async_trait] impl util::DynValue for ProjectsStore { type Target = config::projects::ProjectsStore; async fn load(self, state: &mut State) -> Result<Self::Target> { match self { ProjectsStore::Static { projects } => { let projects_store = config::static_projects::StaticProjects::new(projects.load(state).await?) .await?; config::projects::ProjectsStore::with_manager(projects_store).await } } } } }
// require("dotenv").config(); import "dotenv/config"; import "express-async-errors"; import express from "express"; import path from "path"; import errorHandler from "./middleware/errorHandler"; import { logger } from "./middleware/logger"; import cors from "cors"; import cookieParser from "cookie-parser"; import corsOptions from "./config/corsOptions"; import authRoutes from "./routes/authRoutes"; import userRoutes from "./routes/userRoutes"; import noteRoutes from "./routes/noteRoutes"; import downloadRoutes from "./routes/downloadRoutes"; import rootRoutes from "./routes/rootRoutes"; import { AppDataSource } from "./config/data-source"; //load & run passport middleware(initialize + strategies) for Oauth2/SSO import "./config/passport"; const app = express(); const PORT = process.env.PORT || 4000; //avoid 5000//used by other services eg linkedin passport //access routes+ middleware only when conn to db is established //make it an IIF (async () => { try { // create express app //initialize connection to db await AppDataSource.initialize(); console.log("Connected to Postgres"); //log req events app.use(logger); //parse data/cookie app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); //allow cross origin requests//other origins to req our api//leave black to allow all //corsOptions= { // origin: ["http://localhost:3050"], //can be an array or function for dynamic origins like below // credentials: true, //allow setting of cookies etc // optionsSuccessStatus: 200; // } //if no origin configured, it allows all origins app.use(cors(corsOptions)); /*----------------------------------------- * SERVE STATIC FILES i.e css, images or js files eg files in public or build folder ---------------------------*-------------*/ app.use("/", express.static(path.join(__dirname, "public"))); //or app.use(express.static("public"));// = 'public' means ./public /*----------------------------------------- * ROUTES ----------------------------------------*/ app.use("/api/auth", authRoutes); app.use("/api/users", userRoutes); app.use("/api/notes", noteRoutes); app.use("/api/download", downloadRoutes); /*----------------------------------------- * GENERAL ROUTES ---------------------------*-------------*/ //---------API HOME/INDEX PAGE ROUTE-------- app.use("/", rootRoutes); //---------API 404 PAGE---------------- //app works same as .use but go thru all http verbs //TS is able to infer types of req, and res since we passed the route path app.all("*", (req, res) => { res.status(404); /**check accept header to determine response //accept html else json */ if (req.accepts(".html")) { res.sendFile(path.join(__dirname, "views", "404.html")); } else if (req.accepts("json")) { res.json({ message: "404 Not Found" }); } else { res.type("txt").send("404 Not Found"); } }); /*----------------------------------------- * ERROR HANDLER//MUST BE THE LAST MIDDLEWARE ---------------------------*-------------*/ app.use(errorHandler); /*----------------------------------------- * START EXPRESS SERVER ---------------------------*-------------*/ app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); } catch (error) { console.error(error); //throw new Error("Unable to connect to db"); } })();
import Alert from "../components/Alert"; import ActionBar from "../components/ActionBar"; import ItemsGrid from "../components/ItemsGrid"; import { useQuery } from "@tanstack/react-query"; import useAxiosPrivate from "../hooks/useAxiosPrivate"; export default function Home() { const axios = useAxiosPrivate(); const { isLoading, isError, error, data } = useQuery({ queryKey: ["get_images"], queryFn: () => { return axios.get("/api/image"); }, }); return ( <> <ActionBar /> {isError ? ( <Alert variant="error" message={error.response.data.message} /> ) : ( <ItemsGrid images={isLoading ? [] : data.data} /> )} </> ); }
package mysql import ( "database/sql" "github.com/go-test/deep" "github.com/joeycumines/go-sql/export" _ "github.com/pingcap/tidb/types/parser_driver" "reflect" "strings" "testing" ) const ( schemaExample1 = `../../testdata/schema-example-1.json` schemaExample1Query = "SELECT `bs`.`_id` AS `bs`,`ap`.`_id` AS `ap`,`d`.`_id` AS `d`,`da`.`_id` AS `da`,`df`.`_id` AS `df`,`o`.`_id` AS `o`,`orf`.`_id` AS `orf`,`sm`.`_id` AS `sm`,`w`.`_id` AS `w`,`wa`.`_id` AS `wa`,`wf`.`_id` AS `wf` FROM (((((((((`big_show` AS `bs` LEFT JOIN `angryPandas` AS `ap` ON `bs`.`angryPandaId`=`ap`.`_id`) LEFT JOIN `drongos` AS `d` ON `bs`.`drongo_id`=`d`.`_id`) LEFT JOIN `drongo_arrivals` AS `da` ON `d`.`drongo_arrival`=`da`.`_id`) LEFT JOIN `foods` AS `df` ON `d`.`_id`=`df`.`drongo_id`) LEFT JOIN `outtakes` AS `o` ON `bs`.`outtake_id`=`o`.`_id`) LEFT JOIN `foods` AS `orf` ON `o`.`_id`=`orf`.`outtake_id`) LEFT JOIN `smallMongooses` AS `sm` ON `bs`.`smallMongooseId`=`sm`.`_id`) LEFT JOIN `wheelbarrows` AS `w` ON `bs`.`wheelbarrow_id`=`w`.`_id`) LEFT JOIN `wide_aunties` AS `wa` ON `w`.`wide_auntie`=`wa`.`_id`) LEFT JOIN `foods` AS `wf` ON `w`.`_id`=`wf`.`wheelbarrow_id` WHERE (bs.owo = ?) AND (`bs`.`_id` > ? OR (`bs`.`_id` <=> ? AND (`ap`.`_id` > ? OR (`ap`.`_id` <=> ? AND (`d`.`_id` > ? OR (`d`.`_id` <=> ? AND (`da`.`_id` > ? OR (`da`.`_id` <=> ? AND (`df`.`_id` > ? OR (`df`.`_id` <=> ? AND (`o`.`_id` > ? OR (`o`.`_id` <=> ? AND (`orf`.`_id` > ? OR (`orf`.`_id` <=> ? AND (`sm`.`_id` > ? OR (`sm`.`_id` <=> ? AND (`w`.`_id` > ? OR (`w`.`_id` <=> ? AND (`wa`.`_id` > ? OR (`wa`.`_id` <=> ? AND (`wf`.`_id` > ?))))))))))))))))))))) AND ((CASE WHEN sm.type IS NOT NULL THEN sm.type = 'LARGE' ELSE 1 END)) ORDER BY `bs`.`_id`,`ap`.`_id`,`d`.`_id`,`da`.`_id`,`df`.`_id`,`o`.`_id`,`orf`.`_id`,`sm`.`_id`,`w`.`_id`,`wa`.`_id`,`wf`.`_id` LIMIT 466" schemaExample1QueryWhereNoSpaceship = "WHERE (bs.owo = ?) AND (`bs`.`_id` > ? OR ((`bs`.`_id` = ? OR (? IS NULL AND `bs`.`_id` IS NULL)) AND (`ap`.`_id` > ? OR ((`ap`.`_id` = ? OR (? IS NULL AND `ap`.`_id` IS NULL)) AND (`d`.`_id` > ? OR ((`d`.`_id` = ? OR (? IS NULL AND `d`.`_id` IS NULL)) AND (`da`.`_id` > ? OR ((`da`.`_id` = ? OR (? IS NULL AND `da`.`_id` IS NULL)) AND (`df`.`_id` > ? OR ((`df`.`_id` = ? OR (? IS NULL AND `df`.`_id` IS NULL)) AND (`o`.`_id` > ? OR ((`o`.`_id` = ? OR (? IS NULL AND `o`.`_id` IS NULL)) AND (`orf`.`_id` > ? OR ((`orf`.`_id` = ? OR (? IS NULL AND `orf`.`_id` IS NULL)) AND (`sm`.`_id` > ? OR ((`sm`.`_id` = ? OR (? IS NULL AND `sm`.`_id` IS NULL)) AND (`w`.`_id` > ? OR ((`w`.`_id` = ? OR (? IS NULL AND `w`.`_id` IS NULL)) AND (`wa`.`_id` > ? OR ((`wa`.`_id` = ? OR (? IS NULL AND `wa`.`_id` IS NULL)) AND (`wf`.`_id` > ?))))))))))))))))))))) AND ((CASE WHEN sm.type IS NOT NULL THEN sm.type = 'LARGE' ELSE 1 END))" ) func TestDialect_charset(t *testing.T) { if v := (&Dialect{}).charset(); v != `utf8mb4` { t.Error(v) } if v := (&Dialect{Collation: `a`}).charset(); v != `utf8mb4` { t.Error(v) } if v := (&Dialect{Charset: `a`}).charset(); v != `a` { t.Error(v) } } func TestDialect_collation(t *testing.T) { if v := (&Dialect{}).collation(); v != `utf8mb4_bin` { t.Error(v) } if v := (&Dialect{Charset: `a`}).collation(); v != `utf8mb4_bin` { t.Error(v) } if v := (&Dialect{Collation: `a`}).collation(); v != `a` { t.Error(v) } } func TestDialect_SelectBatch_nil(t *testing.T) { if v, err := (*Dialect)(nil).SelectBatch(nil); err != nil || v != nil { t.Error(v, err) } } func TestDialect_SelectBatch_success(t *testing.T) { for _, tc := range [...]struct { Name string Dialect *Dialect Args *export.SelectBatch Snippet export.Snippet }{ { Name: `table name only with spaceship`, Dialect: &Dialect{NullSafeEqual: true}, Args: &export.SelectBatch{ Schema: jsonUnmarshalTestResource(schemaExample1, new(export.Schema)), Filters: []*export.Snippet{{SQL: `bs.owo = ?`, Args: []any{321}}}, Offset: map[string]int64{ `bs`: 42, `ap`: 6, }, Limit: 466, }, Snippet: export.Snippet{ SQL: schemaExample1Query, Args: []any{321, sql.NullInt64{Int64: 42, Valid: true}, sql.NullInt64{Int64: 42, Valid: true}, sql.NullInt64{Int64: 6, Valid: true}, sql.NullInt64{Int64: 6, Valid: true}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}}, }, }, { Name: `table name only with spaceship no offset`, Dialect: &Dialect{NullSafeEqual: true}, Args: &export.SelectBatch{ Schema: jsonUnmarshalTestResource(schemaExample1, new(export.Schema)), Filters: []*export.Snippet{{SQL: `bs.owo = ?`, Args: []any{321}}}, Limit: 466, }, Snippet: export.Snippet{ SQL: "SELECT `bs`.`_id` AS `bs`,`ap`.`_id` AS `ap`,`d`.`_id` AS `d`,`da`.`_id` AS `da`,`df`.`_id` AS `df`,`o`.`_id` AS `o`,`orf`.`_id` AS `orf`,`sm`.`_id` AS `sm`,`w`.`_id` AS `w`,`wa`.`_id` AS `wa`,`wf`.`_id` AS `wf` FROM (((((((((`big_show` AS `bs` LEFT JOIN `angryPandas` AS `ap` ON `bs`.`angryPandaId`=`ap`.`_id`) LEFT JOIN `drongos` AS `d` ON `bs`.`drongo_id`=`d`.`_id`) LEFT JOIN `drongo_arrivals` AS `da` ON `d`.`drongo_arrival`=`da`.`_id`) LEFT JOIN `foods` AS `df` ON `d`.`_id`=`df`.`drongo_id`) LEFT JOIN `outtakes` AS `o` ON `bs`.`outtake_id`=`o`.`_id`) LEFT JOIN `foods` AS `orf` ON `o`.`_id`=`orf`.`outtake_id`) LEFT JOIN `smallMongooses` AS `sm` ON `bs`.`smallMongooseId`=`sm`.`_id`) LEFT JOIN `wheelbarrows` AS `w` ON `bs`.`wheelbarrow_id`=`w`.`_id`) LEFT JOIN `wide_aunties` AS `wa` ON `w`.`wide_auntie`=`wa`.`_id`) LEFT JOIN `foods` AS `wf` ON `w`.`_id`=`wf`.`wheelbarrow_id` WHERE (bs.owo = ?) AND ((CASE WHEN sm.type IS NOT NULL THEN sm.type = 'LARGE' ELSE 1 END)) ORDER BY `bs`.`_id`,`ap`.`_id`,`d`.`_id`,`da`.`_id`,`df`.`_id`,`o`.`_id`,`orf`.`_id`,`sm`.`_id`,`w`.`_id`,`wa`.`_id`,`wf`.`_id` LIMIT 466", Args: []any{321}, }, }, { Name: `table name only with spaceship and offset all null`, Dialect: &Dialect{NullSafeEqual: true}, Args: &export.SelectBatch{ Schema: jsonUnmarshalTestResource(schemaExample1, new(export.Schema)), Filters: []*export.Snippet{{SQL: `bs.owo = ?`, Args: []any{321}}}, Offset: map[string]int64{}, Limit: 466, }, Snippet: export.Snippet{ SQL: schemaExample1Query, Args: []interface{}{321, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}}, }, }, { Name: `table name only without spaceship`, Dialect: &Dialect{}, Args: &export.SelectBatch{ Schema: jsonUnmarshalTestResource(schemaExample1, new(export.Schema)), Filters: []*export.Snippet{{SQL: `bs.owo = ?`, Args: []any{321}}}, Offset: map[string]int64{ `bs`: 42, `ap`: 6, }, Limit: 466, }, Snippet: export.Snippet{ SQL: schemaExample1Query[:887] + schemaExample1QueryWhereNoSpaceship + schemaExample1Query[1424:], Args: []interface{}{321, sql.NullInt64{Int64: 42, Valid: true}, sql.NullInt64{Int64: 42, Valid: true}, sql.NullInt64{Int64: 42, Valid: true}, sql.NullInt64{Int64: 6, Valid: true}, sql.NullInt64{Int64: 6, Valid: true}, sql.NullInt64{Int64: 6, Valid: true}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}, sql.NullInt64{Int64: 0, Valid: false}}, }, }, { Name: `simple with table schema`, Dialect: (*Dialect)(nil), Args: &export.SelectBatch{ Schema: func() *export.Schema { v, err := (&export.Template{Targets: map[string]*export.Target{`t`: { Table: export.Table{Schema: `schm`, Name: `tbl`}, PrimaryKey: `somePrimaryKey`, }}}).Schema() if err != nil { t.Fatal(err) } return v }(), }, Snippet: export.Snippet{SQL: "SELECT `t`.`somePrimaryKey` AS `t` FROM `schm`.`tbl` AS `t` ORDER BY `t`.`somePrimaryKey`"}, }, { Name: `preserves name case`, Dialect: (*Dialect)(nil), Args: &export.SelectBatch{ Schema: func() *export.Schema { v, err := (&export.Template{Targets: map[string]*export.Target{`T_A`: { Table: export.Table{Schema: `TBL_SCHEMA`, Name: `TBL_NAME`}, PrimaryKey: `SOME_PK`, }}}).Schema() if err != nil { t.Fatal(err) } return v }(), }, Snippet: export.Snippet{SQL: "SELECT `T_A`.`SOME_PK` AS `T_A` FROM `TBL_SCHEMA`.`TBL_NAME` AS `T_A` ORDER BY `T_A`.`SOME_PK`"}, }, } { t.Run(tc.Name, func(t *testing.T) { snippet, err := tc.Dialect.SelectBatch(tc.Args) if err != nil || snippet == nil { t.Fatal(snippet, err) } if snippet.SQL != tc.Snippet.SQL { expectTextFormattedSQL(t, snippet.SQL, tc.Snippet.SQL) } if diff := deep.Equal(snippet.Args, tc.Snippet.Args); diff != nil { t.Errorf("unexpected value: %#v\n%s", snippet.Args, strings.Join(diff, "\n")) } }) } } func TestDialect_SelectRows_nil(t *testing.T) { if v, err := (*Dialect)(nil).SelectRows(nil); err != nil || v != nil { t.Error(v, err) } } func TestDialect_SelectRows_success(t *testing.T) { for _, tc := range [...]struct { Name string Dialect *Dialect Args *export.SelectRows SQL string }{ { Name: `table name only`, Dialect: &Dialect{}, Args: &export.SelectRows{ Schema: &export.Schema{ PrimaryKeys: map[export.Table]string{ {Name: `tAblE_NAmE`}: `ColuMn_naME`, }, }, Table: export.Table{Name: `tAblE_NAmE`}, IDs: []int64{4, 2, 91, -233}, }, SQL: "SELECT * FROM `tAblE_NAmE` WHERE `ColuMn_naME` IN (4,2,91,-233) ORDER BY `ColuMn_naME`", }, { Name: `table schema and name`, Dialect: &Dialect{}, Args: &export.SelectRows{ Schema: &export.Schema{ PrimaryKeys: map[export.Table]string{ {Schema: `sChemEa_saD`, Name: `tAblE_NAmE`}: `ColuMn_naME`, }, }, Table: export.Table{Schema: `sChemEa_saD`, Name: `tAblE_NAmE`}, IDs: []int64{4, 2, 91, -233}, }, SQL: "SELECT * FROM `sChemEa_saD`.`tAblE_NAmE` WHERE `ColuMn_naME` IN (4,2,91,-233) ORDER BY `ColuMn_naME`", }, } { t.Run(tc.Name, func(t *testing.T) { snippet, err := tc.Dialect.SelectRows(tc.Args) if err != nil || snippet == nil { t.Fatal(snippet, err) } if snippet.SQL != tc.SQL { expectTextFormattedSQL(t, snippet.SQL, tc.SQL) } }) } } func TestDialect_InsertRows_nil(t *testing.T) { if v, err := (*Dialect)(nil).InsertRows(nil); err != nil || v != nil { t.Error(v, err) } } func TestDialect_InsertRows_success(t *testing.T) { for _, tc := range [...]struct { Name string Dialect *Dialect Args *export.InsertRows SQL string }{ { Name: `table name only`, Dialect: &Dialect{}, Args: &export.InsertRows{ Schema: &export.Schema{}, Table: export.Table{Name: `tAblE_NAmE`}, Columns: []string{`a`, `B`}, Values: []any{1, 2}, }, SQL: "INSERT INTO `tAblE_NAmE` (`a`,`B`) VALUES (?,?)", }, { Name: `table schema and name`, Dialect: &Dialect{}, Args: &export.InsertRows{ Schema: &export.Schema{}, Table: export.Table{Schema: `sChemEa_saD`, Name: `tAblE_NAmE`}, Columns: []string{`a`, `B`}, Values: []any{1, 2}, }, SQL: "INSERT INTO `sChemEa_saD`.`tAblE_NAmE` (`a`,`B`) VALUES (?,?)", }, } { t.Run(tc.Name, func(t *testing.T) { snippet, err := tc.Dialect.InsertRows(tc.Args) if err != nil || snippet == nil { t.Fatal(snippet, err) } if snippet.SQL != tc.SQL { expectTextFormattedSQL(t, snippet.SQL, tc.SQL) } if !reflect.DeepEqual(tc.Args.Values, snippet.Args) { t.Error() } }) } }
import React, {useState} from "react"; import "./style.css"; import MoreFilter from "./MoreFilter"; import Button from "./Button"; import Category from "./Category"; import TaskModel from "./TaskModel"; import TaskContent from "./TaskContent"; const optionsList = [ { value: "NONE", label: "None", color: "gray", }, { value: "CANCELLED", label: "Cancelled", color: "crimson", }, { value: "STANDBY", label: "Standby", color: "orange", }, { value: "IN-PROGRESS", label: "In-progress", color: "blue", }, { value: "ACTIVE", label: "Active", color: "green", }, ]; export default function Task({searchTask}) { const [modelOpen, setModelOpen] = useState(false); return ( <div className="task"> <div className="top"> <div className="add_task" onClick={() => { setModelOpen(!modelOpen); }} > <Button /> </div> <div className="filter"> <MoreFilter /> </div> <div className="customize"> <Category toggleLabel="Category" options={optionsList} /> </div> </div> <div className="bottom"> <TaskModel type="Add" modelOpen={modelOpen} setModelOpen={setModelOpen} /> </div> <TaskContent searchTask={searchTask} /> </div> ); }
package com.zenjava.playground.browser2.navigation; import com.sun.javafx.css.StyleManager; import com.zenjava.playground.browser.ActivityParameterException; import com.zenjava.playground.browser2.activity.Activatable; import com.zenjava.playground.browser2.activity.HasNode; import com.zenjava.playground.browser2.activity.HasWorkers; import com.zenjava.playground.browser2.activity.Param; import com.zenjava.playground.browser2.transition.*; import javafx.animation.Animation; import javafx.animation.SequentialTransition; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.beans.value.WritableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Worker; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.scene.Node; import javafx.scene.control.Control; import java.lang.reflect.Field; public class Browser extends Control { // work around for bug: http://javafx-jira.kenai.com/browse/RT-16647 static { StyleManager.getInstance().addUserAgentStylesheet("styles/jfxflow-browser.css"); } private ObjectProperty<NavigationManager> navigationManager; private ObjectProperty<HasNode> currentPage; private ObservableList<PlaceResolver> placeResolvers; private ObjectProperty<Animation> currentAnimation; private ObservableList<Worker> workers; private ObjectProperty<Node> content; private ObjectProperty<Bounds> contentBounds; public Browser() { this(new DefaultNavigationManager()); } public Browser(NavigationManager navigationManager) { getStyleClass().add("browser"); this.navigationManager = new SimpleObjectProperty<NavigationManager>(); this.currentPage = new SimpleObjectProperty<HasNode>(); this.placeResolvers = FXCollections.observableArrayList(); this.currentAnimation = new SimpleObjectProperty<Animation>(); this.workers = FXCollections.observableArrayList(); this.content = new SimpleObjectProperty<Node>(); this.contentBounds = new SimpleObjectProperty<Bounds>(); // manage current place final ChangeListener<? super Place> currentPlaceListener = new ChangeListener<Place>() { public void changed(ObservableValue<? extends Place> source, Place oldPlace, Place newPlace) { HasNode newPage = null; if (newPlace != null) { for (PlaceResolver resolver : placeResolvers) { newPage = resolver.resolvePlace(newPlace); if (newPage != null) { HasNode oldPage = currentPage.get(); if (oldPage instanceof Activatable) { ((Activatable) oldPage).setActive(false); } if (newPage instanceof Activatable) { setParameters(newPage, newPlace); ((Activatable) newPage).setActive(true); } currentPage.set(newPage); return; } } } currentPage.set(newPage); } }; this.navigationManager.addListener(new ChangeListener<NavigationManager>() { public void changed(ObservableValue<? extends NavigationManager> source, NavigationManager oldNavigationManager, NavigationManager newNavigationManager) { if (oldNavigationManager != null) { oldNavigationManager.currentPlaceProperty().removeListener(currentPlaceListener); } if (newNavigationManager != null) { newNavigationManager.currentPlaceProperty().addListener(currentPlaceListener); } } }); // manage current page final ListChangeListener<? super Worker> workerListListener = new ListChangeListener<Worker>() { public void onChanged(Change<? extends Worker> change) { // todo be more efficient about this workers.setAll(change.getList()); } }; this.currentPage.addListener(new ChangeListener<HasNode>() { public void changed(ObservableValue<? extends HasNode> source, HasNode oldPage, HasNode newPage) { workers.clear(); if (oldPage instanceof HasWorkers) { ((HasWorkers) oldPage).getWorkers().removeListener(workerListListener); } if (newPage instanceof HasWorkers) { ((HasWorkers) newPage).getWorkers().addListener(workerListListener); } transition(oldPage, newPage); } }); setNavigationManager(navigationManager); } public NavigationManager getNavigationManager() { return navigationManager.get(); } public void setNavigationManager(NavigationManager navigationManager) { this.navigationManager.set(navigationManager); } public ObjectProperty<NavigationManager> navigationManagerProperty() { return navigationManager; } public ObservableList<PlaceResolver> getPlaceResolvers() { return placeResolvers; } public ObjectProperty<Node> contentProperty() { return content; } public ObjectProperty<Bounds> contentBoundsProperty() { return contentBounds; } protected String getUserAgentStylesheet() { return "styles/jfxflow-browser.css"; } protected void setParameters(HasNode page, Place place) { for (Field field : page.getClass().getDeclaredFields()) { Param annotation = field.getAnnotation(Param.class); if (annotation != null) { String name = annotation.value(); if (name == null || name.equals("")) { name = field.getName(); } Object value = place.getParameters().get(name); try { field.setAccessible(true); if (WritableValue.class.isAssignableFrom(field.getType())) { WritableValue property = (WritableValue) field.get(page); property.setValue(value); } else { field.set(page, value); } } catch (IllegalAccessException e) { throw new ActivityParameterException( String.format("Error setting property '%s' on field '%s' in Activity '%s'", name, field.getName(), page), e); } } } } protected void transition(final HasNode oldPage, HasNode newPage) { SequentialTransition transition = new SequentialTransition(); ViewTransition exit = null; if (oldPage != null) { if (oldPage instanceof HasExitTransition) { exit = ((HasExitTransition) oldPage).getExitTransition(); } else { exit = new FadeOutTransition(oldPage.getNode()); } exit.setupBeforeAnimation(contentBounds.get()); transition.getChildren().add(exit.getAnimation()); } ViewTransition entry = null; if (newPage != null) { if (newPage instanceof HasEntryTransition) { entry = ((HasEntryTransition) newPage).getEntryTransition(); } else { entry = new FadeInTransition(newPage.getNode()); } entry.setupBeforeAnimation(contentBounds.get()); transition.getChildren().add(entry.getAnimation()); content.set(newPage.getNode()); } final ViewTransition finalExit = exit; final ViewTransition finalEntry = entry; transition.setOnFinished(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { if (finalEntry != null) { finalEntry.cleanupAfterAnimation(); } if (finalExit != null) { finalExit.cleanupAfterAnimation(); } } }); currentAnimation.set(transition); transition.play(); } }
export const fetchData = async () => { const response = await fetch("/api/client"); if (!response.ok) { throw new Error("Failed to fetch data"); } return response.json(); }; export const fetchEmployeeData = async () => { const response = await fetch("/api/employee"); if (!response.ok) { throw new Error("Failed to fetch data"); } return response.json(); }; // clientApi.ts export const addClient = async (formData: any) => { try { const response = await fetch("/api/client", { method: "POST", body: formData, }); if (!response.ok) { throw new Error("Failed to add client"); } return response.json(); } catch (error) { console.error("Error adding client:", error); throw error; } }; export const addEmployee = async (formData: any) => { try { const response = await fetch("/api/employee", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }); if (!response.ok) { throw new Error("Failed to add client"); } return response.json(); } catch (error) { console.error("Error adding client:", error); throw error; } }; export const deleteClient = async (clientId: any) => { try { const response = await fetch(`/api/client/${clientId}`, { method: "DELETE", }); return response; } catch (error) { console.error("Error deleting client:", error); throw error; } }; export const deleteEmployee = async (employeeId: any) => { try { const response = await fetch(`/api/employee/${employeeId}`, { method: "DELETE", }); return response; } catch (error) { console.error("Error deleting client:", error); throw error; } }; export const updateClient = async (clientId: any, formData: any) => { try { const response = await fetch(`/api/client/${clientId}`, { method: "PUT", body: formData, }); if (!response.ok) { throw new Error("Failed to update client"); } return response.json(); } catch (error) { console.error("Error updating client:", error); throw error; } }; export const updateEmployee = async (employeeId: any, formData: FormData) => { try { const response = await fetch(`/api/employee/${employeeId}`, { method: "PUT", body: formData, // Send formData directly without stringifying }); if (!response.ok) { throw new Error("Failed to update employee"); } return response.json(); } catch (error) { console.error("Error updating employee:", error); throw error; } }; export const addEmployeeClient = async (formData: any) => { try { const response = await fetch("/api/employee_client", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }); if (!response.ok) { throw new Error("Failed to add employee client"); } return response.json(); } catch (error) { console.error("Error adding employee client:", error); throw error; } }; export const fetchEmployeeClients = async (employeeId: any) => { try { const response = await fetch(`/api/employee_client/${employeeId}`); if (!response.ok) { throw new Error("Failed to fetch assigned clients"); } return response.json(); } catch (error) { console.error("Error fetching assigned clients:", error); throw error; } }; export const fetchAllEmployeeClients = async () => { try { const response = await fetch(`/api/employee_client`); if (!response.ok) { throw new Error("Failed to fetch assigned clients"); } return response.json(); } catch (error) { console.error("Error fetching assigned clients:", error); throw error; } }; export const fetchClientById = async (clientId: string) => { try { const response = await fetch(`/api/client/${clientId}`); if (!response.ok) { throw new Error("Failed to fetch client"); } return response.json(); } catch (error) { console.error("Error fetching client:", error); throw error; } }; export async function removeEmployeeClients(employeeId: any) { try { const response = await fetch(`/api/employee_client/${employeeId}`, { method: "DELETE", }); if (!response.ok) { throw new Error("Failed to remove employee clients"); } return await response.json(); } catch (error) { console.error("Error removing employee clients:", error); throw error; } } // Function to update remove date for a specific employee-client relationship export const updateEmployeeClientRemoveDate = async (employeeId: string) => { try { const response = await fetch(`/api/employee_client/${employeeId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ removed_date: new Date().toISOString() }), // Current date }); if (!response.ok) { throw new Error("Failed to update employee-client relationship"); } return response.json(); } catch (error) { console.error("Error updating employee-client relationship:", error); throw error; } }; // This function will remove the client for the given employee ID and set the removed date export async function removeEmployeeClientWithRemoveDate( employeeId: string, clientId: string ) { try { const response = await fetch(`/api/employee_client/${employeeId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ clientId }), }); if (!response.ok) { throw new Error("Failed to remove employee client"); } return response.json(); } catch (error) { console.error("Error removing employee client:", error); throw error; } } export const updateEmployeeClientAddDate = async ( employeeId: string, clientIds: string[] ) => { try { const response = await fetch(`/api/employee_client/${employeeId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ clientIds }), }); if (!response.ok) { throw new Error("Failed to update employee-client relationship"); } return response.json(); } catch (error) { console.error("Error updating employee-client relationship:", error); throw error; } }; // utils/api.js export const updateRemoveDate = async ( employeeId: string, clientId: string, removeDate: any ) => { try { // Create a new Date instance for the current date and time const response = await fetch(`/api/employee_client/${employeeId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ remove_date: removeDate }), }); if (!response.ok) { throw new Error("Failed to update remove date"); } return response.json(); } catch (error) { console.error("Error updating remove date:", error); throw error; } };
import { defineStore } from "pinia" import { copy, isEmpty, uuid } from "@/utils/common" import { wallpaperStore } from "@/plugins/localforage" import { isImageFile } from "@/utils/img" import { usePreferredDark } from "@/utils/use" import { getDailyWallpaperUrl } from "@/api/bing" import { isObjectURL } from "@/utils/browser" import { saveAs } from "file-saver" import { fromUrl } from "@/utils/palette" import { BackgroundSetting, BackgroundType, ThemeMode, TopSiteSetting, LayoutSetting, AlignType, PopupSettting, LanguageType, ThemeSetting } from "@/types/setting" import { SearchSetting, OpenPageTarget, SearchSuggestion } from "@/types/search" export interface SettingState { lang: LanguageType theme: ThemeSetting search: SearchSetting background: BackgroundSetting topSite: TopSiteSetting layout: LayoutSetting popup: PopupSettting } const BACKUP_FILE_MARK = "_MARK_" const DEFAULT_COLOR = ["#1890ff", "#7FBA00", "#F25022", "#FFB900", "#00A4EF", "#1F1F1F"] export default defineStore("setting", { state: (): SettingState => ({ lang: LanguageType.Auto, theme: { mode: ThemeMode.Auto, primaryColor: "#1890ff", colorPalette: [] }, background: { id: "", type: BackgroundType.None, url: "", blur: 0, maskColor: "#000", maskOpacity: 0, autoOpacity: true }, search: { currentEngine: "bing", openPageTarget: OpenPageTarget.Blank, showEngineIcon: true, showEngineSelect: true, searchInputRadius: 4, useSearchEngines: ["bing", "google", "baidu"], suggestion: SearchSuggestion.none }, topSite: { enable: false, col: 6, row: 2, gap: 16, iconSize: 32, boardSize: 64, boardRadius: 4, boardColor: "#fff", boardOpacity: 0.8 }, layout: { align: AlignType.searchCenter }, popup: { current: 0 } }), getters: { /** * 获取当前语言 * 自动时使用浏览器语言 * * @returns currentLang */ currentLang: ({ lang }) => (lang === LanguageType.Auto ? navigator.language : lang), /** * 获取当前主题 * 自动时使用系统主题颜色 * * @returns ThemeMode.Dart | ThemeMode.Light */ currentTheme(): ThemeMode.Dart | ThemeMode.Light { const mode = this.theme.mode if (mode === ThemeMode.Auto) { const isDark = usePreferredDark() return isDark.value ? ThemeMode.Dart : ThemeMode.Light } else { return mode } }, /** * 获取基础颜色 * * @returns Array<string> */ primaryColors(): Array<string> { const { colorPalette } = this.theme if (isEmpty(colorPalette)) { return DEFAULT_COLOR } else { return colorPalette } } }, actions: { /** * 上传壁纸 * @param param0 * @param imageFile */ async uploadBackgroundImage(imageFile: File) { if (!isImageFile(imageFile)) throw new Error("这不是一个图片文件") const id = uuid(), url = URL.createObjectURL(imageFile), url_old = this.background.url // 清除上次壁纸,ObjectURL可能导致内存溢出 await wallpaperStore.clear() if (url_old && isObjectURL(url_old)) { URL.revokeObjectURL(url_old) } // 保存图片到IndexedDB await wallpaperStore.setItem<Blob>(id, imageFile) copy({ id, url }, this.background) }, /** * 重新加载壁纸 * 壁纸使用BlobUrl实现,数据生命周期为session * @param param0 */ async reloadBackgroundImage() { const id = this.background?.id! const file = await wallpaperStore.getItem<Blob>(id) // 校验图片数据是否可用,否则删除该数据 if (file && isImageFile(file)) { const url = URL.createObjectURL(file) this.background.url = url } else { this.background.id = null this.background.url = null await wallpaperStore.removeItem(id) } }, /** * 加载Bing每日壁纸 * @param param0 * @param imageFile */ async loadBingDailyWallpaper() { const url = await getDailyWallpaperUrl() if (isEmpty(url)) return this.background.url = url }, async loadWallpaperPalette() { const { url } = this.background this.theme.colorPalette = await fromUrl(url!) }, /** * 导出设置数据 * 使用JSON格式保存 */ exportSetting() { const { npm_package_name, npm_package_version } = import.meta.env const dataJson = JSON.stringify({ [BACKUP_FILE_MARK]: npm_package_name, ...window.localStorage }) // 保存文件 const blob = new Blob([dataJson], { type: "application/json;charset=utf-8" }) saveAs(blob, `${npm_package_name}_${npm_package_version}.json`) }, /** * 导入设置数据 * 使用JSON格式保存 */ async importSetting(file: File) { if (!file.type.includes("json")) throw new Error("导入文件不匹配") const dataJson = await file.text() const data = JSON.parse(dataJson) const { npm_package_name } = import.meta.env if (data[BACKUP_FILE_MARK] !== npm_package_name) throw new Error("备份文件已损坏") for (let item in data) { if (item === BACKUP_FILE_MARK) continue localStorage.setItem(item, data[item]) } } } })
<?php namespace App\DataTables\Admin\Master; use App\Models\StatusKawin; use Yajra\DataTables\Html\Button; use Yajra\DataTables\Html\Column; use Yajra\DataTables\Html\Editor\Editor; use Yajra\DataTables\Html\Editor\Fields; use Yajra\DataTables\Services\DataTable; class StatusKawinDataTable extends DataTable { /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->setRowId(function ($row) { return $row->id; }) ->addColumn('action', function ($row) { $btn = '<div class="btn-group">'; $btn = $btn . '<a href="' . route('admin.master-data.status-kawin.edit', $row->id) . '" class="btn btn-dark buttons-edit"><i class="fas fa-edit"></i></a>'; $btn = $btn . '<a href="' . route('admin.master-data.status-kawin.destroy', $row->id) . '" class="btn btn-danger buttons-delete"><i class="fas fa-trash fa-fw"></i></a>'; $btn = $btn . '</div>'; return $btn; }); } /** * Get query source of dataTable. * * @param \StatusKawin $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(StatusKawin $model) { return $model->newQuery(); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { return $this->builder() ->setTableId('statuskawin-table') ->columns($this->getColumns()) ->minifiedAjax() ->dom('<"dataTables_wrapper dt-bootstrap"B<"row"<"col-xl-7 d-block d-sm-flex d-xl-block justify-content-center"<"d-block d-lg-inline-flex"l>><"col-xl-5 d-flex d-xl-block justify-content-center"fr>>t<"row"<"col-sm-5"i><"col-sm-7"p>>>') ->orderBy(1) ->buttons( Button::make('create'), Button::make('export'), Button::make('print'), Button::make('reset'), Button::make('reload') ); } /** * Get columns. * * @return array */ protected function getColumns() { return [ Column::computed('action') ->exportable(false) ->printable(false) ->width(60) ->addClass('text-center'), Column::make('nama'), ]; } /** * Get filename for export. * * @return string */ protected function filename() { return 'MasterStatusKawin_' . date('YmdHis'); } }
// // NewsService.swift // Life // // Created by Shyngys Kassymov on 14.02.2018. // Copyright © 2018 Shyngys Kassymov. All rights reserved. // import Foundation import Moya enum NewsService { case topNews(top: Int) case news(id: String) case likeNews(withId: String) case addCommentToNews(withId: String, commentText: String) case likeComment(newsId: String, commentId: String, voteType: UserVote) case createNews( mainImage: URL?, secondaryImages: [URL], title: String, text: String, rawText: String, isHistoryEvent: Bool, isPressService: Bool, tags: [String] ) case updateNews( id: String, mainImage: URL?, secondaryImages: [URL], title: String, text: String, rawText: String, isHistoryEvent: Bool, isPressService: Bool, tags: [String] ) case popularNews case newsWithDetails(rows: Int, offset: Int) } extension NewsService: AuthorizedTargetType { var path: String { switch self { case .topNews, .createNews, .updateNews: return "/News" case .news(let id): return "/News/\(id)" case .likeNews(let id): return "/News/\(id)/like" case .addCommentToNews(let id, _): return "/News/\(id)/comments" case .likeComment(let newsId, let commentId, let voteType): return "/News/\(newsId)/comments/\(commentId)/like/\(voteType.rawValue)" case .popularNews: return "/News/popular" case .newsWithDetails: return "/News/withdetails" } } var method: Moya.Method { switch self { case .news, .topNews, .popularNews, .newsWithDetails: return .get case .addCommentToNews, .createNews: return .post case .likeNews, .likeComment, .updateNews: return .put } } var task: Moya.Task { switch self { case .news, .likeNews, .likeComment, .popularNews: return .requestPlain case .addCommentToNews(_, let commentText): return .requestParameters( parameters: ["commentText": commentText], encoding: JSONEncoding.default ) case .topNews(let top): return .requestParameters( parameters: ["top": top], encoding: URLEncoding.default ) case .createNews( let mainImage, let secondaryImages, let title, let text, let rawText, let isHistoryEvent, let isPressService, let tags): var data = [MultipartFormData]() if let mainImage = mainImage { let mainImageData = mainImage.multipartFormData("MainImage") data.append(mainImageData) } for secondaryImage in secondaryImages { let secondaryImageData = secondaryImage.multipartFormData("SecondaryImages") data.append(secondaryImageData) } data.append(title.multipartFormData("Title")) data.append(text.multipartFormData("Text")) data.append(rawText.multipartFormData("RawText")) data.append(String(isHistoryEvent).multipartFormData("IsHistoryEvent")) data.append(String(isPressService).multipartFormData("IsPressService")) for tag in tags { data.append(tag.multipartFormData("Tags")) } return .uploadMultipart(data) case .updateNews( let id, let mainImage, let secondaryImages, let title, let text, let rawText, let isHistoryEvent, let isPressService, let tags): var data = [MultipartFormData]() data.append(id.multipartFormData("NewsId")) if let mainImage = mainImage { let mainImage = mainImage.multipartFormData("MainImage") data.append(mainImage) } for secondaryImage in secondaryImages { let secondaryImageData = secondaryImage.multipartFormData("SecondaryImages") data.append(secondaryImageData) } data.append(title.multipartFormData("Title")) data.append(text.multipartFormData("Text")) data.append(rawText.multipartFormData("RawText")) data.append(String(isHistoryEvent).multipartFormData("IsHistoryEvent")) data.append(String(isPressService).multipartFormData("IsPressService")) for tag in tags { data.append(tag.multipartFormData("Tags")) } return .uploadMultipart(data) case .newsWithDetails(let rows, let offset): return .requestParameters( parameters: ["rows": rows, "offset": offset], encoding: URLEncoding.default ) } } var sampleData: Data { switch self { case .news, .createNews, .updateNews: return Bundle.main.stubJSONWith(name: "news_details") case .topNews, .popularNews, .newsWithDetails: return Bundle.main.stubJSONWith(name: "news") case .likeNews, .likeComment: return [:].toJSONData() case .addCommentToNews: return Bundle.main.stubJSONWith(name: "comment") } } var headers: [String: String]? { return nil } var needsAuth: Bool { return true } }
<single-spa-router> <!-- This is the single-spa Layout Definition for your microfrontends. See https://single-spa.js.org/docs/layout-definition/ for more information. --> <!-- Example layouts you might find helpful: <nav> <application name="@org/navbar"></application> </nav> <route path="settings"> <application name="@org/settings"></application> </route> --> <div> <div> <application name="@react-nav/navbar"></application> </div> <main> <route default> <application name="@react-home/page"></application> </route> <route path="posts"> <application name="@react-post/page""></application> </route> <route path="users"> <application name="@react-user/page""></application> </route> <route path="country"> <application name="@react-country/page""></application> </route> </main> </div> </single-spa-router>
package com.example.hermes.ui.delivery import android.app.Application import androidx.lifecycle.viewModelScope import com.example.hermes.R import com.example.hermes.application.Hermes import com.example.hermes.domain.models.Address import com.example.hermes.domain.models.Order import com.example.hermes.domain.usecase.delete.ClearBasketUseCase import com.example.hermes.domain.usecase.get.GetAddressActiveUseCase import com.example.hermes.domain.usecase.send.SendOrderUseCase import com.example.hermes.ui.base.BaseViewModel import com.example.hermes.ui.basket.BasketContract import com.example.hermes.ui.map.MapContract import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.HttpException import java.io.IOException import javax.inject.Inject class DeliveryViewModel( application: Application ) : BaseViewModel<DeliveryContract.Event, DeliveryContract.State, DeliveryContract.Effect>( application ) { @Inject lateinit var sendOrderUseCase: SendOrderUseCase @Inject lateinit var clearBasketUseCase: ClearBasketUseCase @Inject lateinit var getAddressActiveUseCase: GetAddressActiveUseCase init { (application as Hermes).appComponent?.inject(this) } override fun createInitialState(): DeliveryContract.State { return DeliveryContract.State.Default } override fun handleEvent(event: DeliveryContract.Event) { when (event) { is DeliveryContract.Event.OnClickSendOrder -> clickSendOrder(event.order) } } fun getAddressActive(): Address? { var address: Address? = null viewModelScope.launch { setState { DeliveryContract.State.Loading } try { address = getAddressActiveUseCase.execute() } catch (e: Exception) { setEffect { DeliveryContract.Effect.ShowMessage(R.string.delivery_error) } } setState { DeliveryContract.State.Setting } } return address } private fun clickSendOrder(order: Order) { viewModelScope.launch { setState { DeliveryContract.State.Loading } try { withContext(Dispatchers.IO) { sendOrderUseCase.execute(order) clearBasketUseCase.execute() } setEffect { DeliveryContract.Effect.ShowMessage(R.string.delivery_mes_send_success) } setEffect { DeliveryContract.Effect.OnGeneralActivity } } catch (e: IOException) { setEffect { DeliveryContract.Effect.ShowMessage(R.string.delivery_error_not_connection) } } catch (e: HttpException) { setEffect { DeliveryContract.Effect.ShowMessage(R.string.delivery_mes_server_error) } } catch (e: Exception) { setEffect { DeliveryContract.Effect.ShowMessage(R.string.delivery_error) } } setState { DeliveryContract.State.Setting } } } }
package com.itangcent.utils /** * A map of escape characters to their unescaped versions. */ private val escapeCharacters = mapOf( 'b' to '\b', // Backspace 't' to '\t', // Tab 'n' to '\n', // Newline 'r' to '\r', // Carriage return '\\' to '\\', // Backslash ) /** * Used to convert escaped characters in a string to their unescaped version. * For example, "\\n" would be converted to "\n". * * @return The unescaped string. */ fun String.unescape(): String { val sb = StringBuilder() var escaped = false for (ch in this) { if (!escaped) { if (ch == '\\') { escaped = true } else { sb.append(ch) } continue } escaped = false if (escapeCharacters.containsKey(ch)) { sb.append(escapeCharacters[ch]) continue } sb.append('\\') sb.append(ch) continue } if (escaped) { sb.append('\\') } return sb.toString() }
import React, { Component } from "react"; import axios from "axios"; import "../JokeList.css"; import JokeItem from "./JokeItem"; export default class JokeList extends Component { static defaultProps = { numJokestoGet: 10, }; constructor(props) { super(props); this.state = { jokes: [], loading: false, }; } componentWillMount() { this.setState({ loading: true }, this.getTenJokes); } async getTenJokes() { let jokes = []; while (jokes.length < this.props.numJokestoGet) { const response = await axios.get("https://icanhazdadjoke.com/", { headers: { Accept: "application/json" }, }); jokes.push({ joke: response.data.joke, vote: 0 }); } this.setState((state) => ({ loading: false, jokes: [...state.jokes, ...jokes], })); } handleClick = () => { this.setState({ loading: true }, this.getTenJokes); }; addVote = (index) => { const jokes = this.state.jokes; jokes[index] = { ...jokes[index] }; jokes[index].vote += 1; this.setState({ jokes }); }; subtractVote = (index) => { const jokes = this.state.jokes; jokes[index] = { ...jokes[index] }; jokes[index].vote -= 1; this.setState({ jokes }); }; render() { const sorted = this.state.jokes.sort((a, b) => b.vote - a.vote); const tenJokes = sorted.map((joke, index) => ( <JokeItem key={index} joke={joke.joke} vote={joke.vote} addVote={this.addVote} subtractVote={this.subtractVote} id={index} /> )); if (this.state.loading) { return ( <div className="spinner"> <i class="fa fa-spin"> {" "} <span aria-label="Laugh" role="img"> 😂 </span> </i> <br /> <h1>Getting new jokes ... </h1> </div> ); } else { return ( <div className="JokeList"> <div className="JokeTitle"> <h1>Dad Jokes</h1> <p> <span aria-label="Laugh" role="img"> 😆 </span> </p> <button className="addJokes" onClick={this.handleClick}> New Jokes </button> </div> <div className="JokeItems"> <ul>{tenJokes}</ul> </div> </div> ); } } }
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var spRouter = require('./routes/sanpham'); var apiUser = require('./routes/api-user'); var apiSp = require('./routes/api-sp'); var login = require('./routes/login'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/sp',spRouter) app.use('/apiUser',apiUser) app.use('/apiSp',apiSp) app.use('/login',login) // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; //API res.status(err.status || 500) if(req.originalUrl.indexOf('/api')==0){ res.json( { status :0, msg:err.message } ); }else{ res.render('error') } res.render('error'); }); module.exports = app;
/********************************************************************************** * @name CESS_helperMassiveTest * @version 1.0 * @author María Dolores Sánchez Meroño - mdolores.sanchez@iecisa.com * @creation date 16/11/2020 * @description Apex Class with test for CESS_helperMassive * @group Test **********************************************************************************/ @isTest public class CESS_helperMassiveTest { private final static String HEADER_2 = 'Linea,Resultado,Id Lead,Error'; /********************************************************************************** * @author María Dolores Sánchez Meroño - mdolores.sanchez@iecisa.com * @creation date 16/11/2020 * @description Test setup **********************************************************************************/ @testSetup private static void setup() { ORG_TestDataUtils orgDataUtils = ORG_TestDataUtils.getInstance(); List <Lead> lstLd = new List <Lead>(); lstLd.add(new Lead (LastName='Test1', source_manualrecord__c='Otros', Email = 'test1@email.com', MobilePhone='666778899',Status='Unqualified',result__c='Duplicado')); lstLd.add(new Lead (LastName='Test2', source_manualrecord__c='Otros', Email = 'test2@email.com', MobilePhone='666778898',Status='New')); lstLd.add(new Lead (LastName='Test3', source_manualrecord__c='Otros', Email = 'test3@email.com', MobilePhone='666778897',Status='New',sent_cti__c = True)); insert lstLd; } /********************************************************************************** * @author Alejandro Martínez Hernández - alejandro.martinez@iecisa.com * @creation date 14/04/2020 * @description Test createCsvObj **********************************************************************************/ @isTest static void createCsvObj_test() { String sep = System.Label.ORG_lbl_csvSep; String header = 'Id Lead'+ORG_Constantes.MSG_LINE_BREAK; String csvString = header ; Integer numLin = 1; Map<Integer, String> mapInfoAdd = new Map<Integer, String>(); for(Lead ld : [SELECT Id,lead_number__c,FirstName,LastName,campaign_cti__c,source_type__c FROM Lead]){ String recordLine = ld.lead_number__c+ORG_Constantes.MSG_LINE_BREAK; csvString = csvString + recordLine; String infoAdd = ld.FirstName+CESS_Constantes.CESS_SEP+ld.LastName+CESS_Constantes.CESS_SEP+ld.campaign_cti__c+CESS_Constantes.CESS_SEP+ld.source_type__c; mapInfoAdd.put(numLin,infoAdd); numLin++; } csvString = csvString + '1234'+ORG_Constantes.MSG_LINE_BREAK; CESS_csvObject csvObj = new CESS_csvObject(csvString); Map<Integer, String> mapLinEstado = new Map<Integer, String>(); numLin = 1; for (List<String> line : csvObj.lines) { mapLinEstado.put(numLin, ORG_Constantes.MSG_EMPTY); numLin++; } Test.startTest(); CESS_csvObject outCsv = CESS_helperMassive.createCsvObj(HEADER_2, csvObj, mapLinEstado,mapInfoAdd); Test.stopTest(); System.assertNotEquals(null, outCsv, 'El objeto csv de salida debe ser distinto de null'); } }
'use client' import { logOut } from "@/app/actions/logout" import { useUiStore } from "@/store/ui-store" import clsx from "clsx" import { useSession } from "next-auth/react" import Link from "next/link" import { IoCloseOutline, IoLogInOutline, IoLogOutOutline, IoPeopleOutline, IoPersonOutline, IoReaderOutline, IoSearchOutline, IoShirtOutline } from "react-icons/io5" const Sidebar = () => { const isSideMenuOpen = useUiStore(state => state.isSideMenuOpen) const closeMenu = useUiStore(state => state.closeSideMenu) const { data: session } = useSession() const isAuthenticated = !!session?.user const roleSession = session?.user.role return ( <div> { isSideMenuOpen && <> <div className="fixed top-0 left-0 w-screen h-screen z-10 bg-black opacity-50 backdrop-filter backdrop-blur-sm"></div> <div onClick={closeMenu} className="fixed top-0 left-0 w-screen h-screen z-10 backdrop-filter backdrop-blur-sm" ></div> </> } <nav className={ clsx( "fixed px-5 right-0 top-0 w-[300px] h-screen bg-white z-20 shadow-2xl transition-all duration-300", { "translate-x-full": !isSideMenuOpen } ) }> <IoCloseOutline size={30} className="absolute top-5 right-5 cursor-pointer" onClick={() => closeMenu()} /> {/* input search */} <div className="relative mt-14"> <IoSearchOutline size={20} className="absolute top-2 left-2" /> <input type="text" placeholder="Buscar" className="w-full bg-gray-50 rounded px-10 py-1 border-b-2 text-xl border-gray-200 focus:outline-none focus:border-gray-600" /> </div> {/* menu */} { isAuthenticated && ( <> <Link href="/profile" onClick={() => closeMenu()} className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoPersonOutline size={30} /> <span className="ml-3 text-xl">Profile</span> </Link> <Link href="/orders" onClick={() => closeMenu()} className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoReaderOutline size={30} /> <span className="ml-3 text-xl">Orders</span> </Link> </> ) } <hr className="mt-5" /> { !isAuthenticated && ( <Link href="/auth/login" className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoLogInOutline size={30} /> <span className="ml-3 text-xl">Log in</span> </Link> ) } { roleSession === 'admin' && ( <> <Link href="/admin/products" onClick={() => closeMenu()} className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoShirtOutline size={30} /> <span className="ml-3 text-xl">Products</span> </Link> <Link href="/admin/orders" onClick={() => closeMenu()} className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoReaderOutline size={30} /> <span className="ml-3 text-xl">Orders</span> </Link> <Link href="/admin/users" onClick={() => closeMenu()} className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all" > <IoPeopleOutline size={30} /> <span className="ml-3 text-xl">Users</span> </Link> </> ) } <hr className="mt-5" /> {/*LogOut */} { isAuthenticated && ( <button className="flex items-center mt-5 p-2 hover:bg-gray-100 rounded transition-all w-full" onClick={() => logOut()} > <IoLogOutOutline size={30} /> <span className="ml-3 text-xl">Log out</span> </button> ) } </nav> </div> ) } export default Sidebar
import MockDate from 'mockdate' import { describe, expect, vi, it, beforeAll, afterAll } from 'vitest' import { SaveSurveyResultController } from '@/presentation/controllers' import { InvalidParamError } from '@/presentation/errors' import { forbidden, ok, serverError } from '@/presentation/helpers' import { faker } from '@faker-js/faker' import { LoadAnswersBySurveySpy, SaveSurveyResultSpy } from '../../presentation/mocks' interface SutTypes { sut: SaveSurveyResultController loadAnswersBySurveySpy: LoadAnswersBySurveySpy saveSurveyResultSpy: SaveSurveyResultSpy } const makeSut = (): SutTypes => { const loadAnswersBySurveySpy = new LoadAnswersBySurveySpy() const saveSurveyResultSpy = new SaveSurveyResultSpy() const sut = new SaveSurveyResultController(loadAnswersBySurveySpy, saveSurveyResultSpy) return { sut, loadAnswersBySurveySpy, saveSurveyResultSpy } } const mockRequest = (answer?: string): SaveSurveyResultController.Request => ({ surveyId: faker.datatype.uuid(), answer: answer ?? '', accountId: faker.datatype.uuid() }) describe('SaveSurveyResult Controller', () => { beforeAll(() => { MockDate.set(new Date()) }) afterAll(() => { MockDate.reset() }) it('Should call LoadAnswersBySurvey with correct values', async () => { const { sut, loadAnswersBySurveySpy } = makeSut() const request = mockRequest() await sut.handle(request) expect(loadAnswersBySurveySpy.id).toBe(request.surveyId) }) it('Should return 403 if LoadAnswersBySurvey returns null', async () => { const { sut, loadAnswersBySurveySpy } = makeSut() loadAnswersBySurveySpy.result = [] const httpResponse = await sut.handle(mockRequest()) expect(httpResponse).toEqual(forbidden(new InvalidParamError('surveyId'))) }) it('Should return 500 if LoadAnswersBySurvey throws', async () => { const { sut, loadAnswersBySurveySpy } = makeSut() vi.spyOn(loadAnswersBySurveySpy, 'loadAnswers').mockRejectedValueOnce(new Error()) const httpResponse = await sut.handle(mockRequest()) expect(httpResponse).toEqual(serverError(new Error())) }) it('Should return 403 if an invalid answers is provided', async () => { const { sut } = makeSut() const httpResponse = await sut.handle(mockRequest()) expect(httpResponse).toEqual(forbidden(new InvalidParamError('answer'))) }) it('Should call SaveSurveyResult with correct values', async () => { const { sut, saveSurveyResultSpy, loadAnswersBySurveySpy } = makeSut() const request = mockRequest(loadAnswersBySurveySpy.result[0]) await sut.handle(request) expect(saveSurveyResultSpy.saveSurveyResultParams).toEqual({ surveyId: request.surveyId, accountId: request.accountId, date: new Date(), answer: request.answer }) }) it('Should return 500 if SaveSurveyResult throws', async () => { const { sut, saveSurveyResultSpy, loadAnswersBySurveySpy } = makeSut() vi.spyOn(saveSurveyResultSpy, 'save').mockRejectedValueOnce(new Error()) const request = mockRequest(loadAnswersBySurveySpy.result[0]) const httpResponse = await sut.handle(request) expect(httpResponse).toEqual(serverError(new Error())) }) it('Should return 200 on success', async () => { const { sut, saveSurveyResultSpy, loadAnswersBySurveySpy } = makeSut() const request = mockRequest(loadAnswersBySurveySpy.result[0]) const httpResponse = await sut.handle(request) expect(httpResponse).toEqual(ok(saveSurveyResultSpy.result)) }) })
import * as PIXI from "pixi.js"; import Constant from "./Constants"; import { getReels, getReelStops, setStartReelsStopping } from "./Model"; import Reel from "./Reel"; import Resize from "./Resize"; export default class ReelsContainer extends Resize { private reelsPanel: PIXI.Container; private reelsContainer: PIXI.Container; private reelBG: PIXI.Sprite; private reels: Array<Reel> = []; private symTextures: Array<PIXI.Texture> = []; private game: PIXI.Application; private reelStops: number[] = []; constructor(game: PIXI.Application) { super(); this.game = game; this.init(); this.resize(); } private init(): void { this.reelsPanel = new PIXI.Container(); this.reelsPanel.pivot.set(Constant.GAME_WIDTH / 2, Constant.GAME_HEIGHT / 2); this.game.stage.addChild(this.reelsPanel); this.reelsContainer = new PIXI.Container(); this.reelsPanel.addChild(this.reelsContainer); this.reelsContainer.x = Constant.REELS_PANEL_OFFSET_X this.reelsContainer.y = Constant.REELS_PANEL_OFFSET_Y const reelMask: PIXI.Graphics = new PIXI.Graphics(); reelMask.beginFill(0x000000, 0.5); reelMask.drawRect(0, 54, 405, 213); reelMask.endFill(); this.reelsContainer.addChild(reelMask); this.reelsContainer.mask = reelMask; const reelBGTexture = this.game.loader.resources!.reel.texture; this.reelBG = new PIXI.Sprite(reelBGTexture); this.reelBG.y = 54; this.reelsContainer.addChild(this.reelBG); for (let i: number = 0; i < Constant.NUM_OF_REELS; i++) { const reel: Reel = new Reel(this.game); this.reels.push(reel); reel.getReelContainer().x = Constant.REELS_OFFSET_X + ((Constant.SYMBOL_WIDTH + Constant.REELS_GAP) * i); this.reelsContainer.addChild(reel.getReelContainer()); } this.setReelStops(); } private setReelStops(): void { const reels: number[][] = getReels(); this.reelStops = [...getReelStops()]; this.reelStops.forEach((pos: number, i: number) => { this.reels[i].showStaticReel(pos, i); }); } public async updateReels(): Promise<void> { const startTIme = Date.now(); console.log("Start Spin"); const spinStartPromises: Array<Promise<void>> = this.reels.map((reel: Reel, i: number): Promise<void> => { return new Promise<void>((resolve) => { const startDelay: number = 250 * i; setTimeout(() => { console.log("reel: ", i); reel.spinStart(this.reelStops[i], i).then(() => { resolve(); }); if (i === this.reels.length - 1) { setTimeout(() => { setStartReelsStopping(true); this.reelStops = [...getReelStops()]; }, 500) } }, startDelay + 16); }); }); await Promise.all(spinStartPromises); const endTime = Date.now(); const totalTime = endTime - startTIme; console.log("Spinning Done: ", totalTime); setStartReelsStopping(false); } protected resize(): void { const scale: number = Math.min(window.innerWidth / Constant.GAME_WIDTH, window.innerHeight / Constant.GAME_HEIGHT); this.reelsPanel.scale.set(scale); this.reelsPanel.position.set(this.game.screen.width / 2, this.game.screen.height / 2); } }
export interface SettingsFromPage { code_commands: CodeCommand[]; parse_commands: ParseCommand[]; expected_output_fields: ExpectedOutputFields; input_schema: InputSchema; } export interface CodeCommand { cmd: string; args: Arg[]; summary: string; description: string; examples?: string[]; screenshot?: string; } export interface Arg { name: string; description: string; options?: string[]; optional?: boolean; } export interface ParseCommand { cmd: string; description: string; examples: string[]; description_extra?: string; } export interface ExpectedOutputFields { type: string; fields: Record<string, OutputField>; } export interface OutputField { type: string; required?: boolean; active: boolean; normalize?: any; draft_field?: boolean; default_value?: string; format?: Format; } export interface Format { preset: string; } export interface InputSchema { customer: string; type: string; name: string; description: string; example: Example[]; fields: Record<string, InputField>; id: string; family: string; patch: number; version: string; } export interface InputField { type: "string" | "number"; required: boolean; } export interface Example { limit: number; tag: string; since: number; }
#include "Beings/Shared/PICharacterBase.h" #include "WaterBodyActor.h" #include "Beings/Player/States/PIClimbingState.h" #include "Beings/Shared/States/PIMovementState.h" #include "Beings/Shared/States/PIStateBase.h" void APICharacterBase::SetCurrentState(const TSharedPtr<FPIStateBase>& state) { auto setCurrentLambda = [this, state] { _currentState = state; if (!_currentState.IsValid()) return; if (_inputDelegates.IsValid()) { _currentState->BindInput(_inputDelegates.ToSharedRef()); } _currentState->Enter(); }; if (_currentState.IsValid()) { if (_currentState->CanExit()) { if (_inputDelegates.IsValid()) { _currentState->UnbindInput(_inputDelegates.ToSharedRef()); } _currentState->Exit(FPIStateOnExitDelegate::CreateLambda(setCurrentLambda)); } return; } setCurrentLambda(); } void APICharacterBase::BeginPlay() { Super::BeginPlay(); } void APICharacterBase::CreateMovementState(const float& capsuleRadius, const float& movementAcceleration) { _movementState = MakeShared<FPIMovementState>(this, FPIMovementStateData( capsuleRadius, _capsuleRadiusAcceleration, _rotationAcceleration, movementAcceleration )); } void APICharacterBase::CreateClimbingState(const float& capsuleRadius, const float& movementAcceleration) { _climbingState = MakeShared<FPIClimbingState>(this, FPIClimbingStateData( capsuleRadius, _capsuleRadiusAcceleration, movementAcceleration, _rotationAcceleration )); } void APICharacterBase::CreateSwimmingState(const float& capsuleRadius, const float& movementAcceleration) { _swimmingState = MakeShared<FPISwimmingState>(this, FPISwimmingStateData( capsuleRadius, _capsuleRadiusAcceleration, _rotationAcceleration, movementAcceleration )); } void APICharacterBase::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (!_currentState.IsValid()) return; _currentState->Tick(DeltaSeconds); // fixing Npc crash while it's missing implementation if (!_swimmingState.IsValid()) return; // TODO(anderson): should this really be here? AWaterBody* waterBody = _waterBodyActor.Get(); if (_currentState != _swimmingState) { if (_swimmingState->CanStartSwimming(waterBody)) { StartSwimming(waterBody); } } if (_currentState == _swimmingState) { if (_swimmingState->CanEndSwimming()) { EndSwimming(); } } } void APICharacterBase::SetInputDelegates(const TSharedPtr<FPIInputDelegates>& inputDelegates) { if (_currentState.IsValid()) { _currentState->UnbindInput(inputDelegates.ToSharedRef()); } _inputDelegates = inputDelegates; if (_currentState.IsValid()) { _currentState->BindInput(inputDelegates.ToSharedRef()); } } void APICharacterBase::NotifyActorBeginOverlap(AActor* OtherActor) { Super::NotifyActorBeginOverlap(OtherActor); // fixing Npc crash while it's missing implementation if (!_swimmingState.IsValid()) return; _waterBodyActor = Cast<AWaterBody>(OtherActor); if (_currentState == _swimmingState) { _swimmingState->WaterBody = _waterBodyActor; } } void APICharacterBase::NotifyActorEndOverlap(AActor* OtherActor) { Super::NotifyActorEndOverlap(OtherActor); if (_waterBodyActor == OtherActor) { _waterBodyActor = nullptr; } }
import type { BlogMeta } from 'types/types'; import { Fragment } from 'react'; import Blog from 'components/blog'; import Section from 'design-system/section'; import SignUp from 'components/sign-up'; import Head from 'next/head'; import pkg from '../package.json'; interface LayoutBlogProps { blog: BlogMeta; children: React.ReactNode; } function LayoutBlog({ blog, children }: LayoutBlogProps) { return ( <Fragment> <Head> <title> {blog.title} · {pkg.name} </title> <meta name="description" content={blog.blurb} /> <meta property="og:title" content={blog.title} /> <meta property="og:description" content={blog.blurb} /> {blog.heroImage && ( <meta property="og:image" content={`https://${pkg.name}${blog.heroImage.src}`} /> )} <meta property="og:url" content={`https://${pkg.name}/blog/${blog.slug}`} /> <meta property="og:type" content="article" key="og:type" /> {blog.heroImage && <meta property="og:image:height" content={`${blog.heroImage.height}`} />} {blog.heroImage && <meta property="og:image:width" content={`${blog.heroImage.width}`} />} <meta name="twitter:card" content="summary_large_image" /> {blog.heroImage && ( <meta name="twitter:image" content={`https://${pkg.name}${blog.heroImage.src}`} /> )} </Head> <Section isSeparated> <Blog {...blog}>{children}</Blog> </Section> <Section isSunken isSeparated> <SignUp /> </Section> </Fragment> ); } export default LayoutBlog;
<div class="container-fluid"> <div class="row"> <div class="col ms-5 p-5"> <div class="row"> <div class="col"> <mat-form-field appearance="outline" style="width: 100%"> <mat-label>Escriba para filtrar...</mat-label> <span matPrefix><mat-icon class="me-4">search</mat-icon> &nbsp;</span> <input matInput (keyup)="onKey($event)" #input> </mat-form-field> </div> <div class="col-4 pt-3 text-center ps-0" *ngIf="dateSelected"> <button mat-raised-button class="me-2" (click)="openModal('edit')">Editar cita</button> <button mat-raised-button color="warn" (click)="openModal('delete')">Eliminar cita</button> </div> </div> <div class="row"> <div class="col mat-elevation-z8 p-0"> <mat-table *ngIf="dataSource.data.length; else loading" [dataSource]="dataSource" class="w-100"> <!-- NAME Column --> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef> Nombre del dueño</mat-header-cell> <mat-cell *matCellDef="let element"> {{element.userName}} {{element.userLastName}}</mat-cell> </ng-container> <!-- RUT Column --> <ng-container matColumnDef="state"> <mat-header-cell *matHeaderCellDef> Estado </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.state | state}} </mat-cell> </ng-container> <!-- ADDRESS Column --> <ng-container matColumnDef="date"> <mat-header-cell *matHeaderCellDef> Fecha </mat-header-cell> <mat-cell *matCellDef="let element"> {{setDate(element.date) | moment}} </mat-cell> </ng-container> <!-- ADDRESS Column --> <ng-container matColumnDef="time"> <mat-header-cell *matHeaderCellDef> Hora </mat-header-cell> <mat-cell *matCellDef="let element"> {{getTime(element.block)}} </mat-cell> </ng-container> <!-- ANIMAL Column --> <ng-container matColumnDef="animal"> <mat-header-cell *matHeaderCellDef> Paciente </mat-header-cell> <mat-cell *matCellDef="let element"> <mat-chip-list [selectable]="false"> <mat-chip class="animals">{{element.patient?.name}}</mat-chip> </mat-chip-list> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let element; columns: displayedColumns;" [ngClass]="element === dateSelected? 'clickedClass' : ''" (click)="dateSelected = element" style="cursor: pointer;" ></mat-row> </mat-table> <mat-paginator *ngIf="dataSource.data" [pageSizeOptions]="[10, 15, 25, 35]" showFirstLastButtons></mat-paginator> <ng-template #loading> <div class="row w-100 justify-content-center text-center"> <div class="col-4"></div> <div class="col-4 text-center"> <div class="row"> <div class="row mt-3"> <div class="col"> <h2>Cargando información...</h2> </div> </div> <div class="row my-2"> <div class="col-4"></div> <div class="col-4 pe-0"> <mat-spinner color="accent" class="w-100" [diameter]="40"></mat-spinner> </div> <div class="col-4 ps-0"></div> </div> </div> </div> <div class="col-4"></div> </div> </ng-template> </div> </div> </div> </div> </div>
package com.fnmain.controller; import com.fnmain.pojo.Result; import com.fnmain.pojo.User; import com.fnmain.service.UserService; import com.fnmain.utils.JwtUtil; import com.fnmain.utils.Md5Util; import com.fnmain.utils.ThreadLocalUtil; import jakarta.validation.constraints.Pattern; import org.hibernate.validator.constraints.URL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.util.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/user") @Validated public class UserController { @Autowired private UserService userService; @Autowired private StringRedisTemplate stringRedisTemplate; @PostMapping("/register") public Result register(@Pattern(regexp="^\\S{5,16}$") String username, @Pattern(regexp="^\\S{5,16}$") String password) { User user = userService.findByUserName(username); if (user == null) { userService.register(username, password); return Result.success(); } return Result.error("用户名称已将被占用"); } @PostMapping("/login") public Result<String> login(@Pattern(regexp="^\\S{5,16}$") String username, @Pattern(regexp="^\\S{5,16}$") String password) { User user = userService.findByUserName(username); if (user == null) { return Result.error("用户不存在"); } if (Md5Util.getMD5String(password).equals(user.getPassword())) { //登陆成功 Map<String, Object> claims = new HashMap<>(); claims.put("id", user.getId()); claims.put("username", user.getUsername()); String token = JwtUtil.genToken(claims); //将token存储到redis中 ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.set(token, token, 1, TimeUnit.HOURS); return Result.success(token); } return Result.error("密码错误"); } @GetMapping("/userInfo") public Result<User> userInfo() { Map<String, Object> map = ThreadLocalUtil.get(); String username = (String) map.get("username"); return Result.success(userService.findByUserName(username)); } @PutMapping("/update") public Result update(@RequestBody @Validated User user) { System.out.println(user.getEmail()); userService.update(user); return Result.success(); } @PatchMapping("/updateAvatar") public Result updateAvatar(@RequestParam @URL String avatarUrl) { Map<String, Object> map = ThreadLocalUtil.get(); Integer id = (Integer) map.get("id"); userService.updateAvatar(avatarUrl, id); return Result.success(); } @PatchMapping("/updatePwd") public Result updatePassword(@RequestBody Map<String, String> params, @RequestHeader("Autorization") String token) { //1.校验参数 String oldPwd = params.get("old_pwd"); String newPwd = params.get("new_pwd"); String rePwd = params.get("re_pwd"); if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) { return Result.error("缺少必要的参数"); } //原来的密码是否正确 //调用userService根据用户名字拿到原密码, 再和old Map<String, Object> map = ThreadLocalUtil.get(); String username = (String) map.get("username"); User loginUser = userService.findByUserName(username); if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) { return Result.error("原密码填写不正确"); } //newPwd和rePwd if (!rePwd.equals(newPwd)) { return Result.error("两次填写的新密码不一样"); } //2.调用server完成密码更新 userService.updatePwd(newPwd); //删除redis中对应的token ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.getOperations().delete(token); return Result.success(); } }
import { GetServerSideProps } from "next" import { Box, Button, FormControl, Grid, MenuItem, Select, TextField, Typography, } from "@mui/material" import { ShopLayout } from "@/components/layouts" import { jwt, countries } from "@/utils" import { useForm } from "react-hook-form" import Cookies from "js-cookie" import { useRouter } from "next/router" import { useContext, useEffect } from "react" import { CartContext } from "@/context" type FormData = { firstName: string lastName: string address: string address2: string zip: string city: string country: string phone: string } const getAddressFormCookies = (): FormData => { return { firstName: Cookies.get("firstName") || "", lastName: Cookies.get("lastName") || "", address: Cookies.get("address") || "", address2: Cookies.get("address2") || "", zip: Cookies.get("zip") || "", city: Cookies.get("city") || "", country: Cookies.get("country") || "ARG", phone: Cookies.get("phone") || "", } } const AddressPage = () => { const router = useRouter() const { updateAddress } = useContext(CartContext) const { register, handleSubmit, formState: { errors }, } = useForm<FormData>({ defaultValues: getAddressFormCookies(), }) const onSubmitAddress = (data: FormData) => { updateAddress(data) router.push("/checkout/summary") } return ( <ShopLayout title="Dirección" pageDescription="Confirmar dirección de destino" > <form onSubmit={handleSubmit(onSubmitAddress)}> <Typography variant="h1" component="h1"> Dirección </Typography> <Grid container spacing={2} sx={{ mt: 2 }}> <Grid item xs={12} sm={6}> <TextField label="Nombre" variant="filled" fullWidth {...register("firstName", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.firstName} helperText={errors.firstName?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <TextField label="Apellido" variant="filled" fullWidth {...register("lastName", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.lastName} helperText={errors.lastName?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <TextField label="Dirección" variant="filled" fullWidth {...register("address", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.address} helperText={errors.address?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <TextField label="Dirección 2 (opcional)" variant="filled" fullWidth {...register("address2")} error={!!errors.address2} helperText={errors.address2?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <TextField label="Código Postal" variant="filled" fullWidth {...register("zip", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.zip} helperText={errors.zip?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <TextField label="Ciudad" variant="filled" fullWidth {...register("city", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.city} helperText={errors.city?.message} ></TextField> </Grid> <Grid item xs={12} sm={6}> <FormControl fullWidth> <TextField select variant="filled" label="País" defaultValue="ARG" {...register("country", { required: "Este campo es requerido", })} error={!!errors.country} helperText={errors.country?.message} > {countries.map((country) => ( <MenuItem value={country.code} key={country.code} > {country.name} </MenuItem> ))} </TextField> </FormControl> </Grid> <Grid item xs={12} sm={6}> <TextField label="Teléfono" variant="filled" fullWidth {...register("phone", { required: "Este campo es requerido", minLength: { value: 2, message: "Mínimo 2 caracteres", }, })} error={!!errors.phone} helperText={errors.phone?.message} ></TextField> </Grid> </Grid> <Box sx={{ mt: 5 }} display="flex" justifyContent="center"> <Button type="submit" color="secondary" className="circular-btn" size="large" > Revisar pedido </Button> </Box> </form> </ShopLayout> ) } // export const getServerSideProps: GetServerSideProps = async ({ req }) => { // const { token = "" } = req.cookies // let isValidToken = false // try { // await jwt.isValidToken(token) // isValidToken = true // } catch (error) { // isValidToken = false // } // if (!isValidToken) { // return { // redirect: { // destination: "/auth/login?p=/checkout/address", // permanent: false, // }, // } // } // return { // props: {}, // } // } export default AddressPage
'use client' import { useState } from "react" import { useRouter } from "next/navigation" import Link from "next/link" import { signIn } from "next-auth/react" export default function LoginForm () { const router = useRouter() const [data , setData] = useState({ email: "", password : "" , }) const handleSubmit = async e => { e.preventDefault() try { const response = await signIn('credentials',{ ...data , redirect : false }) if(response.error) { return Response.json({message : 'connection lost'} , {status : 501}) } router.push('/dashboard') } catch (error) { alert('sometime went wrong ... please try again') } } return ( <div className="grid place-items-center h-screen "> <div className="flex flex-col gap-6 border-2 p-10 rounded-md border-teal-400 shadow-xl"> <h1 className="font-bold text-2xl">Enter the details</h1> <form className="flex flex-col items-start gap-4 " onSubmit={handleSubmit}> <input onChange={e => setData({...data , email : e.target.value})} value={data.email} type="email" placeholder="Email" className="border-2 p-3"/> <input onChange={e => setData({...data , password :e.target.value})} value={data.password} type="password" placeholder="Password" className="border-2 p-3" /> <button type="submit" className="text-white bg-teal-600 text-center w-full mt-4 p-2 rounded-md cursor-pointer">Login</button> <p className="text-right text-sm">Don't have an account?<Link href='/' className="underline">Register</Link></p> </form> </div> </div> ) }
import { ListItem, ListItemButton, ListItemIcon, ListItemText } from '@mui/material'; import { useRouter } from 'next/dist/client/router'; import { MouseEvent } from 'react'; import { BaseListItemProps } from '.'; const LinkListItem: React.FC<BaseListItemProps> = ({ item }) => { const router = useRouter(); // routerでページ遷移を行う const handleOnClick = (e: MouseEvent<HTMLAnchorElement>) => { e.preventDefault(); router.push(item.href); }; return ( <ListItem secondaryAction={item.secondaryAction}> <ListItemButton component="a" href={item.href} onClick={handleOnClick}> {item.icon ? <ListItemIcon>{item.icon}</ListItemIcon> : null} <ListItemText inset primary={item.text} /> </ListItemButton> </ListItem> ); }; export default LinkListItem;
package com.bosen.product.controller.admin; import com.bosen.common.constant.response.PageData; import com.bosen.common.constant.response.ResponseData; import com.bosen.product.service.IProductCategoryBrandService; import com.bosen.product.vo.request.ProductCategoryBrandQueryVO; import com.bosen.product.vo.request.ProductCategoryBrandUpsertVO; import com.bosen.product.vo.response.ProductCategoryBrandDetailVO; import com.bosen.product.vo.response.ProductCategoryWithBrandVO; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; /** * 平台品类品牌 * @author Lucas * @version 2.0.0 * @date 2023/3/3 */ @RestController @RequestMapping("/product/category/brand") public class ProductCategoryBrandController { @Resource private IProductCategoryBrandService categoryBrandService; /** * 分页查询 * @param queryVO 参数 * @return 结果 */ @GetMapping("/pageList") public ResponseData<PageData<ProductCategoryBrandDetailVO>> pageList(ProductCategoryBrandQueryVO queryVO) { return categoryBrandService.pageList(queryVO); } /** * 查询所有品类品牌 * @param queryVO 参数 * @return 结果 */ @GetMapping("/listForMobile") @Cacheable(cacheNames = "product:category:brand", key = "'list'", unless = "!(#result?.code == 200)") public ResponseData<List<ProductCategoryWithBrandVO>> listForMobile(ProductCategoryBrandQueryVO queryVO) { return categoryBrandService.listForMobile(queryVO); } /** * 新增/修改 品类品牌 * @return 结果 */ @PostMapping("/upsertCategoryBrand") public ResponseData<Void> upsertCategoryBrand(@RequestBody @Valid ProductCategoryBrandUpsertVO upsertVO) { return categoryBrandService.upsertCategoryBrand(upsertVO); } /** * 删除 * @param ids ids * @return 结果 */ @PostMapping("/deleteByIds") public ResponseData<Void> deleteByIds(@RequestBody List<Long> ids) { return ResponseData.judge(categoryBrandService.removeBatchByIds(ids)); } }
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import dash_table as dtb import dash_daq as daq from datetime import datetime, timedelta from utils.dash_helpers import parse_options import pandas as pd import bing_maps_smartcity as bms from data.bingmaps_data import pp_roadworks, pl_roadworks ################## # Row 0 - Functionality Tree ################## func_tree = html.Div([ dbc.Button([ html.Img(src = './static/down-icon.png', className = 'icon d-inline-block mb-1', ), ], id = 'roadworks_tree_button', outline=False, className = 'tree_button'), dbc.Collapse([ dbc.Card([ dbc.CardHeader('Functionality Tree', className = 'card_header'), html.Img(src='./static/Showcase UI Roadworks.jpg', style=dict(height = '500px')), ], className = 'card py-2') ],id="roadworks_tree_collapse",)]) ################## # Roadwork Map ################## bing_map = dbc.Card([ dbc.CardHeader('Roadwork Map', className = 'card_header'), bms.BingMaps( id = 'roadwork_map', polylines = pl_roadworks, pushpins = pp_roadworks, ) ], className = 'card', style={'height': '400px'}) ################## # Roadwork Details ################## rwd_header = dbc.Row([ dbc.Col(html.Img(src='./static/roadworksSign_details.png', className = 'rw_icon', style={'verticalAlign': 'middle'}), width = 4, style= {'textAlign': 'center'}), dbc.Col([ html.P('Select pushpin/table entry to view the details', id='rwd_header', className='detail_head'), html.P(id='rwd_id'), ], width=8) ]) rwd_schedule = html.Div([ dbc.Row([ dbc.Col(html.P('Started', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_start', className='detail_info')], width = 7), ]), dbc.Row([ dbc.Col(html.P('Due Date', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_end', className='detail_info')], width = 7), ]), dbc.Row([ dbc.Col(html.P('Est. Completion', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_est', className='detail_info')], width = 7), ], id = 'rwd_est_div') ]) rwd_location = dbc.Row([ dbc.Col(html.P('Location', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_loc', className='detail_info')], width = 7), ]) rwd_obstractions = html.Div([ dbc.Row([ dbc.Col(html.P('Speed Limit', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_speed', className='detail_info')], width = 7), ]), dbc.Row([ dbc.Col(html.P('Open Lanes', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_lanes', className='detail_info')], width = 7), ]) ]) rwd_description = html.Div([ dbc.Row([ dbc.Col(html.P('Phase', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_phase', className='detail_info')], width = 7), ]), dbc.Row([ dbc.Col(html.P('Description', className='detail_title'), width = 5), dbc.Col([html.P('-', id='rwd_desc', className='detail_info')], width = 7), ]) ]) # details layout rw_details = dbc.Card([ dbc.CardHeader('Roadwork Details', className='card_header'), html.Div([ rwd_header, html.Hr(), rwd_schedule, html.Hr(), rwd_location, html.Hr(), rwd_obstractions, html.Hr(), rwd_description ], className='p-2 alert_box'), ], className='card', style={'height': '400px'}) ################## # Roadwork Table ################## table_col = {'id': 'Index', 'address': 'Address', 'measure': 'Measure', 'start': 'Starting Date', 'end': 'Exp. End Date'} df_rw = pd.DataFrame([item['metadata'] for item in pp_roadworks])[list(table_col.keys())] # add state column (if start is in the future -> proposed, end in the past -> completed, rest -> work in progress) # if estimated end key exists then take this as official scheduled end date def calc_state(row): selected_pp = [p for p in pp_roadworks if p['metadata']['id'] == row['id']][0] now = datetime.now() start = datetime.strptime(row['start'], '%d.%m.%Y') end_date = 'end' if 'estimated' not in selected_pp else 'estimated' try: end = datetime.strptime(row[end_date], '%d.%m.%Y') except ValueError: end = datetime.strptime(row[end_date], '%m.%Y') if now < start: val = 'scheduled' elif end < now: val = 'completed' elif start < now < end: val = 'in progress' return val df_rw['state'] = df_rw.apply(calc_state, axis=1) table_col['state'] = 'State' # change display of end date try: df_rw['end'] = pd.to_datetime(df_rw['end'], format='%m.%Y').dt.strftime('%B %Y') except: pass # renaming columns df_rw = df_rw.rename(columns=table_col) # font-family to be used dbc_ff = '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"' rw_table = dbc.Card([ dbc.CardHeader('Roadwork Table', className='card_header'), dtb.DataTable( id = 'rw_table', data = df_rw.to_dict('records'), columns = [{'name': col, 'id': col, 'hidden': True} if col == table_col['id'] else {'name': col, 'id': col} for col in df_rw.columns], # fixed_rows={ 'headers': True, 'data': 0 }, # style_table = {'minHeight': '50px', 'overflowY': 'auto', 'height': '350px'}, style_header = { 'backgroundColor': '#323232', 'font-family': dbc_ff, 'font-size': '16px', 'font-weight': 'bold', 'color' : 'gold' }, style_cell = { 'backgroundColor': '#323232', 'color': 'white', 'height': '44px', 'padding': '8px', 'border-bottom': '1px solid #7b7b7b', 'border-top': '1px solid #7b7b7b', 'font-family': dbc_ff, 'font-size': '16px', 'cursor': 'pointer', 'overflow': 'ellipsis', 'text-align': 'left' }, style_data_conditional = [{ 'if': {'column_id': table_col['state'], 'filter_query': f'{{{table_col["state"]}}} eq "scheduled"'}, 'color': '#e7b416' }, { 'if': {'column_id': table_col['state'], 'filter_query': f'{{{table_col["state"]}}} eq "completed"'}, 'color': '#99c140' }, { 'if': {'column_id': table_col['state'], 'filter_query': f'{{{table_col["state"]}}} eq "in progress"'}, 'color': '#cc3232' }], style_as_list_view = True, # dash-table v4.0.0 has autosize to parent bug, this code takes care of it # last selector disables selection colors (are now the same as defined in style_cell above) css = [{"selector": "div.row.row-1", "rule": "width: 100%;" }, {"selector": "div.cell.cell-1-1", "rule": "width: 100%;" }, {"selector": "table", "rule": "width: 100%;" }, {"selector": '.dash-spreadsheet-container table', "rule": '--accent:#ffffff !important; --selected-background:#676a6f !important;' }] )], className = 'card', style = dict(height = '100%')) ################## # Main Layout ################## layout = html.Div([ dbc.Row(dbc.Col(func_tree)), dbc.Row([dbc.Col(html.Div(id='rwc', style={'color': 'white'}))]), dbc.Row([ dbc.Col(bing_map, width = 8), dbc.Col(rw_details, width = 4), ], className = 'py-1'), html.Div(rw_table, className = 'py-1'), html.Div(id = 'test', className = 'text-white'), html.Div(id = 'roadworks_intermediate', className = 'd-none') ])
package io.nagurea.smsupsdk.contacts.deduplicate; import io.nagurea.smsupsdk.common.TestIntBase; import io.nagurea.smsupsdk.common.status.ResponseStatus; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockserver.configuration.ConfigurationProperties; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.HttpResponse; import org.mockserver.model.HttpStatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockserver.model.HttpRequest.request; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SpringConfiguration.class) class DeduplicateServiceTest extends TestIntBase { private static final String LIST_ID = "50433"; /** * Useless. Only here to show how services could be used with Spring */ @Autowired private DeduplicateService deduplicateService; private static ClientAndServer mockServer; @BeforeAll public static void startMockSMSUpServer() { ConfigurationProperties.logLevel("DEBUG"); mockServer = startMockServer(); mockServer.when( request() .withPath("/list/deduplicate/" + LIST_ID ) .withMethod("PUT") .withHeader("Authorization", EXPECTED_TOKEN) ).respond( HttpResponse.response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody( "{\n" + " \"status\": 1,\n" + " \"message\": \"OK\",\n" + " \"removed\": 4\n" + "}" ) ); } @AfterAll static void stopMockserver(){ mockServer.stop(); } @Test void deduplicate() throws IOException { //given //expected results final DeduplicateResultResponse expectedResponse = DeduplicateResultResponse.builder() .message(ResponseStatus.OK.getDescription()) .removed(4) .build(); final int expectedStatusCode = 200; //given arguments //when final DeduplicateResponse result = deduplicateService.deduplicate(YOUR_TOKEN, LIST_ID); final Integer effectiveStatusCode = result.getStatusCode(); final DeduplicateResultResponse effectiveResponse = result.getEffectiveResponse(); //then assertEquals(expectedStatusCode, effectiveStatusCode); assertEquals(expectedResponse, effectiveResponse); } }
package com.example.myfitness.DataAccessObjects import android.content.Context import android.util.Log import com.example.myfitness.utils.Hash import com.google.android.gms.tasks.Task import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import kotlinx.coroutines.tasks.await import model.User object UsersDAO { fun AddUser(username: String, email: String, password: String) : Task<DocumentReference> { val db = Firebase.firestore val user = hashMapOf( "username" to username, "email" to email, "password" to password ) var result = false return db.collection("users").add(user) } suspend fun GetUserByUsername(username: String) : Boolean { val db = Firebase.firestore val user = db.collection("users") .whereEqualTo("username", username) .get().await() return user.size() > 0 } suspend fun GetUserByEmail(email: String) : Boolean { val db = Firebase.firestore val user = db.collection("users") .whereEqualTo("email", email) .get().await() return user.size() > 0 } suspend fun LoginUser(username: String, password: String) : Boolean { val db = Firebase.firestore val user = db.collection("users") .whereEqualTo("username", username) .whereEqualTo("password", password) .get().await() return user.size() > 0 } suspend fun EditUser(context: Context, username: String, email: String, password: String, weight: Double) { val db = Firebase.firestore val currentUser = getCurrentUser(context) val userRef = db.collection("users").whereEqualTo("username", currentUser) val document = userRef.get().await() if (document.size() > 0) { val user = document.documents[0].reference val updates = HashMap<String, Any>() updates["username"] = username updates["email"] = email updates["weight"] = weight if (!password.isEmpty()) { updates["password"] = Hash.hashPassword(password) } user.update(updates).await() } else { Log.d("EditUser", "Nije moguce promijeniti podatke") } } fun getCurrentUser(context : Context) : String { val prefs = context.getSharedPreferences("user", Context.MODE_PRIVATE) return prefs.getString("username", "")!! } suspend fun getUserInfo(context: Context) : MutableList<User> { val db = Firebase.firestore val userList = mutableListOf<User>() val currentUser = getCurrentUser(context) val users = db.collection("users").whereEqualTo("username", currentUser) try { val result = users.get().await() for (document in result) { val user = document.toObject(User::class.java) userList.add(user) } return userList } catch (e: Exception) { throw e } } }
from argparse import ArgumentParser from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast, no_type_check import matplotlib.pyplot as plt import numpy as np import pandas as pd from numpy import ndarray from pandas import DataFrame, Series ROOT = Path(__file__).resolve().parent JSONS = sorted(ROOT.rglob("*.json")) def min_format(df: DataFrame) -> str: float_fmts = ( "3.0f", # number "0.3f", # val_acc "3.0f", # start "3.0f", # complete "3.0f", # trained "1.2e", # L2 "1.2e", # LR "3.0f", # cbam "3.0f", # cbamr "3.0f", # c_depth "3.0f", # c_dil "3.0f", # c_kern "3.0f", # c_norm "3.0f", # c_n_grp "3.0f", # c_n_lay "3.0f", # c_resid "3.0f", # l_dil "3.0f", # l_n_hid "0.2f", # l_drop "3.0f", # l_kern "3.0f", # l_norm "3.0f", # l_n_grp "3.0f", # l_n_lay "", # state ) return df.to_markdown(tablefmt="simple", floatfmt=float_fmts, index=False) def get_htune_table(df: DataFrame, show: bool = False) -> Tuple[DataFrame, pd.Timedelta]: def renamer(s: str) -> str: if "params" not in s: s = f"{s}_" return s def format_time(t: pd.Timedelta) -> str: """Convert ms to readable""" hrs = t.total_seconds() / 3600 return f"{hrs:0.1f} hrs" shortened = { "params_conv_num_layers": "c_n_lay", "params_conv_kernel": "c_kern", "params_conv_dilation": "c_dil", "params_conv_residual": "c_resid", "params_conv_depthwise": "c_depth", "params_conv_norm": "c_norm", "params_conv_norm_groups": "c_n_grp", "params_conv_cbam": "cbam", "params_conv_cbam_reduction_log2": "cbam_r", "params_lstm_num_layers": "l_n_lay", "params_lstm_hidden_sizes_log2": "l_n_hid", "params_lstm_kernel_sizes": "l_kern", "params_lstm_dilations": "l_dil", "params_lstm_norm": "l_norm", "params_lstm_norm_groups_factor": "l_n_grp", "params_lstm_inner_spatial_dropout": "l_drop", "params_LR": "LR", "params_L2": "L2", "value_": "val_acc_max", "datetime_start_": "start", "datetime_complete_": "complete", "duration_": "trained", "state_": "state", "number_": "id", } renamed = df.rename(mapper=renamer, axis=1).rename(mapper=shortened, axis=1) renamed.start = pd.to_datetime(renamed.start, unit="ms").round("min").astype(str).str[5:-3] renamed.complete = ( pd.to_datetime(renamed.complete, unit="ms").round("min").astype(str).str[5:-3] ) renamed.trained = renamed.trained.apply(pd.Timedelta, unit="ms") total_time = renamed.trained.sum() renamed.trained = renamed.trained.apply(format_time) for col in renamed.columns: if "system_attrs" in col: renamed.drop(columns=col, inplace=True) if show: print(min_format(renamed)) print(f"Total time hypertuning: {format_time(total_time)}") return renamed, total_time def get_best_n(df: DataFrame, n: int = 5) -> DataFrame: table = df.dropna().sort_values(by="val_acc_max", ascending=False) hrs = table.trained.str.replace(" hrs", "").apply(lambda s: float(s)) table = table.loc[hrs > 0.8] best = table.iloc[:n] return best if __name__ == "__main__": N = 10 parser = ArgumentParser() parser.add_argument("--long", action="store_true") long = parser.parse_args().long times = [] tables: List[DataFrame] = [] exps = [] for json in JSONS: df = pd.read_json(json) experiment = json.stem.upper() print(experiment) table, time = get_htune_table(df, show=long) tables.append(table) times.append(time.total_seconds() / 3600) exps.append(experiment) print("\n\nBest models:\n") for table, exp, time in zip(tables, exps, times): if exp == "CONV3DTOCONVLSTM3D_EIGIMG": exp = "CONV3DTOCONVLSTM3D_EIGIMG_[125,175]" best = get_best_n(table, N) counts, edges = np.histogram(table.dropna().val_acc_max) percents = np.round(100 * counts / np.sum(counts), 2) print("=" * 80) print(f"{exp} ({np.round(time, 1)} hours / {len(table)} models evaluated)") print("=" * 80) print("val_acc distribution:\n") for i, percent in enumerate(percents): print( f" [{np.round(edges[i], 3):0.3f}, {np.round(edges[i+1], 3):0.3f}]: {percent:4.1f}%" ) print(f"\n{exp} Best {N}:") print(min_format(best)) print("=" * 80) print(f"Total time tuning all models: {np.sum(times)} hours")
<template> <v-container> <v-row> <v-col> <PhotoCard :image_src="rex_ying_image_src" name="Rex Ying" role="Instructor" ></PhotoCard> </v-col> </v-row> <v-row> <v-col v-for="p in staff"> <PhotoCard v-bind="p" /> </v-col> </v-row> </v-container> </template> <script lang="ts"> import { defineComponent } from "vue"; import PhotoCard from "@/components/PhotoCard.vue"; export default defineComponent({ components: { PhotoCard }, data: () => ({ rex_ying_image_src: new URL( "../assets/photos/ying_rex.jpg", import.meta.url ).href, staff: [ // { // name: "Rex Ying", // image_src: "https://cs.stanford.edu/people/rexy/images/photo_Rex.jpg", // role: "Instructor", // }, // { // name: "Jialin Chen", // image_src: new URL("../assets/photos/chen_jialin.jpg", import.meta.url) // .href, // role: "Head TA", // }, // { // name: "Agastya Rana", // image_src: new URL("../assets/photos/rana_agastya.jpg", import.meta.url) // .href, // role: "TA", // }, // { // name: "Yuhang Chen", // image_src: new URL("../assets/photos/chen_yuhang.jpg", import.meta.url) // .href, // role: "TA", // }, // { // name: "Matt Soleimani", // image_src: new URL("../assets/photos/soleimani_matt.png", import.meta.url) // .href, // role: "TA", // }, // { // name: "Meili Gupta", // image_src: new URL("../assets/photos/gupta_meili.png", import.meta.url) // .href, // role: "ULA", // }, // { // name: "Weikang Qiu", // image_src: new URL("../assets/photos/qiu_weikang.png", import.meta.url) // .href, // role: "Grader", // }, { name: "Josh Beal", image_src: new URL("../assets/photos/josh_beal.jpg", import.meta.url) .href, role: "Teaching Assistant", }, { name: "Derek Dong", image_src: new URL("../assets/photos/derek_dong.jpg", import.meta.url) .href, role: "Undergraduate Learning Assistant", }, { name: "Ngoc Bui", image_src: new URL("../assets/photos/ngoc_bui.jpg", import.meta.url) .href, role: "Grader", }, ], }), }); </script>
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name')->default('')->comment('呢称'); $table->string('email')->unique(); $table->string('password'); $table->string('avatar')->default('')->comment('头像'); $table->string('city')->default('')->comment('城市'); $table->tinyInteger('gender')->default(0)->comment('性别'); $table->string('sign')->default('')->comment('签名'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
import React from 'react'; import { graphql } from 'gatsby'; import styled from 'styled-components'; import SEO from '../components/SEO'; const BeersGridStyles = styled.div` display: grid; gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); `; const SingleBeerStyles = styled.div` border: 1px solid var(--grey); padding: 2rem; text-align: center; img { width: 100%; height: 200px; object-fit: contain; display: block; display: grid; align-items: center; font-size: 10px; } `; export default function BeersPage({ data }) { return ( <> <SEO title={`Beers! We have ${data.beers.nodes.length} in stock`} /> <h2 className="center" style={{ marginBottom: '4rem' }}> We have {data.beers.nodes.length} Beers Available. Dine in Only! </h2> <BeersGridStyles> {data.beers.nodes.map((beer) => { if (!beer.name) return null; const rating = Math.round(beer.rating.average); return ( <SingleBeerStyles key={beer.id}> <img src={beer.image} alt={beer.name} /> <h3>{beer.name}</h3> <h4>{beer.price}</h4> <p title={`${rating} out of 5 stars`}> {`⭐`.repeat(rating)} <span style={{ filter: `grayscale(100%)`, }} > {`⭐`.repeat(5 - rating)} </span> <span>({beer.rating.reviews})</span> </p> </SingleBeerStyles> ); })} </BeersGridStyles> </> ); } export const query = graphql` query { beers: allBeer { nodes { id name price image rating { reviews average } } } } `;
<template> <div class="rounded-2xl bg-white py-6 px-6 flex items-center justify-center"> <div class="flex flex-col items-center"> <h3 class="uppercase text-paperdazgray-500 font-semibold text-center mb-4 text-xl" > Free Account </h3> <div class="circle circle-75 border-4 border-[#B7EF94] mx-auto p-0.5 mb-2" > <div @click="PopUpFileInput" class="circle w-full h-full border-2 border-[#B7EF94] p-1 cursor-pointer" > <img :src="profilePhoto" class="circle w-full h-full profilePhoto" alt="" /> <input ref="profileInput" @input="uploadProfilePicture" type="file" class="hidden" accept="image/x-png,image/jiff,image/jpeg,image/jpg" /> </div> </div> <p class="text-lg font-semibold mb-2 capitalize"> {{ `${user.firstName} ${user.lastName}` }} </p> <!-- <div class="border border-paperdazgray-100 inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full" > <p class="mr-2">{{ `${(user || {}).totalLeavesEarned}` }}</p> <single-leaf-no-stalk /> </div> --> </div> </div> </template> <script> import Vue from 'vue' import SingleLeafNoStalk from '../svg-icons/SingleLeafNoStalk.vue' import login from "~/mixins/login" import mixins from 'vue-typed-mixins' export default mixins(login).extend({ name: 'FreeProductCard', components: { SingleLeafNoStalk }, computed: { user() { return this.$auth.user }, profilePhoto() { return this.$store.getters.profilePhoto }, }, methods: { PopUpFileInput() { try { (this.$refs?.profileInput).click() } catch (err) { console.log(err) } }, async uploadProfilePicture(event) { let fileInput = event.target if(fileInput.files.length < 1 || (fileInput.files[0].size / 1024 / 1024) > 2){ this.$notify.error({ message: 'File size must be less than 2MB', }) return } let formdata = new FormData() formdata.append('upload', fileInput.files[0], 'user-profile-picture.jpg') formdata.append('type', 'profilePicture') formdata.append('userId', (this.user).id) this.$axios .$patch(`/files`, formdata) .then(async () => { //@ts-ignore this.filterUsers() }) .catch(() => { this.$notify.error({ message: 'Unable to upload profile picture', }) }) }, }, }) </script>
# 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. import base64 from barbican.common import config from barbican.common import utils from barbican.model import models from barbican.model import repositories from barbican.plugin.crypto import base from barbican.plugin.crypto import manager from barbican.plugin.interface import secret_store as sstore CONF = config.new_config() config.parse_args(CONF) class StoreCryptoContext(object): """Context for crypto-adapter secret store plugins. This context object allows access to core Barbican resources such as datastore models. """ def __init__( self, project_model, secret_model=None, private_secret_model=None, public_secret_model=None, passphrase_secret_model=None, content_type=None): self.secret_model = secret_model self.private_secret_model = private_secret_model self.public_secret_model = public_secret_model self.passphrase_secret_model = passphrase_secret_model self.project_model = project_model self.content_type = content_type class StoreCryptoAdapterPlugin(object): """Secret store plugin adapting to 'crypto' devices as backend. HSM-style 'crypto' devices perform encryption/decryption processing but do not actually store the encrypted information, unlike other 'secret store' plugins that do provide storage. Hence, this adapter bridges between these two plugin styles, providing Barbican persistence services as needed to store information. Note that this class does not inherit from SecretStoreBase, as it also requires access to lower-level datastore entities such as KEKDatum. This additional information is passed in via the 'context' parameter. """ def __init__(self): super(StoreCryptoAdapterPlugin, self).__init__() def store_secret(self, secret_dto, context): """Store a secret. :param secret_dto: SecretDTO for secret :param context: StoreCryptoContext for secret :returns: an optional dictionary containing metadata about the secret """ # Find HSM-style 'crypto' plugin. encrypting_plugin = manager.get_manager().get_plugin_store_generate( base.PluginSupportTypes.ENCRYPT_DECRYPT, project_id=context.project_model.id ) # Find or create a key encryption key metadata. kek_datum_model, kek_meta_dto = _find_or_create_kek_objects( encrypting_plugin, context.project_model) # Secrets are base64 encoded before being passed to the secret stores. secret_bytes = base64.b64decode(secret_dto.secret) encrypt_dto = base.EncryptDTO(secret_bytes) # Enhance the context with content_type, This is needed to build # datum_model to store if not context.content_type: context.content_type = secret_dto.content_type # Create an encrypted datum instance and add the encrypted cyphertext. response_dto = encrypting_plugin.encrypt( encrypt_dto, kek_meta_dto, context.project_model.external_id ) # Convert binary data into a text-based format. _store_secret_and_datum( context, context.secret_model, kek_datum_model, response_dto) return None def get_secret(self, secret_type, metadata, context): """Retrieve a secret. :param secret_type: secret type :param metadata: secret metadata :param context: StoreCryptoContext for secret :returns: SecretDTO that contains secret """ if (not context.secret_model or not context.secret_model.encrypted_data): raise sstore.SecretNotFoundException() # TODO(john-wood-w) Need to revisit 1 to many datum relationship. datum_model = context.secret_model.encrypted_data[0] # Find HSM-style 'crypto' plugin. decrypting_plugin = manager.get_manager().get_plugin_retrieve( datum_model.kek_meta_project.plugin_name) # wrap the KEKDatum instance in our DTO kek_meta_dto = base.KEKMetaDTO(datum_model.kek_meta_project) # Convert from text-based storage format to binary. encrypted = base64.b64decode(datum_model.cypher_text) decrypt_dto = base.DecryptDTO(encrypted) # Decrypt the secret. secret = decrypting_plugin.decrypt(decrypt_dto, kek_meta_dto, datum_model.kek_meta_extended, context.project_model.external_id) secret = base64.b64encode(secret) key_spec = sstore.KeySpec(alg=context.secret_model.algorithm, bit_length=context.secret_model.bit_length, mode=context.secret_model.mode) return sstore.SecretDTO(secret_type, secret, key_spec, datum_model.content_type) def delete_secret(self, secret_metadata): """Delete a secret.""" pass def generate_symmetric_key(self, key_spec, context): """Generate a symmetric key. :param key_spec: KeySpec that contains details on the type of key to generate :param context: StoreCryptoContext for secret :returns: a dictionary that contains metadata about the key """ # Find HSM-style 'crypto' plugin. plugin_type = _determine_generation_type(key_spec.alg) if base.PluginSupportTypes.SYMMETRIC_KEY_GENERATION != plugin_type: raise sstore.SecretAlgorithmNotSupportedException(key_spec.alg) generating_plugin = manager.get_manager().get_plugin_store_generate( plugin_type, key_spec.alg, key_spec.bit_length, key_spec.mode, project_id=context.project_model.id) # Find or create a key encryption key metadata. kek_datum_model, kek_meta_dto = _find_or_create_kek_objects( generating_plugin, context.project_model) # Create an encrypted datum instance and add the created cypher text. generate_dto = base.GenerateDTO(key_spec.alg, key_spec.bit_length, key_spec.mode, None) # Create the encrypted meta. response_dto = generating_plugin.generate_symmetric( generate_dto, kek_meta_dto, context.project_model.external_id) # Convert binary data into a text-based format. _store_secret_and_datum( context, context.secret_model, kek_datum_model, response_dto) return None def generate_asymmetric_key(self, key_spec, context): """Generates an asymmetric key. Returns a AsymmetricKeyMetadataDTO object containing metadata(s) for asymmetric key components. The metadata can be used to retrieve individual components of asymmetric key pair. """ plugin_type = _determine_generation_type(key_spec.alg) if base.PluginSupportTypes.ASYMMETRIC_KEY_GENERATION != plugin_type: raise sstore.SecretAlgorithmNotSupportedException(key_spec.alg) generating_plugin = manager.get_manager().get_plugin_store_generate( plugin_type, key_spec.alg, key_spec.bit_length, project_id=context.project_model.id) # Find or create a key encryption key metadata. kek_datum_model, kek_meta_dto = _find_or_create_kek_objects( generating_plugin, context.project_model) generate_dto = base.GenerateDTO(key_spec.alg, key_spec.bit_length, None, key_spec.passphrase) # Create the encrypted meta. private_key_dto, public_key_dto, passwd_dto = ( generating_plugin.generate_asymmetric( generate_dto, kek_meta_dto, context.project_model.external_id ) ) _store_secret_and_datum( context, context.private_secret_model, kek_datum_model, private_key_dto) _store_secret_and_datum( context, context.public_secret_model, kek_datum_model, public_key_dto) if key_spec.passphrase and passwd_dto: _store_secret_and_datum( context, context.passphrase_secret_model, kek_datum_model, passwd_dto) return sstore.AsymmetricKeyMetadataDTO() def generate_supports(self, key_spec): """Key generation supported? Specifies whether the plugin supports key generation with the given key_spec. """ return (key_spec and (key_spec.alg.lower() in sstore.KeyAlgorithm.ASYMMETRIC_ALGORITHMS or key_spec.alg.lower() in sstore.KeyAlgorithm.SYMMETRIC_ALGORITHMS)) def store_secret_supports(self, key_spec): """Key storage supported? Specifies whether the plugin supports storage of the secret given the attributes included in the KeySpec """ return True def _determine_generation_type(algorithm): """Determines the type based on algorithm.""" if not algorithm: raise sstore.SecretAlgorithmNotSupportedException(algorithm) symmetric_algs = base.PluginSupportTypes.SYMMETRIC_ALGORITHMS asymmetric_algs = base.PluginSupportTypes.ASYMMETRIC_ALGORITHMS if algorithm.lower() in symmetric_algs: return base.PluginSupportTypes.SYMMETRIC_KEY_GENERATION elif algorithm.lower() in asymmetric_algs: return base.PluginSupportTypes.ASYMMETRIC_KEY_GENERATION else: raise sstore.SecretAlgorithmNotSupportedException(algorithm) def _find_or_create_kek_objects(plugin_inst, project_model): kek_repo = repositories.get_kek_datum_repository() # Find or create a key encryption key. full_plugin_name = utils.generate_fullname_for(plugin_inst) kek_datum_model = kek_repo.find_or_create_kek_datum(project_model, full_plugin_name) # Bind to the plugin's key management. # TODO(jwood): Does this need to be in a critical section? Should the # bind operation just be declared idempotent in the plugin contract? kek_meta_dto = base.KEKMetaDTO(kek_datum_model) if not kek_datum_model.bind_completed: kek_meta_dto = plugin_inst.bind_kek_metadata(kek_meta_dto) # By contract, enforce that plugins return a # (typically modified) DTO. if kek_meta_dto is None: raise base.CryptoKEKBindingException(full_plugin_name) _indicate_bind_completed(kek_meta_dto, kek_datum_model) kek_repo.save(kek_datum_model) return kek_datum_model, kek_meta_dto def _store_secret_and_datum( context, secret_model, kek_datum_model, generated_dto): # Create Secret entities in data store. if not secret_model.id: secret_model.project_id = context.project_model.id repositories.get_secret_repository().create_from(secret_model) # setup and store encrypted datum datum_model = models.EncryptedDatum(secret_model, kek_datum_model) datum_model.content_type = context.content_type datum_model.cypher_text = base64.b64encode(generated_dto.cypher_text) datum_model.kek_meta_extended = generated_dto.kek_meta_extended repositories.get_encrypted_datum_repository().create_from( datum_model) def _indicate_bind_completed(kek_meta_dto, kek_datum): """Updates the supplied kek_datum instance Updates the kek_datum per the contents of the supplied kek_meta_dto instance. This function is typically used once plugins have had a chance to bind kek_meta_dto to their crypto systems. :param kek_meta_dto: :param kek_datum: :return: None """ kek_datum.bind_completed = True kek_datum.algorithm = kek_meta_dto.algorithm kek_datum.bit_length = kek_meta_dto.bit_length kek_datum.mode = kek_meta_dto.mode kek_datum.plugin_meta = kek_meta_dto.plugin_meta
/* LZ4 - Fast LZ compression algorithm Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - LZ4 homepage : http://www.lz4.org - LZ4 source repository : https://github.com/lz4/lz4 */ /* * This file contains unmodified code from lz4 1.9.3's decompressor, plus * associated macros and constants. * * It also contains a couple of defines from the old lz4.c to make things * fit together smoothly. * */ #include <sys/zfs_context.h> int LZ4_uncompress_unknownOutputSize(const char *source, char *dest, int isize, int maxOutputSize); /* * Tuning parameters */ /* * COMPRESSIONLEVEL: Increasing this value improves compression ratio * Lowering this value reduces memory usage. Reduced memory usage * typically improves speed, due to cache effect (ex: L1 32KB for Intel, * L1 64KB for AMD). Memory usage formula : N->2^(N+2) Bytes * (examples : 12 -> 16KB ; 17 -> 512KB) */ #define COMPRESSIONLEVEL 12 /* * NOTCOMPRESSIBLE_CONFIRMATION: Decreasing this value will make the * algorithm skip faster data segments considered "incompressible". * This may decrease compression ratio dramatically, but will be * faster on incompressible data. Increasing this value will make * the algorithm search more before declaring a segment "incompressible". * This could improve compression a bit, but will be slower on * incompressible data. The default value (6) is recommended. */ #define NOTCOMPRESSIBLE_CONFIRMATION 6 /* * Little Endian or Big Endian? * Note: overwrite the below #define if you know your architecture endianness. */ #if defined(_ZFS_BIG_ENDIAN) #define LZ4_BIG_ENDIAN 1 #else /* * Little Endian assumed. PDP Endian and other very rare endian format * are unsupported. */ #undef LZ4_BIG_ENDIAN #endif /*-************************************ * CPU Feature Detection **************************************/ /* LZ4_FORCE_MEMORY_ACCESS * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. * The below switch allow to select different access method for improved performance. * Method 0 (default) : use `memcpy()`. Safe and portable. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. * Method 2 : direct access. This method is portable but violate C standard. * It can generate buggy code on targets which assembly generation depends on alignment. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. * Prefer these methods in priority order (0 > 1 > 2) */ #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ # if defined(__GNUC__) && \ ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) # define LZ4_FORCE_MEMORY_ACCESS 2 # elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) # define LZ4_FORCE_MEMORY_ACCESS 1 # endif #endif /* * LZ4_FORCE_SW_BITCOUNT * Define this parameter if your target system or compiler does not support hardware bit count */ /* * Illumos : we can't use GCC's __builtin_ctz family of builtins in the * kernel * Linux : we can use GCC's __builtin_ctz family of builtins in the * kernel */ #undef LZ4_FORCE_SW_BITCOUNT #if defined(__sunos__) #define LZ4_FORCE_SW_BITCOUNT #endif /* * Compiler Options */ /* Disable restrict */ #define restrict /* * Linux : GCC_VERSION is defined as of 3.9-rc1, so undefine it. * torvalds/linux@3f3f8d2f48acfd8ed3b8e6b7377935da57b27b16 */ #ifdef GCC_VERSION #undef GCC_VERSION #endif #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) #ifndef LZ4_FORCE_INLINE # ifdef _MSC_VER /* Visual Studio */ # define LZ4_FORCE_INLINE static __forceinline # else # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ # ifdef __GNUC__ # define LZ4_FORCE_INLINE static inline __attribute__((always_inline)) # else # define LZ4_FORCE_INLINE static inline # endif # else # define LZ4_FORCE_INLINE static # endif /* __STDC_VERSION__ */ # endif /* _MSC_VER */ #endif /* LZ4_FORCE_INLINE */ /* LZ4_FORCE_O2 and LZ4_FORCE_INLINE * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8, * together with a simple 8-byte copy loop as a fall-back path. * However, this optimization hurts the decompression speed by >30%, * because the execution does not go to the optimized loop * for typical compressible data, and all of the preamble checks * before going to the fall-back path become useless overhead. * This optimization happens only with the -O3 flag, and -O2 generates * a simple 8-byte copy loop. * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8 * functions are annotated with __attribute__((optimize("O2"))), * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute * of LZ4_wildCopy8 does not affect the compression speed. */ #if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__) # define LZ4_FORCE_O2 __attribute__((optimize("O2"))) # undef LZ4_FORCE_INLINE # define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"),always_inline)) #else # define LZ4_FORCE_O2 #endif #ifndef expect #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) # define expect(expr,value) (__builtin_expect ((expr),(value)) ) #else # define expect(expr,value) (expr) #endif #endif #ifndef likely #define likely(expr) expect((expr) != 0, 1) #endif #ifndef unlikely #define unlikely(expr) expect((expr) != 0, 0) #endif #ifndef _KERNEL #include <stdlib.h> /* malloc, calloc, free */ #include <string.h> /* memset, memcpy */ #endif #define ALLOC(s) malloc(s) #define ALLOC_AND_ZERO(s) calloc(1,s) #define FREEMEM(p) free(p) #define MEM_INIT(p,v,s) memset((p),(v),(s)) /*-************************************ * Common Constants **************************************/ #define MINMATCH 4 #define WILDCOPYLENGTH 8 #define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ #define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ #define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ #define FASTLOOP_SAFE_DISTANCE 64 #define KB *(1 <<10) #define MB *(1 <<20) #define GB *(1U<<30) #ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */ # define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */ #endif #define LZ4_DISTANCE_ABSOLUTE_MAX 65535 #if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */ # error "LZ4_DISTANCE_MAX is too big : must be <= 65535" #endif #define ML_BITS 4 #define ML_MASK ((1U<<ML_BITS)-1) #define RUN_BITS (8-ML_BITS) #define RUN_MASK ((1U<<RUN_BITS)-1) #define DEBUGLOG(l, ...) {} /* disabled */ #ifndef assert #define assert ASSERT #endif /*-************************************ * Types **************************************/ #ifndef _KERNEL #include <limits.h> #endif #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) #ifndef _KERNEL #include <stdint.h> #endif typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; typedef uintptr_t uptrval; #else # if UINT_MAX != 4294967295UL # error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4" # endif typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; typedef size_t uptrval; /* generally true, except OpenVMS-64 */ #endif #if defined(__x86_64__) typedef U64 reg_t; /* 64-bits in x32 mode */ #else typedef size_t reg_t; /* 32-bits in x32 mode */ #endif typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive; /*-************************************ * Reading and writing into memory **************************************/ /** * LZ4 relies on memcpy with a constant size being inlined. In freestanding * environments, the compiler can't assume the implementation of memcpy() is * standard compliant, so it can't apply its specialized memcpy() inlining * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze * memcpy() as if it were standard compliant, so it can inline it in freestanding * environments. This is needed when decompressing the Linux Kernel, for example. */ #if defined(__GNUC__) && (__GNUC__ >= 4) #define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) #else #define LZ4_memcpy(dst, src, size) memcpy(dst, src, size) #endif static unsigned LZ4_isLittleEndian(void) { const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ return one.c[0]; } #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) /* lie to the compiler about data alignment; use with caution */ static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ /* currently only defined for gcc and icc */ typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } #else /* safe and portable access using memcpy() */ static U16 LZ4_read16(const void* memPtr) { U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; } static void LZ4_write32(void* memPtr, U32 value) { LZ4_memcpy(memPtr, &value, sizeof(value)); } #endif /* LZ4_FORCE_MEMORY_ACCESS */ static U16 LZ4_readLE16(const void* memPtr) { if (LZ4_isLittleEndian()) { return LZ4_read16(memPtr); } else { const BYTE* p = (const BYTE*)memPtr; return (U16)((U16)p[0] + (p[1]<<8)); } } /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ LZ4_FORCE_INLINE void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd) { BYTE* d = (BYTE*)dstPtr; const BYTE* s = (const BYTE*)srcPtr; BYTE* const e = (BYTE*)dstEnd; do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e); } static const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; #ifndef LZ4_FAST_DEC_LOOP # if defined __i386__ || defined _M_IX86 || defined __x86_64__ || defined _M_X64 # define LZ4_FAST_DEC_LOOP 1 # elif defined(__aarch64__) && !defined(__clang__) /* On aarch64, we disable this optimization for clang because on certain * mobile chipsets, performance is reduced with clang. For information * refer to https://github.com/lz4/lz4/pull/707 */ # define LZ4_FAST_DEC_LOOP 1 # else # define LZ4_FAST_DEC_LOOP 0 # endif #endif #if LZ4_FAST_DEC_LOOP LZ4_FORCE_INLINE void LZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset) { assert(srcPtr + offset == dstPtr); if (offset < 8) { LZ4_write32(dstPtr, 0); /* silence an msan warning when offset==0 */ dstPtr[0] = srcPtr[0]; dstPtr[1] = srcPtr[1]; dstPtr[2] = srcPtr[2]; dstPtr[3] = srcPtr[3]; srcPtr += inc32table[offset]; LZ4_memcpy(dstPtr+4, srcPtr, 4); srcPtr -= dec64table[offset]; dstPtr += 8; } else { LZ4_memcpy(dstPtr, srcPtr, 8); dstPtr += 8; srcPtr += 8; } LZ4_wildCopy8(dstPtr, srcPtr, dstEnd); } /* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd * this version copies two times 16 bytes (instead of one time 32 bytes) * because it must be compatible with offsets >= 16. */ LZ4_FORCE_INLINE void LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd) { BYTE* d = (BYTE*)dstPtr; const BYTE* s = (const BYTE*)srcPtr; BYTE* const e = (BYTE*)dstEnd; do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e); } /* LZ4_memcpy_using_offset() presumes : * - dstEnd >= dstPtr + MINMATCH * - there is at least 8 bytes available to write after dstEnd */ LZ4_FORCE_INLINE void LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset) { BYTE v[8]; assert(dstEnd >= dstPtr + MINMATCH); switch(offset) { case 1: MEM_INIT(v, *srcPtr, 8); break; case 2: LZ4_memcpy(v, srcPtr, 2); LZ4_memcpy(&v[2], srcPtr, 2); LZ4_memcpy(&v[4], v, 4); break; case 4: LZ4_memcpy(v, srcPtr, 4); LZ4_memcpy(&v[4], srcPtr, 4); break; default: LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); return; } LZ4_memcpy(dstPtr, v, 8); dstPtr += 8; while (dstPtr < dstEnd) { LZ4_memcpy(dstPtr, v, 8); dstPtr += 8; } } #endif /*-************************************ * Local Structures and types **************************************/ typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; /** * This enum distinguishes several different modes of accessing previous * content in the stream. * * - noDict : There is no preceding content. * - withPrefix64k : Table entries up to ctx->dictSize before the current blob * blob being compressed are valid and refer to the preceding * content (of length ctx->dictSize), which is available * contiguously preceding in memory the content currently * being compressed. * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere * else in memory, starting at ctx->dictionary with length * ctx->dictSize. * - usingDictCtx : Like usingExtDict, but everything concerning the preceding * content is in a separate context, pointed to by * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table * entries in the current context that refer to positions * preceding the beginning of the current compression are * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx * ->dictSize describe the location and size of the preceding * content, and matches are found by looking in the ctx * ->dictCtx->hashTable. */ typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; /*-******************************* * Decompression functions ********************************/ typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; typedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error; LZ4_FORCE_INLINE unsigned read_variable_length(const BYTE**ip, const BYTE* lencheck, int loop_check, int initial_check, variable_length_error* error) { U32 length = 0; U32 s; if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ *error = initial_error; return length; } do { s = **ip; (*ip)++; length += s; if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ *error = loop_error; return length; } } while (s==255); return length; } #define LZ4_STATIC_ASSERT(c) ASSERT(c) /*! LZ4_decompress_generic() : * This generic decompression function covers all use cases. * It shall be instantiated several times, using different sets of directives. * Note that it is important for performance that this function really get inlined, * in order to remove useless branches during compilation optimization. */ LZ4_FORCE_INLINE int LZ4_decompress_generic( const char* const src, char* const dst, int srcSize, int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */ earlyEnd_directive partialDecoding, /* full, partial */ dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ const BYTE* const dictStart, /* only if dict==usingExtDict */ const size_t dictSize /* note : = 0 if noDict */ ) { if ((src == NULL) || (outputSize < 0)) { return -1; } { const BYTE* ip = (const BYTE*) src; const BYTE* const iend = ip + srcSize; BYTE* op = (BYTE*) dst; BYTE* const oend = op + outputSize; BYTE* cpy; const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; const int safeDecode = (endOnInput==endOnInputSize); const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); /* Set up the "end" pointers for the shortcut. */ const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; const BYTE* match; size_t offset; unsigned token; size_t length; DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize); /* Special cases */ assert(lowPrefix <= op); if ((endOnInput) && (unlikely(outputSize==0))) { /* Empty output buffer */ if (partialDecoding) return 0; return ((srcSize==1) && (*ip==0)) ? 0 : -1; } if ((!endOnInput) && (unlikely(outputSize==0))) { return (*ip==0 ? 1 : -1); } if ((endOnInput) && unlikely(srcSize==0)) { return -1; } /* Currently the fast loop shows a regression on qualcomm arm chips. */ #if LZ4_FAST_DEC_LOOP if ((oend - op) < FASTLOOP_SAFE_DISTANCE) { DEBUGLOG(6, "skip fast decode loop"); goto safe_decode; } /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ while (1) { /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ assert(oend - op >= FASTLOOP_SAFE_DISTANCE); if (endOnInput) { assert(ip < iend); } token = *ip++; length = token >> ML_BITS; /* literal length */ assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ /* decode literal length */ if (length == RUN_MASK) { variable_length_error error = ok; length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); if (error == initial_error) { goto _output_error; } if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ /* copy literals */ cpy = op+length; LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); if (endOnInput) { /* LZ4_decompress_safe() */ if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; } LZ4_wildCopy32(op, ip, cpy); } else { /* LZ4_decompress_fast() */ if (cpy>oend-8) { goto safe_literal_copy; } LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : * it doesn't know input length, and only relies on end-of-block properties */ } ip += length; op = cpy; } else { cpy = op+length; if (endOnInput) { /* LZ4_decompress_safe() */ DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length); /* We don't need to check oend, since we check it once for each loop below */ if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; } /* Literals can only be 14, but hope compilers optimize if we copy by a register size */ LZ4_memcpy(op, ip, 16); } else { /* LZ4_decompress_fast() */ /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : * it doesn't know input length, and relies on end-of-block properties */ LZ4_memcpy(op, ip, 8); if (length > 8) { LZ4_memcpy(op+8, ip+8, 8); } } ip += length; op = cpy; } /* get offset */ offset = LZ4_readLE16(ip); ip+=2; match = op - offset; assert(match <= op); /* get matchlength */ length = token & ML_MASK; if (length == ML_MASK) { variable_length_error error = ok; if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); if (error != ok) { goto _output_error; } if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */ length += MINMATCH; if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { goto safe_match_copy; } } else { length += MINMATCH; if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { goto safe_match_copy; } /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ if ((dict == withPrefix64k) || (match >= lowPrefix)) { if (offset >= 8) { assert(match >= lowPrefix); assert(match <= op); assert(op + 18 <= oend); LZ4_memcpy(op, match, 8); LZ4_memcpy(op+8, match+8, 8); LZ4_memcpy(op+16, match+16, 2); op += length; continue; } } } if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ /* match starting within external dictionary */ if ((dict==usingExtDict) && (match < lowPrefix)) { if (unlikely(op+length > oend-LASTLITERALS)) { if (partialDecoding) { DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd"); length = MIN(length, (size_t)(oend-op)); } else { goto _output_error; /* end-of-block condition violated */ } } if (length <= (size_t)(lowPrefix-match)) { /* match fits entirely within external dictionary : just copy */ memmove(op, dictEnd - (lowPrefix-match), length); op += length; } else { /* match stretches into both external dictionary and current block */ size_t const copySize = (size_t)(lowPrefix - match); size_t const restSize = length - copySize; LZ4_memcpy(op, dictEnd - copySize, copySize); op += copySize; if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ BYTE* const endOfMatch = op + restSize; const BYTE* copyFrom = lowPrefix; while (op < endOfMatch) { *op++ = *copyFrom++; } } else { LZ4_memcpy(op, lowPrefix, restSize); op += restSize; } } continue; } /* copy match within block */ cpy = op + length; assert((op <= oend) && (oend-op >= 32)); if (unlikely(offset<16)) { LZ4_memcpy_using_offset(op, match, cpy, offset); } else { LZ4_wildCopy32(op, match, cpy); } op = cpy; /* wildcopy correction */ } safe_decode: #endif /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ while (1) { token = *ip++; length = token >> ML_BITS; /* literal length */ assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ /* A two-stage shortcut for the most common case: * 1) If the literal length is 0..14, and there is enough space, * enter the shortcut and copy 16 bytes on behalf of the literals * (in the fast mode, only 8 bytes can be safely copied this way). * 2) Further if the match length is 4..18, copy 18 bytes in a similar * manner; but we ensure that there's enough space in the output for * those 18 bytes earlier, upon entering the shortcut (in other words, * there is a combined check for both stages). */ if ( (endOnInput ? length != RUN_MASK : length <= 8) /* strictly "less than" on input, to re-enter the loop with at least one byte */ && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { /* Copy the literals */ LZ4_memcpy(op, ip, endOnInput ? 16 : 8); op += length; ip += length; /* The second stage: prepare for match copying, decode full info. * If it doesn't work out, the info won't be wasted. */ length = token & ML_MASK; /* match length */ offset = LZ4_readLE16(ip); ip += 2; match = op - offset; assert(match <= op); /* check overflow */ /* Do not deal with overlapping matches. */ if ( (length != ML_MASK) && (offset >= 8) && (dict==withPrefix64k || match >= lowPrefix) ) { /* Copy the match. */ LZ4_memcpy(op + 0, match + 0, 8); LZ4_memcpy(op + 8, match + 8, 8); LZ4_memcpy(op +16, match +16, 2); op += length + MINMATCH; /* Both stages worked, load the next token. */ continue; } /* The second stage didn't work out, but the info is ready. * Propel it right to the point of match copying. */ goto _copy_match; } /* decode literal length */ if (length == RUN_MASK) { variable_length_error error = ok; length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); if (error == initial_error) { goto _output_error; } if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ } /* copy literals */ cpy = op+length; #if LZ4_FAST_DEC_LOOP safe_literal_copy: #endif LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) ) || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) { /* We've either hit the input parsing restriction or the output parsing restriction. * In the normal scenario, decoding a full block, it must be the last sequence, * otherwise it's an error (invalid input or dimensions). * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow. */ if (partialDecoding) { /* Since we are partial decoding we may be in this block because of the output parsing * restriction, which is not valid since the output buffer is allowed to be undersized. */ assert(endOnInput); DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end") DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length); DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op)); DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip)); /* Finishing in the middle of a literals segment, * due to lack of input. */ if (ip+length > iend) { length = (size_t)(iend-ip); cpy = op + length; } /* Finishing in the middle of a literals segment, * due to lack of output space. */ if (cpy > oend) { cpy = oend; assert(op<=oend); length = (size_t)(oend-op); } } else { /* We must be on the last sequence because of the parsing limitations so check * that we exactly regenerate the original size (must be exact when !endOnInput). */ if ((!endOnInput) && (cpy != oend)) { goto _output_error; } /* We must be on the last sequence (or invalid) because of the parsing limitations * so check that we exactly consume the input and don't overrun the output buffer. */ if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) { DEBUGLOG(6, "should have been last run of literals") DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend); DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend); goto _output_error; } } memmove(op, ip, length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */ ip += length; op += length; /* Necessarily EOF when !partialDecoding. * When partialDecoding, it is EOF if we've either * filled the output buffer or * can't proceed with reading an offset for following match. */ if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) { break; } } else { LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ ip += length; op = cpy; } /* get offset */ offset = LZ4_readLE16(ip); ip+=2; match = op - offset; /* get matchlength */ length = token & ML_MASK; _copy_match: if (length == ML_MASK) { variable_length_error error = ok; length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); if (error != ok) goto _output_error; if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ } length += MINMATCH; #if LZ4_FAST_DEC_LOOP safe_match_copy: #endif if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ /* match starting within external dictionary */ if ((dict==usingExtDict) && (match < lowPrefix)) { if (unlikely(op+length > oend-LASTLITERALS)) { if (partialDecoding) length = MIN(length, (size_t)(oend-op)); else goto _output_error; /* doesn't respect parsing restriction */ } if (length <= (size_t)(lowPrefix-match)) { /* match fits entirely within external dictionary : just copy */ memmove(op, dictEnd - (lowPrefix-match), length); op += length; } else { /* match stretches into both external dictionary and current block */ size_t const copySize = (size_t)(lowPrefix - match); size_t const restSize = length - copySize; LZ4_memcpy(op, dictEnd - copySize, copySize); op += copySize; if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ BYTE* const endOfMatch = op + restSize; const BYTE* copyFrom = lowPrefix; while (op < endOfMatch) *op++ = *copyFrom++; } else { LZ4_memcpy(op, lowPrefix, restSize); op += restSize; } } continue; } assert(match >= lowPrefix); /* copy match within block */ cpy = op + length; /* partialDecoding : may end anywhere within the block */ assert(op<=oend); if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { size_t const mlen = MIN(length, (size_t)(oend-op)); const BYTE* const matchEnd = match + mlen; BYTE* const copyEnd = op + mlen; if (matchEnd > op) { /* overlap copy */ while (op < copyEnd) { *op++ = *match++; } } else { LZ4_memcpy(op, match, mlen); } op = copyEnd; if (op == oend) { break; } continue; } if (unlikely(offset<8)) { LZ4_write32(op, 0); /* silence msan warning when offset==0 */ op[0] = match[0]; op[1] = match[1]; op[2] = match[2]; op[3] = match[3]; match += inc32table[offset]; LZ4_memcpy(op+4, match, 4); match -= dec64table[offset]; } else { LZ4_memcpy(op, match, 8); match += 8; } op += 8; if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ if (op < oCopyLimit) { LZ4_wildCopy8(op, match, oCopyLimit); match += oCopyLimit - op; op = oCopyLimit; } while (op < cpy) { *op++ = *match++; } } else { LZ4_memcpy(op, match, 8); if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); } } op = cpy; /* wildcopy correction */ } /* end of decoding */ if (endOnInput) { DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst)); return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ } else { return (int) (((const char*)ip)-src); /* Nb of input bytes read */ } /* Overflow error detected */ _output_error: return (int) (-(((const char*)ip)-src))-1; } } /* * LZ4_uncompress_unknownOutputSize() : * isize : is the input size, therefore the compressed size * maxOutputSize : is the size of the destination buffer (which must be * already allocated) * return : the number of bytes decoded in the destination buffer * (necessarily <= maxOutputSize). If the source stream is * malformed, the function will stop decoding and return a * negative result, indicating the byte position of the faulty * instruction. This function never writes beyond dest + * maxOutputSize, and is therefore protected against malicious * data packets. * note : Destination buffer must be already allocated. * This version is slightly slower than real_LZ4_uncompress() * */ /* * Note: In upstream code, LZ4_uncompress_unknownOutputSize is now a legacy * wrapper for LZ4_decompress_safe which is a wrapper for * LZ4_decompress_generic; this wrapper flattens that, rather than * rewriting the callers. */ int LZ4_uncompress_unknownOutputSize(const char* source, char* dest, int compressedSize, int maxDecompressedSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, decode_full_block, noDict, (BYTE*)dest, NULL, 0); }
import { useEffect, useState } from "react"; import { Chat } from "./components/core/Chat"; import Auth from "./components/core/Auth/Auth.tsx"; import { getItemFromLS, removeItemFromLS, setItemToLS, } from "./utils/localStorage.ts"; import SideBar from "./components/core/SideBar/SideBar.tsx"; import { Group, PrivateRoom, RoomType, RoomsType } from "../types/Rooms.ts"; import { User } from "../types/Users.ts"; import { socket } from "./adapters/socket.ts"; import { useMediaQuery, useDisclosure } from "@mantine/hooks"; import { Messages } from "../types/Messages.ts"; import { useResizable } from "react-resizable-layout"; import { SplitterForResize } from "./components/shared/SplitterForResize"; import { ID, SelectedImage } from "../types/PublicTypes.ts"; import useEmojiPickerStore from "./store/useEmojiPickerStore.ts"; import AppHeader from "./components/core/AppHeader/AppHeader.tsx"; import Modal from "./components/shared/Modal/Modal.tsx"; import UserProfile from "./components/core/UserProfile/UserProfile.tsx"; function App() { const [user, setUser] = useState<User | null>(null); const [rooms, setRooms] = useState<RoomsType>([]); const [room, setRoom] = useState<RoomType | null>(null); const [messages, setMessages] = useState<Messages | null>(null); const matches = useMediaQuery("(max-width: 765px)"); const [areMessagesLoading, setAreMessagesLoading] = useState(false); const [areRoomsLoading, setAreRoomsLoading] = useState(true); const [filteredChats, setFilteredChats] = useState<RoomsType | null>(null); const [addedRoomId, setAddedRoomId] = useState<ID | null>(null); const [selectedImages, setSelectedImages] = useState<SelectedImage[]>([]); const userFromLS: User = getItemFromLS("user"); const { currentEmojiId, closeEmojiPicker } = useEmojiPickerStore(); const [ isUserProfileOpened, { open: openUserProfile, close: closeUserProfile }, ] = useDisclosure(false); const { isDragging: isLeftBarDragging, position: leftBarCurrentWidth, splitterProps: leftBarDragBarProps, } = useResizable({ axis: "x", initial: 500, min: 315, max: 500, }); const createUser = (name: string) => { const updateUserData = (data: User) => { setUser(data); setItemToLS("user", data); }; const handleUserCreation = (newUser: User) => { updateUserData(newUser); }; const handleUserExists = (user: User) => { updateUserData(user); }; const handleUserCreationFailed = (message: string) => { console.log("User creation failed!: ", message); }; socket.emit("create_user", name); socket.on("user_created", handleUserCreation); socket.on("user_exists", handleUserExists); socket.on("user_creation_failed", handleUserCreationFailed); }; const updateUser = () => { socket.emit("get_user", userFromLS.id); socket.on("user_got", (newUser) => { setUser(newUser); setItemToLS("user", newUser); }); }; const loadMessages = () => { if (room) { socket.emit( "get_messages", (room as Group).members ? room.id : (room as PrivateRoom).commonId, ); socket.on("messages_got", (messages) => { setAreMessagesLoading(false); setMessages(messages); }); } }; const handleLogOut = () => { socket.emit("user_disconnect", user?.id); setUser(null); removeItemFromLS("user"); setMessages(null); setRoom(null); setRooms([]); }; const fetchAllRooms = (roomIds: ID[]) => { socket.emit("get_rooms", roomIds); socket.on("rooms_got", (rooms) => { setAreRoomsLoading(false); setRooms(rooms); }); }; const joinRoom = (id: ID | string) => { if (!id) return; socket.emit("join_room", id); }; const handleAddRoomLocally = (room: RoomType) => { setAddedRoomId(room.id); setRooms((prevRooms) => !prevRooms.some((r) => r.id === room.id) ? [room, ...prevRooms] : prevRooms, ); }; const handleEndRoomCreation = (room: RoomType) => { setRoom(room); setAreMessagesLoading(false); setAddedRoomId(null); }; const handleRoomDeleteLocally = (id: ID) => { if (room && id === room.id) { setRoom(null); } setRooms((prevRooms) => { return prevRooms.filter((room: RoomType) => room.id !== id); }); setRoom(null); }; useEffect(() => { if (userFromLS) updateUser(); setAreRoomsLoading(true); socket.on("send_group", handleAddRoomLocally); socket.on("group_created", (group: Group) => { if (user && group.creators[0] === user.id) { handleEndRoomCreation(group); joinRoom(group.id); return; } setAreMessagesLoading(false); setAddedRoomId(null); }); socket.on("send_private-room_to_opponent", (newPrivateRoom) => { setRooms((prevRooms) => [newPrivateRoom, ...prevRooms]); setFilteredChats( (prevChats) => prevChats && [...prevChats, newPrivateRoom], ); }); socket.on("private-room_created", handleEndRoomCreation); socket.on("group_deleted", handleRoomDeleteLocally); socket.on("group_credentials_updated", (updatedGroupCredentials) => { setRoom( (prevRoom) => prevRoom && { ...prevRoom, ...updatedGroupCredentials, id: prevRoom.id, }, ); setRooms((prevRooms) => { return prevRooms.map((room) => { if (room.id === updatedGroupCredentials.id) { return { ...room, ...updatedGroupCredentials, id: room.id, }; } return room; }); }); }); return () => { socket.off("send_group"); socket.off("update_group_credentials"); socket.off("private-room_created"); socket.off("group_deleted"); socket.off("group_credentials_updated"); socket.off("send_private-room_to_opponent"); socket.off("group_created"); socket.off("create_user"); socket.off("user_created"); socket.off("user_exists"); socket.off("user_creation_failed"); socket.off("get_user"); socket.off("failed_get_messages"); }; // eslint-disable-next-line }, [socket]); useEffect(() => { loadMessages(); socket.on("failed_get_messages", () => { setAreMessagesLoading(false); setMessages(null); }); return () => { socket.off("failed_get_messages"); }; // eslint-disable-next-line }, [room]); useEffect(() => { if (user) fetchAllRooms(user?.rooms); }, [user]); return ( <div className={`flex md:pb-10 ${ !user && "items-center justify-center" } h-screen flex-col`} > {!userFromLS ? ( <Auth createUser={createUser} /> ) : ( <> {user ? ( <> <AppHeader room={room} user={user} openUserProfileModal={openUserProfile} /> <main className={`flex h-full flex-col ${ user && "md:min-h-[500px] md:px-52" }`} > <div className="flex h-full md:rounded-md md:rounded-tl-none md:rounded-tr-none md:border-b-2 md:border-l-2 md:border-r-2 md:border-slate-600"> {matches ? ( !room ? ( <SideBar user={user} addedRoomId={addedRoomId} setAddedRoomId={setAddedRoomId} setSelectedImages={setSelectedImages} areRoomsLoading={areRoomsLoading} setRooms={setRooms} setAreMessagesLoading={setAreMessagesLoading} rooms={rooms} room={room} setRoom={setRoom} filteredChats={filteredChats} setFilteredChats={setFilteredChats} /> ) : ( <Chat user={user} selectedImages={selectedImages} setSelectedImages={setSelectedImages} messages={messages} areMessagesLoading={areMessagesLoading} setMessages={setMessages} room={room} setRoom={setRoom} setRooms={setRooms} filteredChats={filteredChats} setFilteredChats={setFilteredChats} setAreMessagesLoading={setAreMessagesLoading} rooms={rooms} /> ) ) : ( <> <div style={{ width: leftBarCurrentWidth, overflow: "auto", }} > <SideBar user={user} setSelectedImages={setSelectedImages} setRooms={setRooms} addedRoomId={addedRoomId} setAddedRoomId={setAddedRoomId} setAreMessagesLoading={setAreMessagesLoading} rooms={rooms} room={room} areRoomsLoading={areRoomsLoading} setRoom={setRoom} filteredChats={filteredChats} setFilteredChats={setFilteredChats} /> </div> <SplitterForResize isDragging={isLeftBarDragging} {...leftBarDragBarProps} /> <Chat user={user} messages={messages} areMessagesLoading={areMessagesLoading} setMessages={setMessages} room={room} selectedImages={selectedImages} setSelectedImages={setSelectedImages} setRoom={setRoom} setRooms={setRooms} filteredChats={filteredChats} setFilteredChats={setFilteredChats} setAreMessagesLoading={setAreMessagesLoading} rooms={rooms} /> </> )} </div> <Modal close={closeUserProfile} opened={isUserProfileOpened} title={`${user.name}'s profile`} > <UserProfile user={user} handleLogOut={handleLogOut} closeUserProfileModal={closeUserProfile} setUser={setUser} /> </Modal> {currentEmojiId && ( <div className="fixed left-0 top-0 h-full w-full" onClick={closeEmojiPicker} /> )} </main> </> ) : ( <div className="flex flex-col gap-5"> <h1>The Chat Is Loading...</h1> <p className="max-w-sm text-sm"> <span className="text-yellow-300">Note:</span> Initial loading time may be slightly longer than usual due to the limitations of my server, which is hosted for free. </p> </div> )} </> )} </div> ); } export default App; // TODO // fix mobile issues // FEATURES // - add a profile page.
package noctiluca.features.authentication.templates.scaffold.instancedetail import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import noctiluca.features.authentication.getString import noctiluca.instance.model.Instance @Composable internal fun BoxScope.InstanceDetailActionButtons( instance: Instance, isSignInProgress: Boolean, horizontalPadding: Dp, onClickAuthorize: (Instance) -> Unit, ) = Column( modifier = Modifier.fillMaxWidth() .align(Alignment.BottomCenter) .background(MaterialTheme.colorScheme.surface), ) { Divider(Modifier.fillMaxWidth()) Row( modifier = Modifier.fillMaxWidth() .padding( vertical = 8.dp, horizontal = horizontalPadding, ), horizontalArrangement = Arrangement.End ) { AuthorizeButton(instance, isSignInProgress, onClickAuthorize) } } @Composable private fun AuthorizeButton( instance: Instance, isSignInProgress: Boolean, onClickAuthorize: (Instance) -> Unit, ) { if (isSignInProgress) { OutlinedButton( onClick = {}, enabled = false, ) { CircularProgressIndicator(Modifier.size(20.dp)) } return } Button( onClick = { onClickAuthorize(instance) }, ) { Text(getString().sign_in_request_authentication) } }
import { Component, Injectable, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { PoMenuItem, PoToolbarAction, PoToolbarProfile } from '@po-ui/ng-components'; import { FindEasyService } from './services/findEasy.service'; import { Utils } from './utils/functions.utils'; @Injectable({ providedIn: 'root', }) @Component({ selector: 'fe-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { hideMenu: boolean = false; title = 'Find Easy'; endereco: string = ''; dataHora: string = ''; msgStatus: string = ''; lat: number = 0; lng: number = 0; zoom: number = 18; count: number = 0; typeStatus: any; corTag: any; hasConnection: boolean = false; hideLoading: boolean = true; isContinue: boolean = true; /** * Criação dos itens para o menu do Perfil */ profileActions: Array<PoToolbarAction> = [ { icon: 'po-icon-exit', label: 'Exit', action: this.logoff.bind(this), type: 'danger', }, ]; // Perfil do usuário profileUser: PoToolbarProfile = { avatar: '', title: 'Usuário teste', subtitle: 'usuario@gmail.com', }; // Menus menus: Array<PoMenuItem> = [ { label: 'Home', shortLabel: 'Home', icon: 'po-icon-home', }, ]; toolbarActions: Array<PoToolbarAction> = [ { label: 'Item 1', icon: 'po-icon-folder', separator: true, visible: false, }, ]; constructor(private router: Router, private feService: FindEasyService) { this.hideMenu = this.router.url === '/login'; } ngOnInit(): void { this.configPage(); } configPage() { const userId: string = window.localStorage.getItem('userId'); if (!Utils.isEmpty(window.localStorage.getItem('tokenFE')) && !Utils.isEmpty(userId)) { this.hideLoading = false; this.getInfoUser(userId); } else { this.router.navigate(['/login']); } } logoff() { this.isContinue = false; window.localStorage.clear(); this.hideMenu = true; this.router.navigate(['/login']); } getInfoUser(userId: string) { this.feService.get(`/FindUser/${userId}`, '').subscribe((infoUserId) => { if (infoUserId.data.hasOwnProperty('usuario')) { this.isContinue = true; this.getDados(infoUserId.data.dispositivo); this.profileUser = { title: `${infoUserId.data.nome} ${infoUserId.data.sobrenome}`, subtitle: infoUserId.data.email, avatar: '', }; } this.hideLoading = true; }); } /** * Função responsável por buscar as coordenadas do mapa */ getDados(userId: string) { if (this.isContinue) { this.feService.get(`FindById/${userId}`, 'Get Dados').subscribe((resp) => { if (resp.hasOwnProperty('data') && !Utils.isEmpty(resp.data)) { this.hasConnection = true; const dados = resp.data[0].hasOwnProperty('Atual') ? resp.data[0].Atual : resp.data[0].hasOwnProperty('Anterior') ? resp.data[0].Anterior : undefined; if (!Utils.isEmpty(dados)) { this.lat = dados.latitude; this.lng = dados.longitude; this.dataHora = Utils.makeFormatDate(new Date(dados.data_inclusao)); this.validConnection(resp, dados.data_inclusao); } } this.hideLoading = true; setTimeout(() => { this.getDados(userId); }, 1000); }); } } validConnection(resp, dateResp: string) { const now: Date = new Date(); now.setMinutes(now.getMinutes() - 30); const dateLocation: Date = new Date(dateResp); this.hasConnection = resp.hasOwnProperty('data') && !Utils.isEmpty(resp.data) && dateLocation.getTime() >= now.getTime(); } }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.linhv.repository.impl; import com.linhv.pojo.PostComment; import com.linhv.repository.PostCommentRepository; import java.util.List; import javax.persistence.NoResultException; import javax.persistence.Query; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author prodi */ @Repository @Transactional public class PostCommentRepositoryImpl implements PostCommentRepository{ @Autowired private LocalSessionFactoryBean factory; @Override public List<PostComment> getAllByPostId(String id) { Session s = this.factory.getObject().getCurrentSession(); Query q = s.createQuery("FROM PostComment cmt " + "WHERE cmt.postId.id=:id ORDER BY cmt.updatedDate"); q.setParameter("id", id); return q.getResultList(); } @Override public List<PostComment> getSubsByCommentId(String id) { Session s = this.factory.getObject().getCurrentSession(); Query q = s.createQuery("FROM PostComment cmt " + "WHERE cmt.commentId.id=:id ORDER BY cmt.updatedDate"); q.setParameter("id", id); return q.getResultList(); } @Override public PostComment getById(String id) { Session s = this.factory.getObject().getCurrentSession(); try { return s.get(PostComment.class, id); } catch (NoResultException ex) { ex.printStackTrace(); return null; } } @Override public PostComment add(PostComment comment) { Session s = this.factory.getObject().getCurrentSession(); try { s.save(comment); return comment; } catch (HibernateException ex) { ex.printStackTrace(); return null; } } @Override public boolean update(PostComment comment) { Session s = this.factory.getObject().getCurrentSession(); try { s.update(comment); return true; } catch (HibernateException ex) { ex.printStackTrace(); return false; } } @Override public boolean delete(PostComment comment) { Session s = this.factory.getObject().getCurrentSession(); try { s.delete(comment); return true; } catch (HibernateException ex) { ex.printStackTrace(); return false; } } @Override public int countCommentByPostId(String id) { Session s = this.factory.getObject().getCurrentSession(); Query q = s.createQuery("SELECT COUNT(*) FROM PostComment cmt " + "WHERE cmt.postId.id=:id"); q.setParameter("id", id); return (int) q.getSingleResult(); } @Override public List<PostComment> getAllByUserId(int id) { Session s = this.factory.getObject().getCurrentSession(); Query q = s.createQuery("FROM PostComment cmt WHERE cmt.userId.id=:id"); q.setParameter("id", id); return q.getResultList(); } }
import { ChangeDetectionStrategy, Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { NbDialogRef } from '@nebular/theme'; import { ShopCardComponent } from '..'; import { ThreeJsService } from '../../services'; /** * Компонент модального окна с информацией о точке, в которой находится магазин * @export * @class ShopInfoModalComponent * @implements {AfterViewInit} */ @Component({ selector: 'map-shop-info-modal', templateUrl: './shop-info-modal.component.html', styleUrls: ['./shop-info-modal.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ShopInfoModalComponent implements AfterViewInit { /** * Кол-во этажей * @type {number} * @memberof ShopInfoModalComponent */ public levels: number = 0; /** * Ссылка на канвас * @type {ElementRef<HTMLCanvasElement>} * @memberof ShopInfoModalComponent */ @ViewChild('canvas') public canvasRef: ElementRef<HTMLCanvasElement>; constructor(public dialogRef: NbDialogRef<ShopCardComponent>, private readonly threeJsService: ThreeJsService) {} public ngAfterViewInit(): void { this.threeJsService.initCanvas(this.canvasRef); this.threeJsService.renderBuilding(this.levels); } /** * Закрытие модального окна * @memberof ShopInfoModalComponent */ public close(): void { this.dialogRef.close(); } }
import React from "react"; import { Route, Routes } from "react-router-dom"; import Counter from "./Counter"; import PackagesUsed from "./PackagesUsed"; import ReduxThunk from "./ReduxThunk"; import TodoApp from "./TodoApp"; import Home from "../Pages/Home"; import Login from "../Pages/Login"; import Feeds from "../Pages/Feeds"; import Careers from "../Pages/Careers"; import Posts from "../Pages/Posts"; import RequireAuth from "../hoc/RequireAuth"; const AllRoutes = () => { return ( <Routes> <Route path="/" element={<TodoApp />} /> <Route path="/counter" element={<Counter />} /> <Route path="/packages" element={<PackagesUsed />} /> <Route path="/reduxThunk" element={<ReduxThunk />} /> <Route path="/home" element={<Home />} /> <Route path="login" element={<Login />} /> <Route path="feeds" element={ <RequireAuth> <Feeds /> </RequireAuth> } /> <Route path="careers" element={ <RequireAuth> <Careers /> </RequireAuth> } /> <Route path="posts" element={ <RequireAuth> <Posts /> </RequireAuth> } /> </Routes> ); }; export default AllRoutes;
<a name="readme-top"></a> # Node JS Learings | Topics | Go to Topic | | ----------- | ----------- | | Event Loop and Async Patterns | <a href="#event-loop-and-async-patterns">Link</a> | | Advanced express js : Template engines, serving static files | <a href="#advanced-express-js-template-engines-serving-static-files">Link</a> | | Node JS Buffers and Streams | <a href="#node-js-buffers-and-streams">Link</a> | | ParaNode JS Server Architecture Patternsgraph | <a href="#node-js-server-architecture-patterns">Link</a> | | Node JS Build and Deployment | <a href="#node-js-build-and-deployment">Link</a> | | Node JS Testing, Debugging and Security | <a href="#node-js-testing-debugging-and-security">Link</a> | <!-- Event Loop --> ## Event Loop and Async Patterns - [x] Event Loop - [ ] Node Runtime, Node API protocols - [ ] Callbacks, Promises, Async / Await - [ ] Error handling <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Advanced Express JS --> ## Advanced express js Template engines serving static files - [ ] Serving static files - [ ] Template engines : CSR, SSR, SSG, ISR - [ ] Setting Cache Headers <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Node JS Buffers and Streams --> ## Node JS Buffers and Streams - [ ] Common use cases - [ ] File uploads and downloads <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Node JS Server Architecture Patterns --> ## Node JS Server Architecture Patterns - [ ] Network protocols - [ ] REST APIs : 3 layer Architecture - [ ] GraphQL API - [ ] Real Time applications and WebSocket Communication: Meme Sharing App - [ ] Event Driven Architecture : File processing use case or other use case <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Node JS Build and Deployment --> ## Node JS Build and Deployment - [ ] Basic Deployment options - [ ] Clustering and Process management with PM2 <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Node JS Testing, Debugging and Security --> ## Node JS Testing Debugging and Security - [ ] Testing methods and frameworks - [ ] Debugging options - [ ] Security best practises ## References Building SSG https://www.webdevdrops.com/en/build-static-site-generator-nodejs-8969ebe34b22/ https://github.com/SalsaBoy990/static-site-express https://dev.to/kartiknair/how-to-build-a-simple-static-site-generator-using-node-js-4l01 Node JS Streams https://syndelltech.com/node-js-streams-all-you-need-to-know/ https://www.freecodecamp.org/news/node-js-streams-everything-you-need-to-know-c9141306be93/ https://medium.com/@mohammerat/unlocking-the-power-of-streams-in-node-js-tips-and-tricks-for-optimal-performance-d819f07da40d https://blog.appsignal.com/2022/02/02/use-streams-to-build-high-performing-nodejs-applications.html https://levelup.gitconnected.com/using-streams-in-node-js-real-world-examples-and-performance-benefits-b48b848f377a https://dev.to/mrrishimeena/mastering-nodejs-streams-a-comprehensive-guide-37bb
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import pathOr from 'ramda/src/pathOr'; import { breakpointMedium } from 'config/styles/breakpoints'; const TemperatureInfo = ({ block }) => { const [isCentigrade, setIsCentigrade] = useState(true); let lowEnd = -10; let highEnd = 40; let low = block.temperature_low_in_c || lowEnd; let high = block.temperature_high_in_c || highEnd; if (!isCentigrade) { lowEnd = 10; highEnd = 110; low = block.temperature_low_in_f || lowEnd; high = block.temperature_high_in_f || highEnd; } const marginLeft = (100 * (low - lowEnd)) / (highEnd - lowEnd); const marginRight = (100 * (highEnd - high)) / (highEnd - lowEnd); const conditions = pathOr( '', ['riding_condition_values', 0, 'text'], block ).toLowerCase(); return ( <> <div className="temperature_info__container"> <div className="temperature_info__toggle_container"> <div> <h3>TEMPERATURE RANGE</h3> <p> {pathOr( '', ['temperature_range_description', 0, 'text'], block )} </p> </div> <div className="temperature_info__toggle_container"> <button className={ isCentigrade ? 'temperature_info__button_selected' : 'temperature_info__button' } onClick={() => setIsCentigrade(true)} > ºC </button> <button className={ !isCentigrade ? 'temperature_info__button_selected' : 'temperature_info__button' } onClick={() => setIsCentigrade(false)} > ºF </button> </div> </div> <div className="temperature_info__progress_container"> <div className="temperature_info__progress" /> </div> {isCentigrade ? ( <div className="temperature_info__progress_marks"> <div>{'<-10ºC'}</div> <div>0ºC</div> <div>10ºC</div> <div>20ºC</div> <div>30ºC</div> <div>{'>40ºC'}</div> </div> ) : ( <div className="temperature_info__progress_marks"> <div>{'<10ºF'}</div> <div>30ºF</div> <div>50ºF</div> <div>70ºF</div> <div>90ºF</div> <div>{'>110ºF'}</div> </div> )} <h3>RIDING CONDITIONS</h3> <p> {pathOr( '', ['riding_conditions_description', 0, 'text'], block )} </p> <div className="temperature_info__conditions"> <div className="temperature_info__condition_bar_container"> <div className={ conditions.includes('cold') ? 'temperature_info__condition_bar_selected' : 'temperature_info__condition_bar' } /> <div className="temperature_info__condition_bar_text"> COLD </div> </div> <div className="temperature_info__condition_bar_container"> <div className={ conditions.includes('rain') ? 'temperature_info__condition_bar_selected' : 'temperature_info__condition_bar' } /> <div className="temperature_info__condition_bar_text"> RAIN </div> </div> <div className="temperature_info__condition_bar_container"> <div className={ conditions.includes('wind') ? 'temperature_info__condition_bar_selected' : 'temperature_info__condition_bar' } /> <div className="temperature_info__condition_bar_text"> WIND </div> </div> <div className="temperature_info__condition_bar_container"> <div className={ conditions.includes('hot') ? 'temperature_info__condition_bar_selected' : 'temperature_info__condition_bar' } /> <div className="temperature_info__condition_bar_text"> HOT </div> </div> </div> </div> <style jsx> {` @media (min-width: ${breakpointMedium}) { .temperature_info__container { padding: 0; } } @media (max-width: ${breakpointMedium}) { .temperature_info__container { padding: 0 0 40px 0; } } .temperature_info__content { display: flex; flex-wrap: wrap; } .temperature_info__column { width: 100%; } .temperature_info__bullet { display: flex; flex-direction: row; } img { margin-top: 2px; margin-right: 15px; width: 35px; height: 35px; } .temperature_info__progress { height: 8px; margin-left: ${marginLeft}%; margin-right: ${marginRight}%; background: linear-gradient( 90deg, #f7f7f7, #000000, #f7f7f7 ); } .temperature_info__progress_container { width: 100%; background-color: #ffffff; } .temperature_info__progress_marks { display: flex; flex-direction: row; justify-content: space-between; margin: 10px 0; } .temperature_info__conditions { display: flex; flex-direction: row; justify-content: space-between; } .temperature_info__condition_bar_container { width: 24.5%; } .temperature_info__condition_bar { background-color: #ffffff; height: 8px; } .temperature_info__condition_bar_selected { background-color: #000000; height: 8px; } .temperature_info__condition_bar_text { margin: 10px 0; text-align: center; } .temperature_info__button { border: none; outline: none; background-color: transparent; color: #000000; cursor: pointer; } .temperature_info__button_selected { border: none; outline: none; font-weight: 800; background-color: transparent; color: #000000; cursor: pointer; } .temperature_info__toggle_container { display: flex; flex-direction: row; justify-content: space-between; align-items: center; } h3 { font-weight: 500; font-size: 1em; } p { font-size: 1em; margin: 6px 0; } `} </style> </> ); }; TemperatureInfo.propTypes = { block: PropTypes.object.isRequired, }; export default TemperatureInfo;
import {Link} from "react-router-dom"; import styles from "./MovieCard.module.scss"; interface MovieCardProps{ id: number, title: string; overview: string; popularity: number; poster_path: string; release_date: string; vote_average: number; vote_count: number; image?: string; } const MovieCard =({id, title, overview, popularity, release_date, vote_average, vote_count, image = "/movie-thumb.png"}: MovieCardProps)=>{ return( <div className={styles.card}> <img className={styles.thumbnail} src={image} alt="Movie thumbnail" /> <div className={styles.content}> <div> <Link to={`/movies/${id}`}>{title}</Link> </div> <div className={styles.popularity}>{popularity}</div> <div className={styles.overview}>{overview} </div> <div className={styles.overview}>{release_date} </div> <div className={styles.overview}>{vote_average} </div> <div className={styles.overview}>{vote_count} </div> </div> </div> ); } export default MovieCard;
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import UIKit /** * An object that defines the appearance of bulletin items. */ @objc public class BLTNItemAppearance: NSObject { // MARK: - Color Customization /// The tint color to apply to the action button (default `.link` on iOS 13 and `.blue` on older systems). @objc public var actionButtonColor: UIColor = { if #available(iOS 13.0, *) { return .link } else { return #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) } }() /// The button image to apply to the action button @objc public var actionButtonImage: UIImage? /// The title color to apply to action button (default white). @objc public var actionButtonTitleColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) /// The border color to apply to action button. @objc public var actionButtonBorderColor: UIColor? = nil /// The border width to apply to action button. @objc public var actionButtonBorderWidth: CGFloat = 1.0 /// The title color to apply to the alternative button (default `.link` on iOS 13 and `.blue` on older systems). @objc public var alternativeButtonTitleColor: UIColor = { if #available(iOS 13.0, *) { return .link } else { return #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) } }() /// The border color to apply to the alternative button. @objc public var alternativeButtonBorderColor: UIColor? = nil /// The border width to apply to the alternative button. @objc public var alternativeButtonBorderWidth: CGFloat = 1.0 /// The tint color to apply to the imageView (if image rendered in template mode, default `.link` on iOS 13 and `.blue` on older systems). @objc public var imageViewTintColor: UIColor = { if #available(iOS 13.0, *) { return .link } else { return #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) } }() /// The color of title text labels (default `.secondaryLabel` on iOS 13 and light gray on older systems). @objc public var titleTextColor: UIColor = { if #available(iOS 13.0, *) { return .secondaryLabel } else { return #colorLiteral(red: 0.568627451, green: 0.5647058824, blue: 0.5725490196, alpha: 1) } }() /// The color of description text labels (default `.label` on iOS 13 and black on older systems). @objc public var descriptionTextColor: UIColor = { if #available(iOS 13.0, *) { return .label } else { return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) } }() // MARK: - Corner Radius Customization /// The corner radius of the action button (default 12). @objc public var actionButtonCornerRadius: CGFloat = 12 /// The corner radius of the alternative button (default 12). @objc public var alternativeButtonCornerRadius: CGFloat = 12 // MARK: - Font Customization /// An optional custom font to use for the title label. Set this to nil to use the system font. @objc public var titleFontDescriptor: UIFontDescriptor? /// An optional custom font to use for the description label. Set this to nil to use the system font. @objc public var descriptionFontDescriptor: UIFontDescriptor? /// An optional custom font to use for the buttons. Set this to nil to use the system font. @objc public var buttonFontDescriptor: UIFontDescriptor? /** * Whether the description text should be displayed with a smaller font. * * You should set this to `true` if your text is long (more that two sentences). */ @objc public var shouldUseCompactDescriptionText: Bool = false // MARK: - Font Constants /// The font size of title elements (default 30). @objc public var titleFontSize: CGFloat = 30 /// The font size of description labels (default 20). @objc public var descriptionFontSize: CGFloat = 20 /// The font size of compact description labels (default 15). @objc public var compactDescriptionFontSize: CGFloat = 15 /// The font size of action buttons (default 17). @objc public var actionButtonFontSize: CGFloat = 17 /// The font size of alternative buttons (default 15). @objc public var alternativeButtonFontSize: CGFloat = 15 } // MARK: - Font Factories extension BLTNItemAppearance { /** * Creates the font for title labels. */ @objc public func makeTitleFont() -> UIFont { if let titleFontDescriptor = self.titleFontDescriptor { return UIFont(descriptor: titleFontDescriptor, size: titleFontSize) } else { return UIFont.systemFont(ofSize: titleFontSize, weight: .medium) } } /** * Creates the font for description labels. */ @objc public func makeDescriptionFont() -> UIFont { let size = shouldUseCompactDescriptionText ? compactDescriptionFontSize : descriptionFontSize if let descriptionFontDescriptor = self.descriptionFontDescriptor { return UIFont(descriptor: descriptionFontDescriptor, size: size) } else { return UIFont.systemFont(ofSize: size) } } /** * Creates the font for action buttons. */ @objc public func makeActionButtonFont() -> UIFont { if let buttonFontDescriptor = self.buttonFontDescriptor { return UIFont(descriptor: buttonFontDescriptor, size: actionButtonFontSize) } else { return UIFont.systemFont(ofSize: actionButtonFontSize, weight: .semibold) } } /** * Creates the font for alternative buttons. */ @objc public func makeAlternativeButtonFont() -> UIFont { if let buttonFontDescriptor = self.buttonFontDescriptor { return UIFont(descriptor: buttonFontDescriptor, size: alternativeButtonFontSize) } else { return UIFont.systemFont(ofSize: alternativeButtonFontSize, weight: .semibold) } } } // MARK: - Status Bar /** * Styles of status bar to use with bulletin items. */ @objc public enum BLTNStatusBarAppearance: Int { /// The status bar is hidden. case hidden /// The color of the status bar is determined automatically. This is the default style. case automatic /// Style to use with dark backgrounds. case lightContent /// Style to use with light backgrounds. case darkContent }
import vidFrame1 from "../assets/video frame.png" import link from "../assets/link.png" import more from "../assets/more.png" import { Link } from "react-router-dom" import RepoHeader from "../components/repoHeader" function Repo(params) { const data = [ { category: "Recent Files", repos: [ { id:2, img: "", duration: "00:34", title: "How to create Facebook Ad listing", category:"", date: "SEPTEMBER 23, 2023" }, { id:2, img: "", duration: "00:34", title: "How to create Facebook Ad listing", date: "SEPTEMBER 23, 2023" } ] }, { category: "Files from last week", repos: [ { id:3, img: "", duration: "00:34", title: "How to create Facebook Ad listing", date: "SEPTEMBER 23, 2023" }, { id:4, img: "", duration: "00:34", title: "How to create Facebook Ad listing", date: "SEPTEMBER 23, 2023" }, ] } ] return ( <> <RepoHeader/> <div className="repo-content"> {data.map((category) => ( <div className="repo-category" key={category.category}> <h4 className="category-name">{category.category}</h4> <div className="video-grid"> {category.repos.map((repo) => ( <Link to={`/video/${repo.id}`}> <div className="video-grid-item" key={repo.title}> <div className="videoFrame"> <img src={vidFrame1} alt="" /> <span>{repo.duration}</span> </div> <div className="videoDetails"> <div> <h3>{repo.title}</h3> <p>{repo.date}</p> </div> <div> <img src={link} alt="" /> <img src={more} alt="" /> </div> </div> </div> </Link> ))} </div> </div> ))} </div> </> ) } export default Repo
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:valorant_fantasy/views/authentication_page/team_build_page/team_player_list_page.dart'; class TeamBuildPage extends StatelessWidget { final String? playerName; final String? teamInitials; const TeamBuildPage({super.key, this.playerName, this.teamInitials}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Select players you prefer", style: TextStyle(fontSize: 18), ), ), body: SingleChildScrollView( child: Column( children: [ playerCard(context), Padding( padding: const EdgeInsets.only(left: 20, right: 20, top: 20), child: SizedBox( width: double.infinity, height: 50, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 35, 211, 129)), onPressed: () {}, child: const Text( "Done", style: TextStyle( color: Colors.white, fontSize: 17, fontWeight: FontWeight.bold), )), ), ) ], ), ), ); } Widget playerCard(BuildContext context) { return ListView.builder( shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () async { Get.to(() => const TeamPlayerList()); }, child: ListTile( leading: const Icon( Icons.gamepad, size: 40, color: Colors.amber, ), title: Text( playerName.toString(), style: const TextStyle(color: Colors.white), ), subtitle: Text( teamInitials.toString(), style: const TextStyle(color: Colors.white), ), )); }); } }
/** * External dependencies */ import classNames from 'classnames'; /** * WordPress dependencies */ import { useInstanceId } from '@wordpress/compose'; import { forwardRef } from '@wordpress/element'; /** * Internal dependencies */ import BaseControl from '../base-control'; import InputBase from '../input-control/input-base'; import { Select } from './styles/select-control-styles'; import type { WordPressComponentProps } from '../context'; import type { SelectControlProps } from './types'; import SelectControlChevronDown from './chevron-down'; import { useDeprecated36pxDefaultSizeProp } from '../utils/use-deprecated-props'; function useUniqueId( idProp?: string ) { const instanceId = useInstanceId( SelectControl ); const id = `inspector-select-control-${ instanceId }`; return idProp || id; } function UnforwardedSelectControl( props: WordPressComponentProps< SelectControlProps, 'select', false >, ref: React.ForwardedRef< HTMLSelectElement > ) { const { className, disabled = false, help, hideLabelFromVision, id: idProp, label, multiple = false, onChange, options = [], size = 'default', value: valueProp, labelPosition = 'top', children, prefix, suffix, __next40pxDefaultSize = false, __nextHasNoMarginBottom = false, ...restProps } = useDeprecated36pxDefaultSizeProp( props ); const id = useUniqueId( idProp ); const helpId = help ? `${ id }__help` : undefined; // Disable reason: A select with an onchange throws a warning. if ( ! options?.length && ! children ) return null; const handleOnChange = ( event: React.ChangeEvent< HTMLSelectElement > ) => { if ( props.multiple ) { const selectedOptions = Array.from( event.target.options ).filter( ( { selected } ) => selected ); const newValues = selectedOptions.map( ( { value } ) => value ); props.onChange?.( newValues, { event } ); return; } props.onChange?.( event.target.value, { event } ); }; const classes = classNames( 'components-select-control', className ); return ( <BaseControl help={ help } id={ id } __nextHasNoMarginBottom={ __nextHasNoMarginBottom } > <InputBase className={ classes } disabled={ disabled } hideLabelFromVision={ hideLabelFromVision } id={ id } label={ label } size={ size } suffix={ suffix || ( ! multiple && <SelectControlChevronDown /> ) } prefix={ prefix } labelPosition={ labelPosition } __next40pxDefaultSize={ __next40pxDefaultSize } > <Select { ...restProps } __next40pxDefaultSize={ __next40pxDefaultSize } aria-describedby={ helpId } className="components-select-control__input" disabled={ disabled } id={ id } multiple={ multiple } onChange={ handleOnChange } ref={ ref } selectSize={ size } value={ valueProp } > { children || options.map( ( option, index ) => { const key = option.id || `${ option.label }-${ option.value }-${ index }`; return ( <option key={ key } value={ option.value } disabled={ option.disabled } hidden={ option.hidden } > { option.label } </option> ); } ) } </Select> </InputBase> </BaseControl> ); } /** * `SelectControl` allows users to select from a single or multiple option menu. * It functions as a wrapper around the browser's native `<select>` element. * * ```jsx * import { SelectControl } from '@wordpress/components'; * import { useState } from '@wordpress/element'; * * const MySelectControl = () => { * const [ size, setSize ] = useState( '50%' ); * * return ( * <SelectControl * label="Size" * value={ size } * options={ [ * { label: 'Big', value: '100%' }, * { label: 'Medium', value: '50%' }, * { label: 'Small', value: '25%' }, * ] } * onChange={ setSize } * /> * ); * }; * ``` */ export const SelectControl = forwardRef( UnforwardedSelectControl ); export default SelectControl;
import UIKit import SnapKit class TableViewController: UIViewController { private var tableView = UITableView() private var filteredContacts: [String] = [] let contacts = [ "Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Harry", "Isabelle", "Jack", "Karen", "Liam", "Mia", "Nancy", "Oliver", "Penny", "Quinn", "Ryan", "Samantha", "Tom", "Ursula", "Victoria", "William", "Xander", "Yvonne", "Zoe" ] override func viewDidLoad() { super.viewDidLoad() // Set up table view tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView) // Set up search bar let searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self navigationItem.searchController = searchController } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = view.bounds } } extension TableViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return contacts.count > 0 ? 26 : 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let letter = Character(UnicodeScalar(section + 65)!) if isFiltering { return filteredContacts.filter { $0.hasPrefix(String(letter)) }.count } return contacts.filter { $0.hasPrefix(String(letter)) }.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let letter = Character(UnicodeScalar(indexPath.section + 65)!) let contactName: String if isFiltering { let filtered = filteredContacts.filter { $0.hasPrefix(String(letter)) } contactName = filtered[indexPath.row] } else { let filtered = contacts.filter { $0.hasPrefix(String(letter)) } contactName = filtered[indexPath.row] } cell.textLabel?.text = contactName return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return String(Character(UnicodeScalar(section + 65)!)) } func sectionIndexTitles(for tableView: UITableView) -> [String]? { let alphabet = (0..<26).map { String(UnicodeScalar("A".unicodeScalars.first!.value + $0)!) } return alphabet } } extension TableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let letter = Character(UnicodeScalar(indexPath.section + 65)!) let contactName: String if isFiltering { let filtered = filteredContacts.filter { $0.hasPrefix(String(letter)) } contactName = filtered[indexPath.row] } else { let filtered = contacts.filter { $0.hasPrefix(String(letter)) } contactName = filtered[indexPath.row] } print("Selected contact: \(contactName)") } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = #colorLiteral(red: 0.7057395577, green: 0.7057395577, blue: 0.7057395577, alpha: 1) let titleLabel = UILabel() titleLabel.font = .boldSystemFont(ofSize: 16) titleLabel.textColor = .white titleLabel.text = self.tableView(tableView, titleForHeaderInSection: section) headerView.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.centerY.equalToSuperview() make.leading.equalToSuperview().inset(16) } return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } } extension TableViewController: UISearchResultsUpdating { private var isFiltering: Bool { let searchBar = navigationItem.searchController?.searchBar return searchBar?.text?.isEmpty == false && searchBar?.isFirstResponder == true } func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text?.lowercased() { filteredContacts = contacts.filter { $0.lowercased().contains(searchText) } } else { filteredContacts = [] } tableView.reloadData() } }
# Cheat sheet for RUN - SLEEP - STOP2 Hands on How to reduce consutmption step by step on STM32U575 device in every operation mode! ## Reduce SRAM and Flash size in linker script ```c MEMORY { RAM (xrw) : ORIGIN = 0x28000000, LENGTH = 16K FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K } ``` ## Deactivate RTC WakeUp in MX_RTC_Init(void) ```c /* USER CODE BEGIN RTC_Init 2 */ HAL_RTCEx_DeactivateWakeUpTimer(&hrtc); /* USER CODE END RTC_Init 2 */ ``` ## USER CODE 2 modification ```c /* USER CODE BEGIN 2 */ /* 1 - Measure consumption in Run LDO operation --------------------------------------------------*/ HAL_Delay(1500); /* 2 - Measure consumption in Run SMPS operation --------------------------------------------------*/ /* The SMPS regulator supplies the Vcore Power Domains */ HAL_PWREx_ConfigSupply(PWR_SMPS_SUPPLY); HAL_Delay(1500); /* 3 - Measure consumption for Power-down Mode for Flash Banks ------------------------------------*/ /* Enable the Power-down Mode for Flash Banks*/ HAL_FLASHEx_EnablePowerDown(FLASH_BANK_2); HAL_Delay(1500); /* Enable ultra low power mode */ HAL_PWREx_EnableUltraLowPowerMode(); /* Enable the Autonomous Mode for the RTC Stop0/1/2 */ __HAL_RCC_RTCAPB_CLKAM_ENABLE(); /* Set RTC wakeup timer for 2s */ HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 0, RTC_WAKEUPCLOCK_CK_SPRE_16BITS, 0); /* 4 - Measure consumption in SLEEP mode Full SRAM retention---------------------------------------*/ /* Enter in SlEEP mode */ HAL_SuspendTick(); HAL_PWR_EnterSLEEPMode(PWR_LOWPOWERREGULATOR_ON, PWR_SLEEPENTRY_WFI); HAL_ResumeTick(); /* 5 - Measure consumption in SLEEP mode with SRAM4 retention only --------------------------------*/ /* Enter in SlEEP mode */ HAL_PWREx_DisableRAMsContentRunRetention(PWR_SRAM1_FULL_RUN); HAL_PWREx_DisableRAMsContentRunRetention(PWR_SRAM2_FULL_RUN); HAL_PWREx_DisableRAMsContentRunRetention(PWR_SRAM3_FULL_RUN); HAL_SuspendTick(); HAL_PWR_EnterSLEEPMode(PWR_LOWPOWERREGULATOR_ON, PWR_SLEEPENTRY_WFI); HAL_ResumeTick(); /* 6 - Measure consumption in SLEEP mode with SRAM4 retention only and busses APBx/AHBx shutdown ----*/ /* Enter in SlEEP mode */ (*RCC).CFGR2 = (RCC_CFGR2_AHB1DIS | RCC_CFGR2_AHB2DIS1 | RCC_CFGR2_AHB2DIS2 | RCC_CFGR2_APB1DIS | RCC_CFGR2_APB2DIS); HAL_SuspendTick(); HAL_PWR_EnterSLEEPMode(PWR_LOWPOWERREGULATOR_ON, PWR_SLEEPENTRY_WFI); HAL_ResumeTick(); /* 7 - Measure consumption in SLEEP mode with SRAM4 retention only and busses APBx/AHBx shutdown ----*/ /*Keep live SRM4, PWR, RTC */ /* Enter in SlEEP mode */ CLEAR_REG(RCC->AHB1SMENR); CLEAR_REG(RCC->AHB2SMENR1); CLEAR_REG(RCC->APB1SMENR1); CLEAR_REG(RCC->APB1SMENR2); CLEAR_REG(RCC->APB2SMENR); HAL_SuspendTick(); HAL_PWR_EnterSLEEPMode(PWR_LOWPOWERREGULATOR_ON, PWR_SLEEPENTRY_WFI); HAL_ResumeTick(); /* 8 - Measure consumption in Stop 2 mode Full SRAM retention ---------------------------------------*/ /* Enter in Stop 2 mode */ HAL_PWREx_EnableRAMsContentRunRetention(PWR_SRAM1_FULL_RUN); HAL_PWREx_EnableRAMsContentRunRetention(PWR_SRAM2_FULL_RUN); HAL_PWREx_EnableRAMsContentRunRetention(PWR_SRAM3_FULL_RUN); HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI); /* Disable RAM page(s) content lost in Stop mode (Stop 0, 1, 2, 3) */ HAL_PWREx_DisableRAMsContentStopRetention(PWR_SRAM1_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_SRAM2_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_SRAM3_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_ICACHE_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_DCACHE1_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_DMA2DRAM_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_PERIPHRAM_FULL_STOP_RETENTION); HAL_PWREx_DisableRAMsContentStopRetention(PWR_PKA32RAM_FULL_STOP_RETENTION); /*enable AHB2 bus again because GPIO PC7 LED toggling*/ (*RCC).CFGR2 &= ~(RCC_CFGR2_AHB2DIS1); /* USER CODE END 2 */ ``` ## While(1) loop modification ```c while (1) { /* Led Toggling */ HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_7); HAL_Delay(1500); HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_7); /* 9 - Measure consumption in Stop 2 mode reduced SRAM retention------------------------------*/ /* Enter in Stop 2 mode */ HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } ``` ## Expected results ![Image1](./img/LPmodes_result.png)
import { BannerProps } from 'components/Banner' import { GameCardProps } from 'components/GameCard' import { GameItemProps } from 'components/GameItem' import { HighlightProps } from 'components/Highlight' import { BannerFragment } from 'graphql/generated/BannerFragment' import { GameFragment } from 'graphql/generated/GameFragment' import { HighlightFragment } from 'graphql/generated/HighlightFragment' import { QueryOrders_orders } from 'graphql/generated/QueryOrders' import { getImageUrl, formatPrice } from 'utils/helpers' interface MapperSectionResult { highlight?: HighlightProps gameCards: GameCardProps[] } export const mapperSection = ( highlight?: HighlightFragment | null, gameCards: GameFragment[] = [] ): MapperSectionResult => ({ ...(highlight && { highlight: mapperHighlight(highlight) }), gameCards: gameCards.map(mapperGame) }) export const mapperHighlight = (highlight: HighlightFragment): HighlightProps => ({ title: highlight.title, subtitle: highlight.subtitle, background: getImageUrl(highlight.background?.url), image: getImageUrl(highlight.image?.url), buttonLabel: highlight.buttonLabel, buttonLink: highlight.buttonLink, reverse: highlight.reverse }) export const mapperGame = (game: GameFragment): GameCardProps => ({ id: game.id, title: game.name, subtitle: game.developers[0].name, slug: game.slug, image: getImageUrl(game.cover?.url), price: formatPrice(game.price), ...(game.discount && { discount: formatPrice(game.discount), ribbon: Math.round((1 - game.discount / game.price) * 100) + '% OFF' }) }) export const mapperBanner = (banner: BannerFragment): BannerProps => ({ title: banner.title, subtitle: banner.subtitle, buttonLabel: banner.button?.label as string, buttonLink: banner.button?.href as string, image: getImageUrl(banner.image?.url), ...(banner.ribbon && { ribbon: banner.ribbon.text, ribbonColor: banner.ribbon.color || undefined }) }) export const mapperOrder = (order: QueryOrders_orders): GameItemProps[] => { return order.games.map(game => ({ id: game.id, title: game.name, price: formatPrice(game.discount || game.price), image: getImageUrl(game.cover?.url), downloadLink: '', slug: game.slug, paymentInfo: { number: order.card_last4 ? '**** '.repeat(3) + order.card_last4 : 'Free Game', flag: order.card_brand, image: order.card_brand ? '/img/cards/' + order.card_brand + '.png' : null, purchaseDate: 'Purchased made on ' + new Intl.DateTimeFormat('en-US', { day: 'numeric', month: 'short', year: 'numeric' }).format(new Date(order.created_at)) } })) }
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import * as serviceWorker from "./serviceWorker"; import reducer, { initialState } from "./reducer"; import { StateProvider } from "./StateProvider"; import { createRoot } from "react-dom/client"; // Import createRoot from react-dom/client const root = createRoot(document.getElementById("root")); root.render( <React.StrictMode> <StateProvider initialState={initialState} reducer={reducer}> <App /> </StateProvider> </React.StrictMode> ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
import matplotlib.pyplot as plt import os # Assuming Env class is defined somewhere else and imported properly from env import Env def main(): game_types = ['basic', 'intermediate', 'hard'] task_volumes = [10, 50, 100] plots_dir = "./plots" if not os.path.exists(plots_dir): os.makedirs(plots_dir) for task_volume in task_volumes: for game_type in game_types: random_cumulative_rewards = [] adaptive_cumulative_rewards = [] dqn_cumulative_rewards = [] ppo_cumulative_rewards = [] for i in range(100): env = Env(game_type, task_volume, ['random', 'adaptive', 'dqn', 'ppo']) rewards, actions = env.simulate_game(verbose=False) random_cumulative_rewards.append(rewards['Random']) adaptive_cumulative_rewards.append(rewards['Adaptive']) dqn_cumulative_rewards.append(rewards['DQN']) ppo_cumulative_rewards.append(rewards['PPO']) plt.figure(figsize=(10, 6)) plt.plot(random_cumulative_rewards, label='Random') plt.plot(adaptive_cumulative_rewards, label='Adaptive') plt.plot(dqn_cumulative_rewards, label='DQN') plt.plot(ppo_cumulative_rewards, label='PPO') plt.xlabel('Iteration') plt.ylabel(f'Agents Cumulative Rewards') plt.title(f'Cumulative Rewards Comparison - {game_type.capitalize()} Game Task Volume = {task_volume}') plt.legend() plt.grid(True) plt.savefig(f"{plots_dir}/{game_type}_game_rewards_plot_task_volume_{task_volume}.png") plt.close() if __name__ == "__main__": main()
package com.github.zigcat.BlogPlatform.controllers; import com.github.zigcat.BlogPlatform.models.AppUser; import com.github.zigcat.BlogPlatform.models.AppUserRole; import com.github.zigcat.BlogPlatform.models.Post; import com.github.zigcat.BlogPlatform.repositories.AppUserRepository; import com.github.zigcat.BlogPlatform.repositories.CommentRepository; import com.github.zigcat.BlogPlatform.repositories.PostRepository; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; import java.util.NoSuchElementException; @RestController @RequestMapping("api/post") @RequiredArgsConstructor public class PostController { private final PostRepository repository; private final AppUserRepository userRepository; private final CommentRepository commentRepository; record NewPostRequest( String content ){} @GetMapping public List<Post> getPosts(){ return repository.findAll(); } @GetMapping("/id/{post_id}") public ResponseEntity<Post> getPostById(@PathVariable("post_id") Integer id){ try{ Post post = repository.findById(id).get(); return new ResponseEntity<>(post, HttpStatus.OK); } catch (NoSuchElementException e){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @GetMapping("/user/{user_id}") public ResponseEntity<List<Post>> getPostsByUser(@PathVariable("user_id") Integer id){ try{ AppUser user = userRepository.findById(id).get(); return new ResponseEntity<>(user.getPosts(), HttpStatus.OK); } catch(NoSuchElementException e){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @PostMapping("/create") public ResponseEntity<Post> addPost(@RequestBody NewPostRequest request, @AuthenticationPrincipal UserDetails userAuth){ if(userAuth == null){ return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } else { Post post = new Post(); post.setContent(request.content()); post.setUser(userRepository.findByUsername(userAuth.getUsername())); post.setCreationDate(LocalDate.now()); repository.save(post); return new ResponseEntity<>(HttpStatus.OK); } } @PatchMapping("/update/{post_id}") public ResponseEntity<Post> updatePost(@PathVariable("post_id") Integer id, @RequestBody NewPostRequest request, @AuthenticationPrincipal UserDetails userAuth){ try{ Post post = repository.findById(id).get(); if(post.getUser().getUsername().equals(userAuth.getUsername())){ post.setContent(request.content()); repository.save(post); return new ResponseEntity<>(post, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (NoSuchElementException e){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @DeleteMapping("/delete/{post_id}") public ResponseEntity<Post> deletePost(@PathVariable("post_id") Integer id, @AuthenticationPrincipal UserDetails userAuth){ try{ Post post = repository.findById(id).get(); if(post.getUser().getUsername().equals(userAuth.getUsername()) || userAuth.getAuthorities().contains(new SimpleGrantedAuthority(AppUserRole.ADMIN.toString()))){ commentRepository.deleteAllInBatch(post.getComments()); repository.deleteById(id); return new ResponseEntity<>(HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (NoSuchElementException e){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
import './App.css'; import GalleryList from './containers/galleryList/GalleryList' import { BackArrow, Categories, Container, Header, Overlay } from './AppStyles'; import { Link, Route, Switch } from 'react-router-dom'; import Gallery from './containers/gallery/Gallery'; import { api } from './api' import { useEffect, useState } from 'react'; import { GalleryContext } from './context/galleryContext' import Back from './img/icons/left.png' function App() { const [imgs, setImgs] = useState<{header: string, coverPic: string, link: string, count: number }[]>([]) const [selectedGallery, setSelecteGallery] = useState() const [overlay, setOverlay] = useState(false) const [header, setHeader] = useState('') useEffect(() => { setImgs(api.headers) }, []) const handleSelectGallery = (sel: string, title: string) => { setSelecteGallery(api.galleries[sel]) } const handleSetHeader = (slug: string) => { const header = api.headers.find(h => h.link === slug) if(header) { setHeader(header.header) } else { setHeader('') } } const handleGoBack = () => { setHeader('') } return ( <div className="App" style={{ position: 'relative'}}> <Container> <Header className='relative'>Fotogaléria</Header> <Categories className='relative'>{ header != '' ? <Link to="/" style={{ textDecoration: 'none', color:'#000'}} onClick={handleGoBack}> <BackArrow src={Back} /> { header }</Link> : 'Kategórie' }</Categories> <GalleryContext.Provider value={{ showOverlay: () => setOverlay(true), closeOverlay: () => setOverlay(false), overlay: overlay }}> <Switch> <Route path="/" exact render={() => <GalleryList images={imgs} selectGallery={(selector: string, title: string) => handleSelectGallery(selector, title)} />} /> <Route path="/gallery/:slug" exact render={() => <Gallery setHeader={(slug: string) => handleSetHeader(slug)} />} /> </Switch> </GalleryContext.Provider> </Container> { overlay && <Overlay className="overlay" onClick={() => setOverlay(false)} />} </div> ); } export default App;
package com.example.registeractivity; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class AddCustomer extends AppCompatActivity { EditText e1, e2; TextView t1; int num1, num2; String s1, s2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_customer); Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("PocketBook"); } public boolean getNumbers() { // defining the edit text 1 to e1 e1 = (EditText)findViewById(R.id.num1); // defining the edit text 2 to e2 e2 = (EditText)findViewById(R.id.num2); // defining the text view to t1 t1 = (TextView)findViewById(R.id.result); // taking input from text box 1 s1 = e1.getText().toString(); // taking input from text box 2 s2 = e2.getText().toString(); // condition to check if box is not empty if ((s1.equals(null) && s2.equals(null)) || (s1.equals("") && s2.equals(""))) { String result = "Please enter a value"; t1.setText(result); return false; } else { // converting string to int. num1 = Integer.parseInt(s1); // converting string to int. num2 = Integer.parseInt(s2); } return true; } // a public method to perform addition public void doSum(View v) { // get the input numbers if (getNumbers()) { int sum = num1 + num2; t1.setText(Integer.toString(sum)); } } // a public method to perform power function public void doPow(View v) { // get the input numbers if (getNumbers()) { double sum = Math.pow(num1, num2); t1.setText(Double.toString(sum)); } } // a public method to perform subtraction public void doSub(View v) { // get the input numbers if (getNumbers()) { int sum = num1 - num2; t1.setText(Integer.toString(sum)); } } // a public method to perform multiplication public void doMul(View v) { // get the input numbers if (getNumbers()) { int sum = num1 * num2; t1.setText(Integer.toString(sum)); } } // a public method to perform Division public void doDiv(View v) { // get the input numbers if (getNumbers()) { // displaying the text in text view assigned as t1 double sum = num1 / (num2 * 1.0); t1.setText(Double.toString(sum)); } } // a public method to perform modulus function public void doMod(View v) { // get the input numbers if (getNumbers()) { double sum = num1 % num2; t1.setText(Double.toString(sum)); } } public void go(View v) { Intent intent = new Intent(AddCustomer.this, CustomerActivity.class); startActivity(intent); } }
<!-- Write a script which moves a ball object, given the speed = 5, and direction = 45 degrees Set vx and vy –using the given angle and speed, and the trigonometric functions. Move the x and y position of the ball according to vx and vy (remember that you are adding on the velocity variable at each frame iteration). --> <!doctype html> <html> <head> <meta charset="utf-8"> <title>prac 5 q 2</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="./classes/ball.js"></script> <script type="text/javascript"> $(document).ready(function() { //assign the canvas element to a variable using the DOM var canvas = document.getElementById("myCanvas"); //assign the 2d rendering context (what we draw on) to a variable var context = canvas.getContext("2d"); var canvasWidth = canvas.width; var canvasHeight = canvas.height; //create ball object with radius 10 ball = new Ball(10, 'red'); var xPos = 0; // -3 is where x starts on graph var yPos = 0; //initialise to 0 and equation will be solved for y below var angle = 45; var speed = 5; var vx = Math.cos(angle*Math.PI/180) * speed; var vy = Math.sin(angle*Math.PI/180) * speed; //sets up animation loop function animate () { //clears the stage after every iteration of the loop context.clearRect(0, 0, canvasWidth, canvasHeight); //special animation function - accepts the callback function 'animate' window.requestAnimationFrame(animate, canvas); ball.x += vx; ball.y += vy; //draw ball on canvas using draw method from Ball class ball.draw(context); }; //call it once to kick it off //after that it recursively calls itself window.requestAnimationFrame(animate, canvas); }); </script> </head> <body> <header> </header> <canvas id="myCanvas" width="640" height="480" style="border:1px solid #000000;"> </canvas> </body> </html>
// /* // * Copyright 2015 Adobe Systems Incorporated // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ // package com.employdemy.core.models; // import org.apache.commons.lang3.StringUtils; // import org.apache.sling.api.resource.Resource; // import org.junit.jupiter.api.BeforeEach; // import org.junit.jupiter.api.Test; // import org.junit.jupiter.api.extension.ExtendWith; // import com.day.cq.wcm.api.Page; // import io.wcm.testing.mock.aem.junit5.AemContext; // import io.wcm.testing.mock.aem.junit5.AemContextExtension; // import static org.junit.jupiter.api.Assertions.assertNotNull; // import static org.junit.jupiter.api.Assertions.assertTrue; // /** // * Simple JUnit test verifying the HelloWorldModel // */ // @ExtendWith(AemContextExtension.class) // class HelloWorldModelTest { // private HelloWorldModel hello; // private Page page; // private Resource resource; // @BeforeEach // public void setup(AemContext context) throws Exception { // // prepare a page with a test resource // page = context.create().page("/content/mypage"); // resource = context.create().resource(page, "hello", // "sling:resourceType", "employdemy/components/helloworld"); // // create sling model // hello = resource.adaptTo(HelloWorldModel.class); // } // @Test // void testGetMessage() throws Exception { // // some very basic junit tests // String msg = hello.getMessage(); // assertNotNull(msg); // assertTrue(StringUtils.contains(msg, resource.getResourceType())); // assertTrue(StringUtils.contains(msg, page.getPath())); // } // }
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm"; import { PasswordHashing } from "../../Authentication/PasswordHashing"; @Entity('Users') export class User { @PrimaryGeneratedColumn('uuid') Id: string; @CreateDateColumn({ type: 'timestamp with time zone' , default: 'now()' }) CreatedDate: Date; @UpdateDateColumn({ type: 'timestamp with time zone', nullable: true }) LastUpdatedDate: Date | null; @Column({ type: 'varchar', length: 255 }) Name: string; @Column({ type: 'varchar', length: 255, unique: true }) Email: string; @Column({type: 'text'}) Password: string; @Column({ type: 'timestamp with time zone', nullable: true }) BirthDay: Date | null; @Column({type: 'varchar', length: 255, nullable: true }) Sex: string | null; @Column({ type: 'varchar', length: 255, nullable: true }) Role: string | null; constructor( Id: string, LastUpdatedDate: Date | null, Name: string, Email: string, Password: string, BirthDay: Date | null, Sex: string | null, Role: string | null ) { this.Id = Id; this.LastUpdatedDate = LastUpdatedDate; this.Name = Name; this.Email = Email; this.Password =Password; this.BirthDay = BirthDay; this.Sex = Sex; this.Role = Role; } userValidation(): void { let validationErrors: string[] = []; this.Id = this.Id; this.LastUpdatedDate = this.LastUpdatedDate; this.Name = this.userNameValidation(this.Name, validationErrors); this.Email = this.userEmailValidation(this.Email, validationErrors); this.Password = this.userPasswordValidation(this.Password, validationErrors); this.BirthDay = this.BirthDay; this.Sex = this.userSexValidation(this.Sex, validationErrors); this.Role = this.userRoleValidation(this.Role, validationErrors); if (validationErrors.length > 0) { throw new Error(validationErrors.join("\n")); } } userNameValidation(name: string, validationErrors: string[]): string{ const errorMessage = "The field name cannot be null and must contain a minimum of 3 and a maximum of 50 characters, including: letters and spaces."; if (!/^[a-zA-Z ]{3,50}$/.test(name || "")) { validationErrors.push(errorMessage); } return name; } userEmailValidation(email: string, validationErrors: string[]): string{ const errorMessage = "The field e-mail is invalid."; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email || "")) { validationErrors.push(errorMessage); } return email; } userRoleValidation(role: string | null, validationErrors: string[]): string{ const errorMessage = "The field role is invalid, role must be 'Normal' or 'Admin'."; if (role === null) { role = "Normal"; } if (role !== "Normal" && role !== "Admin") { validationErrors.push(errorMessage); } return role; } userSexValidation(sex: string | null, validationErrors: string[]): string{ const errorMessage = "The field sex is invalid, sex must be 'Male' or 'Female'."; if (sex === null || (sex !== "Female" && sex !== "Male")) { validationErrors.push(errorMessage); sex = "Error"; } return sex; } userPasswordValidation(password: string, validationErrors: string[]): string{ const errorMessage = "The password must contain at least 8 characters, including at least one uppercase letter, one lowercase letter, one number and one special character (@, $, !, %, *, ?, &)."; if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(password || "")) { validationErrors.push(errorMessage); return "Empty"; } return PasswordHashing.hashPassword(password); } }
from ptydls.cluster.scheduler import JobStatus, Slurm from ptydls.utils.helper import slurm_job_status import typing import time from job_util import submission_manager from util.config import config from util import deployment_restrictions UPDATE_CACHE_INTERVAL = 5 jtid_statuses_cache: typing.Dict[str, JobStatus] = {} cache_last_updated_time: typing.Union[int, None] = None is_cache_updating = False def _update_cache_from_slurm_response(slurm_response: dict): # The job id and task ids are separated by an underscore when returned by ptydls, # but the cache uses a dot to separate them. new_statuses = { new_jtid.replace("_", "."): new_status for new_jtid, new_status in slurm_response.items() } # Updating the cache with the new values for new_jtid, new_status in new_statuses.items(): jtid_statuses_cache[new_jtid] = new_status def _update_jtid_status_cache(): global jtid_statuses_cache global cache_last_updated_time all_slurm_jtids = [] jtids_to_update = [] for jtid, submitter in submission_manager.submitter_tracker.items(): if isinstance(submitter.ptydls_submission.rinfo.cluster.scheduler, Slurm): all_slurm_jtids.append(jtid) jtid_underscore = jtid.replace(".", "_") # If the job is running, queued or undefined, we need to update it. # All other statuses are final and don't need to be updated. if jtid in jtid_statuses_cache: cached_status = jtid_statuses_cache[jtid] if cached_status in [JobStatus.RUNNING, JobStatus.UNDEFINED, JobStatus.QUEUED]: jtids_to_update.append(jtid_underscore) else: # Job is not in the cache, so we need to update it jtids_to_update.append(jtid_underscore) # In case getting the latest slurm response takes over 1s, we want the cache last update time to be # when we sent the request, not when we got the response. old_cache_last_updated_time = cache_last_updated_time cache_last_updated_time = int(time.time()) # Fetching the status of all jobs that need to be updated. # This will only return the status of jobs that have changed since the last update. if len(jtids_to_update) > 0: slurm_jwt = None if deployment_restrictions.is_deployment(): slurm_jwt = config["PTYHUB_SLURM_JWT"] _update_cache_from_slurm_response( slurm_job_status( jtids_to_update, update_time=old_cache_last_updated_time, full=False, slurm_jwt=slurm_jwt ) ) # Checking if any jtids are missing from the cache, and if so forcefully fetching their status missing_jtids = [] for jtid in all_slurm_jtids: if jtid not in jtid_statuses_cache: # If there is a slurm job that we still don't have the status of, we need to update it forcefully missing_jtids.append(jtid) if len(missing_jtids) > 0: print(f"WARNING: Missing status for {len(missing_jtids)} jobs. Forcing update.") _update_cache_from_slurm_response( slurm_job_status( jtids_to_update, # The last update time was just now, so set this to time.time() update_time=int(time.time()), full=True ) ) def update_jtid_status_cache(): global is_cache_updating global cache_last_updated_time is_cache_updating = True try: _update_jtid_status_cache() finally: is_cache_updating = False def get_slurm_jtid_status(jtid, force_update=False) -> JobStatus: global jtid_statuses_cache if cache_last_updated_time is None or time.time() - cache_last_updated_time > UPDATE_CACHE_INTERVAL or force_update: # We need to update the cache update_jtid_status_cache() if jtid not in jtid_statuses_cache: # If the job is not in the cache, it has likely been added since the last update. return JobStatus.UNDEFINED return jtid_statuses_cache[jtid]
package frc.robot; /* * MIT License * * Copyright (c) 2022 PhotonVision * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import edu.wpi.first.apriltag.AprilTagFieldLayout; import edu.wpi.first.apriltag.AprilTagFields; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation3d; import edu.wpi.first.math.geometry.Transform3d; import edu.wpi.first.math.geometry.Translation3d; import edu.wpi.first.wpilibj.DriverStation; import java.io.IOException; import java.util.Optional; import org.photonvision.EstimatedRobotPose; import org.photonvision.PhotonCamera; import org.photonvision.PhotonPoseEstimator; import org.photonvision.PhotonPoseEstimator.PoseStrategy; public class PhotonCameraWrapper { public PhotonCamera photonCamera; private PhotonPoseEstimator photonPoseEstimator; private Pose2d pose2d = new Pose2d(); public PhotonCameraWrapper() { // Change the name of your camera here to whatever it is in the PhotonVision UI. photonCamera = new PhotonCamera("clementine_vision"); try { // Attempt to load the AprilTagFieldLayout that will tell us where the tags are on the field. AprilTagFieldLayout fieldLayout = AprilTagFields.k2023ChargedUp.loadAprilTagLayoutField(); // Create pose estimator photonPoseEstimator = new PhotonPoseEstimator( fieldLayout, PoseStrategy.CLOSEST_TO_LAST_POSE, photonCamera, new Transform3d(new Translation3d(0.3, 0, 0), new Rotation3d())); photonPoseEstimator.setMultiTagFallbackStrategy(PoseStrategy.AVERAGE_BEST_TARGETS); } catch (IOException e) { // The AprilTagFieldLayout failed to load. We won't be able to estimate poses if we don't know // where the tags are. DriverStation.reportError("Failed to load AprilTagFieldLayout", e.getStackTrace()); photonPoseEstimator = null; } } /** * @param estimatedRobotPose The current best guess at robot pose * @return an EstimatedRobotPose with an estimated pose, the timestamp, and targets used to create * the estimate */ public Optional<EstimatedRobotPose> getEstimatedGlobalPose() { if (photonPoseEstimator == null) { // The field layout failed to load, so we cannot estimate poses. return Optional.empty(); } photonPoseEstimator.setReferencePose(pose2d); return photonPoseEstimator.update(); } }
package com.luantang.socialmediaanalytics.dashboard.controller; import com.luantang.socialmediaanalytics.dashboard.dto.facebook.*; import com.luantang.socialmediaanalytics.dashboard.service.FacebookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController @RequestMapping("/api/v1/user/facebook/pages") public class FacebookDataController { private final FacebookService facebookService; @Autowired public FacebookDataController(FacebookService facebookService) { this.facebookService = facebookService; } @GetMapping("/details") public ResponseEntity<PageDetailsDto> getPageDetails() { return new ResponseEntity<>(facebookService.getPageDetails(SecurityContextHolder.getContext().getAuthentication().getName()), HttpStatus.OK); } @GetMapping("/page-post-performance") public ResponseEntity<List<PagePostPerformanceDto>> getPagePostPerformanceList(@RequestParam("since") String startDate, @RequestParam("until") String endDate) { return new ResponseEntity<>(facebookService.getPostPerformances(SecurityContextHolder.getContext().getAuthentication().getName(), startDate, endDate), HttpStatus.OK); } @GetMapping("/page-impressions") public ResponseEntity<List<PageImpressionDto>> getPageImpressions(@RequestParam("since") String startDate, @RequestParam("until") String endDate) { return new ResponseEntity<>(facebookService.getPageImpressions(SecurityContextHolder.getContext().getAuthentication().getName(), startDate, endDate), HttpStatus.OK); } @GetMapping("/page-post-engagements") public ResponseEntity<List<PagePostEngagementDto>> getPagePostEngagements(@RequestParam("since") String startDate, @RequestParam("until") String endDate) { return new ResponseEntity<>(facebookService.getPagePostEngagements(SecurityContextHolder.getContext().getAuthentication().getName(), startDate, endDate), HttpStatus.OK); } @GetMapping("/page-fans") public ResponseEntity<List<PageFanDto>> getPageFans(@RequestParam("since") String startDate, @RequestParam("until") String endDate) { return new ResponseEntity<>(facebookService.getPageFans(SecurityContextHolder.getContext().getAuthentication().getName(), startDate, endDate), HttpStatus.OK); } @GetMapping("/page-views_total") public ResponseEntity<List<PageViewDto>> getPageViewsTotal(@RequestParam("since") String startDate, @RequestParam("until") String endDate) { return new ResponseEntity<>(facebookService.getPageViews(SecurityContextHolder.getContext().getAuthentication().getName(), startDate, endDate), HttpStatus.OK); } }
package org.hyperledger.identus.presentproof.controller.http import org.hyperledger.identus.api.http.Annotation import org.hyperledger.identus.pollux.core.service.serdes.* import org.hyperledger.identus.presentproof.controller.http.RequestPresentationInput.annotations import sttp.tapir.{Schema, Validator} import sttp.tapir.json.zio.* import sttp.tapir.Schema.annotations.{description, encodedExample} import zio.json.{DeriveJsonDecoder, DeriveJsonEncoder, JsonDecoder, JsonEncoder} import java.util.UUID final case class RequestPresentationInput( @description(annotations.connectionId.description) @encodedExample(annotations.connectionId.example) connectionId: UUID, @description(annotations.options.description) @encodedExample(annotations.options.example) options: Option[Options] = None, @description(annotations.proofs.description) @encodedExample(annotations.proofs.example) proofs: Seq[ProofRequestAux], @description(annotations.anoncredPresentationRequest.description) @encodedExample(annotations.anoncredPresentationRequest.example) anoncredPresentationRequest: Option[AnoncredPresentationRequestV1], @description(annotations.claims.description) @encodedExample(annotations.claims.example) claims: Option[zio.json.ast.Json.Obj], @description(annotations.credentialFormat.description) @encodedExample(annotations.credentialFormat.example) credentialFormat: Option[String], ) object RequestPresentationInput { object annotations { object connectionId extends Annotation[UUID]( description = "The unique identifier of an established connection between the verifier and the prover.", example = UUID.fromString("bc528dc8-69f1-4c5a-a508-5f8019047900") ) object options extends Annotation[Option[Options]]( description = "The options to use when creating the proof presentation request (e.g., domain, challenge).", example = None ) object proofs extends Annotation[Seq[ProofRequestAux]]( description = "The type of proofs requested in the context of this proof presentation request (e.g., VC schema, trusted issuers, etc.)", example = Seq.empty ) object anoncredPresentationRequest extends Annotation[Option[AnoncredPresentationRequestV1]]( description = "Anoncred Presentation Request", example = Some( AnoncredPresentationRequestV1( requested_attributes = Map( "attribute1" -> AnoncredRequestedAttributeV1( "Attribute 1", List( Map( "cred_def_id" -> "credential_definition_id_of_attribute1" ) ), Some( AnoncredNonRevokedIntervalV1( Some(1635734400), Some(1735734400) ) ) ) ), requested_predicates = Map( "predicate1" -> AnoncredRequestedPredicateV1( "Predicate 1", ">=", 18, List( Map( "schema_id" -> "schema_id_of_predicate1" ) ), Some( AnoncredNonRevokedIntervalV1( Some(1635734400), None ) ) ) ), name = "Example Presentation Request", nonce = "1234567890", version = "1.0", non_revoked = None ) ) ) object claims extends Annotation[Option[zio.json.ast.Json.Obj]]( description = """ |The set of claims to be disclosed from the issued credential. |The JSON object should comply with the schema applicable for this offer (i.e. 'schemaId' or 'credentialDefinitionId'). |""".stripMargin, example = Some( zio.json.ast.Json.Obj( "firstname" -> zio.json.ast.Json.Str("Alice"), "lastname" -> zio.json.ast.Json.Str("Wonderland"), ) ) ) object credentialFormat extends Annotation[Option[String]]( description = "The credential format (default to 'JWT')", example = Some("JWT"), validator = Validator.enumeration( List( Some("JWT"), Some("SDJWT"), Some("AnonCreds") ) ) ) } given encoder: JsonEncoder[RequestPresentationInput] = DeriveJsonEncoder.gen[RequestPresentationInput] given decoder: JsonDecoder[RequestPresentationInput] = DeriveJsonDecoder.gen[RequestPresentationInput] import AnoncredPresentationRequestV1.given given Schema[AnoncredPresentationRequestV1] = Schema.derived given Schema[AnoncredRequestedAttributeV1] = Schema.derived given Schema[AnoncredRequestedPredicateV1] = Schema.derived given Schema[AnoncredNonRevokedIntervalV1] = Schema.derived given schema: Schema[RequestPresentationInput] = Schema.derived }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "logic.h" /** * @file life.c * * @author Maya Savino * * @date 05/03/2023 * * Assignment: Final - Conway's Game of Life * * @brief logic for game of life * * @bugs -x option sometimes induces a seg fault, typecasing issue * * @todo fix -x option (for randomizing colors) * * @param init_matrix initializes the matrix * @param free_matrix frees the matrix * @param hedge hedge implementation * @param torus torus implementation * @param klein klein implementation * @param randomize_colors randomizes colors */ unsigned char **init_matrix(int rows, int cols) { int i, j; unsigned char **a; a = malloc(rows * sizeof(int *)); if(!a) return NULL; for(i = 0; i < rows; i++){ a[i] = malloc(cols * sizeof(int)); if(!a[i]){ for (j = 0; j < i; j++) free(a[j]); free(a); return NULL; } } for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++){ a[i][j] = 0; } } return a; } void free_matrix(unsigned char **A, int rows){ int i; for(i = 0; i < rows; i++) free(A[i]); free(A); } void hedge(unsigned char **A, unsigned char **B, int rows, int cols){ int i, j, x, y, chk; for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++){ chk = 0; for(x = -1; x <= 1; x++){ for(y = -1; y <= 1; y++){ if((x+i) < rows && (y+j) < cols) if((x+i) >= 0 && (y+j) >= 0) if(A[x+i][y+j] == 1) chk += 1; } } if(A[i][j] == 1){ chk -= 1; if(chk < 2) B[i][j] = 0; else if(chk > 3) B[i][j] = 0; else B[i][j] = 1; } else{ B[i][j] = 0; if(chk == 3) B[i][j] = 1; } } } for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++) A[i][j] = 0; } } void torus(unsigned char **A, unsigned char **B, int rows, int cols){ int i, j, x, y, chk, tmp1, tmp2; // Check all cells for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++){ chk = 0; // Check in on the cell's neighbors for(x = -1; x <= 1; x++){ for(y = -1; y <= 1; y++){ tmp1 = ((x+i) % rows); tmp2 = ((y+j) % cols); if (tmp1 < 0) tmp1 = rows - 1; if (tmp2 < 0) tmp2 = cols - 1; if(A[tmp1][tmp2] == 1) chk += 1; } } if(A[i][j] == 1){ chk -= 1; if(chk < 2) B[i][j] = 0; else if(chk > 3) B[i][j] = 0; else B[i][j] = 1; } else{ B[i][j] = 0; if(chk == 3) B[i][j] = 1; } } } for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++) A[i][j] = 0; } } void klein(unsigned char **A, unsigned char **B, int rows, int cols){ int i, j, x, y, chk, tmp1, tmp2; // Check all cells for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++){ chk = 0; // Check in on the cell's neighbors for(x = -1; x <= 1; x++){ for(y = -1; y <= 1; y++){ tmp2 = ((y+j) % cols); tmp1 = x + i; if(tmp2 < 0) tmp2 = cols - 1; if(tmp1 < 0){ tmp2 = cols - tmp2 - 1; tmp1 = rows - 1; } else if(tmp1 >= rows){ tmp2 = cols - tmp2 - 1; tmp1 = ((x+i) % rows); } if(A[tmp1][tmp2] == 1) chk += 1; } } if(A[i][j] == 1){ chk -= 1; if(chk < 2){ B[i][j] = 0; } else if(chk > 3){ B[i][j] = 0; } else{ B[i][j] = 1; } } else{ B[i][j] = 0; if (chk == 3) { B[i][j] = 1; } } } } for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++) A[i][j] = 0; } }
// // CoinListView.swift // CryptoTracker // // Created by Marvis Ighedosa on 20/12/2023. // import SwiftUI struct CoinListView: View { let coin: CoinModel var showPortfolioView:Bool = false var body: some View { HStack{ leftItem Spacer() if showPortfolioView == true { centerItem } else { EmptyView() } rightItem } .padding(.vertical, 8) .font(.subheadline) } } struct CoinListView_Previews: PreviewProvider { static var previews: some View { Group{ CoinListView(coin: dev.coin, showPortfolioView: true) .previewLayout(.sizeThatFits) CoinListView(coin: dev.coin, showPortfolioView: false) .previewLayout(.sizeThatFits) .preferredColorScheme(.dark) } } } extension CoinListView { private var leftItem: some View { HStack{ Text("\(coin.rank)") .frame(minWidth: 30) .foregroundColor(Color.theme.secondaryText) CoinImageView(coin: coin) .frame(width: 40, height: 40) Text(coin.symbol.uppercased()) .fontWeight(.semibold) .foregroundColor(Color.theme.accent) } } private var centerItem: some View { VStack(alignment: .trailing){ Text(coin.currentHoldingsValue.asCurrencyWith2Decimals()) Text((coin.currentHoldings ?? 0).asNumberString()) } } private var rightItem: some View {VStack(alignment:.trailing){ VStack(alignment: .trailing){ Text(coin.currentPrice?.asCurrencyWith6Decimals() ?? "") .foregroundColor(Color.theme.accent) .fontWeight(.bold) Text(coin.priceChangePercentage24H?.asPercentString() ?? "0%") .foregroundColor((coin.priceChangePercentage24H ?? 0) >= 0 ? Color.theme.green : Color.theme.red) } .frame(width: UIScreen.main.bounds.width / 3.5 , alignment: .trailing) } } }
import React, { useState } from 'react'; import axios from 'axios'; import { CopyToClipboard } from 'react-copy-to-clipboard'; import { Container } from '../../globalStyles'; import { InputContainer, InputDiv, Form, FormInput, InputSubmit, Msg, ShortedUrlDiv, ShortUrl, LongUrl, CopyBtn, ShortUrlDiv, } from './Input.styles'; const Input = () => { const [url, setUrl] = useState(null); const [shortUrl, setShortUrl] = useState([]); const [longUrl, setLongUrl] = useState([]); const [copiedItems, setCopiedItem] = useState([]); const [fetching, setFetching] = useState(false); const handleSubmit = (e) => { e.preventDefault(); setFetching(true); if (url === '') { alert('Cannot find any url, Please try again!'); } else { axios .get(`https://api.shrtco.de/v2/shorten?url=${url}`) .then((response) => { setLongUrl([...longUrl, response.data.result.original_link]); setShortUrl([...shortUrl, response.data.result.short_link]); setFetching(false); }) .catch((err) => { console.log(err); }); } }; return ( <> <InputContainer> <Container> <InputDiv> <Form onSubmit={handleSubmit} validate> <FormInput type='text' placeholder='Shorten a link here...' onChange={(e) => setUrl(e.target.value)} /> <InputSubmit type='submit' value='Shorten it!' /> </Form> </InputDiv> {fetching ? ( <Msg>Please wait, Fetching shorten url</Msg> ) : ( <Msg>Please add a link</Msg> )} {shortUrl.length ? shortUrl.map((link, index) => ( <ShortedUrlDiv key={link}> <LongUrl>{longUrl[index]}</LongUrl> <ShortUrlDiv> <ShortUrl>{link}</ShortUrl> <CopyToClipboard text={link}> <CopyBtn onClick={() => setCopiedItem([...copiedItems, index])} isCopied={copiedItems.includes(index)} > {copiedItems.includes(index) ? 'Copied' : 'Copy'} </CopyBtn> </CopyToClipboard> </ShortUrlDiv> </ShortedUrlDiv> )) : null} </Container> </InputContainer> </> ); }; export default Input;
import pandas as pd from sklearn.metrics.pairwise import cosine_similarity import shelve class NetworkPair: # Each NetworkPair instance record previous attacking informtion related to a specific connection def __init__(self, amount: int, attack_amount: int, comm_id: str) -> None: self.amount = amount # Total amount of previous traffic self.attack_amount= attack_amount # Total amount of previous malicious traffic self.comm_id = comm_id # Calculated from: hash(proto, src_ip, src_port, dest_ip, dest_port) def add_attack_history(df: pd.DataFrame, path: str) -> pd.DataFrame: # add attack_amount and attack_rate to data, according to community_id. Return aggregated dataframe. df['attack_rate'] = pd.Series(dtype=float) df['attack_amount'] = pd.Series(dtype=int) with shelve.open(path, flag='r') as db: for index, row in df.iterrows(): comm_id = row['community_id'] if comm_id in db: df.at[index, 'attack_rate'] = db[comm_id].attack_amount / db[comm_id].amount df.at[index, 'attack_amount'] = db[comm_id].attack_amount else: df.at[index, 'attack_rate'] = 0. df.at[index, 'attack_amount'] = 0 db.close() return df def update_shelve(df: pd.DataFrame, path: str) -> None: # Update only info of malicious traffic. pred should has at least columns 'proto', 'src_ip', 'dest_ip', 'src_port', 'dest_port', 'community_id' and 'label_tactic' connections = df.groupby('community_id')['label_tactic'].value_counts().unstack(fill_value=0) connections.rename(columns={True:"True_count", False:"False_count"}, inplace=True) connections = connections[connections["True_count"]!=0] with shelve.open(path, flag='c') as db: for index, row in connections.iterrows(): if index in db: db[index].attack_amount += row['True_count'] db[index].amount += (row['True_count'] + row['False_count']) else: network_pair = NetworkPair(row['True_count']+row['False_count'], row['True_count'], index) db[index] = network_pair db.close()
export class Util { static deepCopy = <T>(target: T): T => { if (target === null) { return target; } if (target instanceof Date) { return new Date(target.getTime()) as any; } if (target instanceof Array) { const cp = [] as any[]; (target as any[]).forEach((v) => { cp.push(v); }); return cp.map((n: any) => Util.deepCopy<any>(n)) as any; } if (typeof target === 'object' && target !== {}) { const cp = { ...(target as { [key: string]: any }) } as { [key: string]: any }; Object.keys(cp).forEach((k) => { cp[k] = Util.deepCopy<any>(cp[k]); }); return cp as T; } return target; }; static notEmpty<TValue>(value: TValue | null | undefined): value is TValue { return value !== null && value !== undefined; } static removeSuffixIfPresent = (suffix: string, original: string): string => { if (original.length < suffix.length) { return original; } const candidate = original.substr(original.length - suffix.length); if (candidate === suffix) { return original.substr(0, original.length - suffix.length); } return original; }; static removePrefixIfPresent = (prefix: string, original: string): string => { if (original.startsWith(prefix)) { return original.slice(prefix.length); } return original; }; static getDisplayNameForTreatment = (t: { name: string; concentration?: number }): string => { if (t.concentration && t.concentration < 100) { return `${t.concentration.toFixed(0)}% ${t.name}`; } else { return t.name; } }; static generateUUID = () => { return Math.random().toString(36).slice(2); }; static firstOrNull<T>(list: T[]): T | null { if (list.length > 0) { return list[0]; } return null; } static lastIndexInArray = (array: any[]): number => { return array.length - 1; }; static lastItemInArray = <T>(array: T[]): T => { return array[array.length - 1]; }; /** * * The main reason for this function is about to integrate the Realms Objects or Collections * and redux, not update the store unless it is a POJO. * */ static toPojo = <T>(fields: string[], rawEntity: T): T => { const pojo: T = {} as T; fields.forEach((field) => (pojo[field] = rawEntity[field])); return pojo; }; static toArrayPojo = <T>(entityProps: string[], realmObjects: Realm.Collection<T>): T[] => { const parseData: T[] = []; realmObjects.forEach((ro) => { const pojo = Util.toPojo<T>(entityProps, ro); parseData.push(pojo); }); return parseData; }; static abbreviate = (volume: number): string => { if (volume < 1000) { return volume.toFixed(0); } return `${(volume / 1000).toFixed(0)}K`; }; static generateTimestamp = () => { return Date.now(); }; static excludeFalsy = (array: any[]) => { return array.filter(Boolean); } static hasInArray = (array: any[], value: string) => { return array.some((s) => s.includes(value)); } static doAsync = async (cb: () => void) => { setTimeout(cb, 1); } static delay = async (seconds: number) => { return new Promise((resolve) => { setTimeout(resolve, seconds * 1000); }); } // These 2 methods use ISO strings (supposedly) static stringFromTimestamp = (ts: number): string => { const d = new Date(ts); return d.toISOString(); } static timestampFromString = (ds: string): number => { const d = new Date(ds); return d.getTime(); } }
= 같은 객체에 대한 여러 변수의 참조 * 하나의 객체에 대한 여러 변수의 참조 ** 두 참조 변수에서 읽기/쓰기는 같은 객체에 적용됨 image:./images/image04.png[] [source, java] ---- BankAccount account = new BankAccount(); account.accountNumber = 1; account.ownerName = “James”; BankAccount account2 = account; System.out.println(account2.accountNumber); System.out.println(account2.ownerName); ---- --- 다른 두 참조 타입 변수는 같은 객체를 참조할 수 있습니다. 참조 타입 변수는 객체가 있는 곳의 값을 저장하기 때문입니다. 이는 같은 객체를 참조하고 있는 두 변수 중 하나의 변수에서 수정이 발생하면 두 변수 모두 영향을 받는다는 것을 의미합니다. == 같은 객체에 대한 여러 변수의 참조 예제에서, `account1` 과 `account2` 는 같은 객체를 가리킵니다. `account1` 은 `new` 연산자를 사용하여 초기화되었고, `accountNumber` 멤버와 `ownerName` 멤버에 값이 할당되었습니다. 그리고 `BankAccount` 타입의 `account2` 에 복사되었습니다. 그리고 두 변수의 값을 출력합니다. [source, java] ---- BankAccount account1 = new BankAccount(); account1.accountNumber = 1; account1.ownerName = "James"; ---- account2의 값은 account1 변수에 할당한 값과 동일합니다. ---- 1 James ---- `account2` 를 `account1` 에 할당하면 두 참조 타입 변수가 동일한 객체를 참조하도록 참조가 복사됩니다. 즉, 객체가 존재하는 위치가 복사됩니다. 따라서 `account2` 는 `account1` 에 할당한 값과 동일한 값을 출력합니다. 위 코드에서 변수는 두 개지만 객체는 하나입니다. == 같은 객체를 참조하는 변수의 값을 변경 아래 예제는 `account1` 변수의 값을 변경한 후 `account2` 변수의 값을 확인합니다. [source, java] ---- account1.accountNumber = 2; account1.ownerName = "Jason"; System.out.println(account2.accountNumber); System.out.println(account2.ownerName); ---- 출력은 아래와 같습니다. ---- 2 Jason ---- 결과는 `account1` 변수를 변경한 값을 보여줍니다. `account1` 과 `account2` 두 변수는 같은 객체를 가리키고 있기 때문에, `account1` 을 통해 변경한 값은 `account2` 에도 당연히 영향을 미칩니다. link:./06_comparision.adoc[이전: 값 타입의 비교와 참조 타입의 비교] + link:./08_ref_as_parameter.adoc[다음: 메소드 파라미터에 참조 타입 사용]
import matplotlib.pyplot as plt import numpy as np import pandas as pd from gsfanalysis.statistics import mode from scipy.stats import skew def quantile_interval(data, q, midpoint=0): sorted_data = np.sort(data - midpoint) q = np.quantile(abs(sorted_data), q) interval = ( midpoint + sorted_data[sorted_data > -q][0], midpoint + sorted_data[sorted_data < q][-1], ) return 0.5 * (interval[1] - interval[0]), interval def plot_sets(ax, sets, key, clip_range, assymetric_interval=False, density=False): line_collections = [] for df, label, color in sets: histopts = dict(bins=100, alpha=0.3, color=color, zorder=-10, density=density) sample_mode = mode(df[key]) def compute_q_and_interval(quantile): if assymetric_interval: q, q_interval = quantile_interval(df[key], quantile, sample_mode) else: q = np.quantile(abs(df[key] - sample_mode), quantile) q_interval = (sample_mode - q, sample_mode + q) return q, q_interval q95, q95_interval = compute_q_and_interval(0.95) q68, q68_interval = compute_q_and_interval(0.68) hist, _, _ = ax.hist( np.clip(df[key], *clip_range), # label="{} - rms: {:.3f}".format(label, rms(df[key])), label=label, range=clip_range, **histopts ) ax.vlines( [sample_mode], ymin=0, ymax=0.66 * max(hist), color=color, label="mode: {:.3f}".format(sample_mode), ls="--", zorder=-3, lw=1, ) ax.plot( q95_interval, 2 * [0.33 * max(hist)], "-o", color=color, # label="Q95: {:.3f}\n rms: {:.3f}".format(q95, rms(df[key].between(*q95_interval)))) label="Q95: {:.3f}".format(q95), ) ax.plot( q68_interval, 2 * [0.66 * max(hist)], "-s", color=color, # label="Q68: {:.3f}\n rms: {:.3f}".format(q68, rms(df[key].between(*q68_interval)))) label="Q68: {:.3f}".format(q68), ) q95_mean = np.mean(df[key][ df[key].between(*q95_interval) ]) print("mean", np.mean(df[key]), "q95_mean", q95_mean, "q95", q95_interval, flush=True) line_collections.append( ax.vlines( [q95_mean], ymin=0, ymax=0.1*max(hist), color=color, label="$\mathrm{{mean}}_{{Q95}}$: {:.3f}".format(q95_mean), zorder=-3, lw=3, ) ) # Bring mean bars to same height ys = [ lc.get_segments()[0][1,1] for lc in line_collections ] for lc in line_collections: s = lc.get_segments() s[0][1,1] = np.mean(ys) lc.set_segments(s) def make_gsf_detailed_comparison_plots( sets, logy=False, mean_height=None, assymetric_interval=False ): """ A set is a tuple (df, label, color-string) """ fig, axes = plt.subplots(1, 3, figsize=(16, 5)) keys = ["res_eQOP_fit", "res_ePNORM_fit", "pull_eQOP_fit"] base_ranges = [(-0.05, 0.05), (-0.3, 0.3), (-2, 2)] # First evaluate ranges, so that we have sane binning afterwards for the hist for i, key in enumerate(keys): for df, _, _ in sets: m = mode(df[key]) if assymetric_interval: _, interval = quantile_interval(df[key], 0.95, m) else: q = np.quantile(abs(df[key] - m), 0.95) interval = (m - q, m + q) base_ranges[i] = ( min([base_ranges[i][0], interval[0], np.mean(df[key])]), max([base_ranges[i][1], interval[1], np.mean(df[key])]), ) for ax, key, clip_range in zip(axes, keys, base_ranges): plot_sets(ax, sets, key, clip_range, assymetric_interval=assymetric_interval) if logy: for ax in axes: ax.set_yscale("log") legend_opts = dict(loc="upper center", bbox_to_anchor=(0.5, -0.2), ncol=2) axes[0].set_title("res QOP") axes[0].legend(**legend_opts) axes[0].set_xlabel("${qop}_{fit} - {qop}_{true} \quad [GeV^{-1}]$") axes[1].set_title("res PNORM") axes[1].legend(**legend_opts) axes[1].set_xlabel("$({p}_{fit} - {p}_{true}) \;/\; p_{true}$") axes[2].set_title("pull QOP") axes[2].legend(**legend_opts) axes[2].set_xlabel("$({qop}_{fit} - {qop}_{true}) \;/\; \sigma_{qop,fit}$") return fig, ax
import { Box, Icon, Text } from '@chakra-ui/react'; import { HeadProps, Link, PageProps, graphql } from 'gatsby'; import React from 'react'; import { IoTodayOutline, IoTrophyOutline } from 'react-icons/io5'; import { Card, CommonHead } from '../components'; import { useContent, useHead } from '../hooks'; import { formatPeriod, formatProgress, getPhotoURL } from '../utils/challenge'; function ChallengesPage({ data: { datoCmsChallengesGeovelo, allChallenge: { nodes: allChallenges }, }, }: PageProps<Queries.ChallengesQuery>): JSX.Element { const { elements } = useContent({ data: datoCmsChallengesGeovelo }); return ( <> {elements?.map(({ Ele, data }) => <Ele data={data} key={data.id} />)} <Box alignSelf="center" display="flex" flexDirection="column" gap={5} maxWidth="100%" padding={5} width={1000} > <Box display="flex" flexWrap="wrap" gap={3}> {allChallenges.map(({ data }) => { if (!data) return <></>; const { id, title, start_datetime, end_datetime, description, photo, collaboration_type, target_type, target_value, progress_value, } = data; if (!title || !start_datetime || !end_datetime) return <></>; const startDatetime = new Date(start_datetime); const endDatetime = new Date(end_datetime); const progress = formatProgress({ collaboration_type, target_type, target_value, progress_value, }); return ( <Box as={Link} borderRadius="16px" key={id} overflow="hidden" sx={{ '&:hover': { backgroundColor: '#efefef', img: { transform: 'scale(1.1)', transition: '0.5s ease' }, }, }} to={`/challenges/${id}`} width={['100%', 'calc((100% - 24px) / 2)', 'calc((100% - 48px) / 3)']} > <Card image={getPhotoURL(photo)} imageAlt="" imagePosition="top" subtitle={ <Box display="flex" flexDirection="column" gap={2}> <Text className="webkit-box" display="-webkit-box" overflow="hidden" style={{ WebkitLineClamp: 3, WebkitBoxOrient: 'vertical' }} > {description || 'Parcourez le plus de kilomètres à vélo'} </Text> <Box display="flex" flexDirection="column" gap={1}> <Box alignItems="center" display="flex" flexDirection="row" gap={1}> <Icon as={IoTodayOutline} color="grey" /> <Text color="grey" fontSize="sm"> {formatPeriod({ startDatetime, endDatetime })} </Text> </Box> {progress && ( <Box alignItems="center" display="flex" flexDirection="row" gap={1}> <Icon as={IoTrophyOutline} color="grey" /> <Text color="grey" fontSize="sm"> {progress} </Text> </Box> )} </Box> </Box> } title={title} variant="outlined" /> </Box> ); })} </Box> </Box> </> ); } export default ChallengesPage; export function Head({ data: { site, datoCmsChallengesGeovelo }, }: HeadProps<Queries.ChallengesQuery>) { const { title, description, url } = useHead({ data: { title: datoCmsChallengesGeovelo?.hero?.title, description: datoCmsChallengesGeovelo?.hero?.subtitle, }, site, }); const imageUrl = datoCmsChallengesGeovelo?.metaImage?.url || datoCmsChallengesGeovelo?.hero?.backgroundImage?.url; return ( <CommonHead description={description} imageUrl={imageUrl} title={title} url={`${url}/challenges`} /> ); } export const query = graphql` fragment ChallengesQuery on DatoCmsChallengesGeovelo { metaImage { url } hero { ...Hero } } fragment Challenge on challenge { data { id title start_datetime end_datetime photo description collaboration_type target_type target_value progress_value } } query Challenges { site { ...GatsbySite } datoCmsChallengesGeovelo { ...ChallengesQuery } allChallenge(sort: { data: { start_datetime: DESC } }) { nodes { ...Challenge } } } `;
import useUser from '@/hooks/useUser'; import { profileMessages } from '@/translations/profile'; import Head from 'next/head'; import React, { Fragment } from 'react'; import { useIntl } from 'react-intl'; import InactiveAlert from './components/InactiveAlert'; import ChangePassword from './components/ChangePassword/ChangePassword'; import { Card, CardContent, Grid, Typography } from '@mui/material'; import ProfileUserInfo from './components/ProfileUserInfo/ProfileUserInfo'; function Profile() { const intl = useIntl(); const { isActive } = useUser(); return ( <Fragment> <Head> <title>{intl.formatMessage(profileMessages.pageTitle)}</title> </Head> {!isActive && <InactiveAlert />} <Grid container spacing={2} rowSpacing={2}> <Grid item xs={12} sm={6}> <Card sx={{ minHeight: '500px' }}> <CardContent> <Typography variant="body1" marginBottom="12px"> {intl.formatMessage(profileMessages.userInfoSectionTitle)} </Typography> <ProfileUserInfo /> </CardContent> </Card> </Grid> <Grid item xs={12} sm={6}> <Card sx={{ minHeight: '500px' }}> <CardContent> <Typography variant="body1" marginBottom="12px"> {intl.formatMessage(profileMessages.changePasswordSectionTitle)} </Typography> <ChangePassword /> </CardContent> </Card> </Grid> </Grid> </Fragment> ); } export default Profile;
import { React, useState, useEffect } from "react"; import { v4 as uuidv4 } from "uuid"; const Checklist = () => { // const [notes, setNotes] = useState(initNotes); const [notes, setNotes] = useState(""); // const [obj, setObj] = useState(getInitObj()); // получение данных из localStorage const [localItem, setLocalItem] = useState( JSON.parse(localStorage.getItem("elems")) || [] ); //после обновления элементов в notes, запускается запись данных в localStorage useEffect(() => { localStorage.setItem("elems", JSON.stringify(localItem)); }, [localItem]); const newItem = () => { if (notes.trim() !== "") { const newElem = { id: uuidv4(), task: notes, isEdit: false, isDone: false, }; setLocalItem((localItem) => [...localItem, newElem]); setNotes(""); } }; function editTask(id) { setLocalItem( localItem.map((note) => { if (note.id === id) { note.isEdit = !note.isEdit; } return note; }) ); } function changeItem(id, field, e) { setLocalItem( localItem.map((note) => { if (note.id === id) { note[field] = e.target.value; } return note; }) ); } function doneTask(id) { setLocalItem( localItem.map((note) => { if (note.id === id) { note.isDone = !note.isDone; } return note; }) ); } function removeTask(id) { setLocalItem(localItem.filter((note) => note.id !== id)); } function keyPress(el) { const code = el.keyCode || el.which; if (code === 13) newItem(); } const result = localItem.map((note) => ( <tr key={note.id}> <td> {note.isEdit ? ( <input value={note.task} onChange={(e) => changeItem(note.id, "task", e)} onBlur={() => editTask(note.id)} autoFocus /> ) : ( <span onDoubleClick={() => editTask(note.id)} className={note.isDone ? "done" : ""} > {note.task} </span> )} <button onClick={() => removeTask(note.id)}>х</button> <button onClick={() => doneTask(note.id)}> {note.isEdit ? "ok" : "✔"} </button> </td> </tr> )); return ( <div> <table> <thead> <tr> <td> {localItem == [] || localItem == "" ? "Добавьте задачу" : "Задачи"} </td> </tr> </thead> <tbody>{result}</tbody> </table> <input placeholder="Добавить задачу..." value={notes} onKeyDown={(el) => keyPress(el)} onChange={(e) => setNotes(e.target.value)} /> <button onClick={newItem}>add task</button> </div> ); }; export default Checklist;
import { useState } from "react"; import { Box, Button, Card, TextField } from "@material-ui/core"; import { updatePassword } from "../../../../actions/updateProfile"; const ProfilePassword = () => { const [password, setPassword] = useState(""); const [passwordVer, setPasswordVer] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); const handleUpdatePassword = (e) => { if (password === "" || passwordVer === "") { setError("Please enter all required information!"); return; } if (password.length < 6 || password.length > 15) { setError("The password must contain 6-15 characters!"); return; } if (password !== passwordVer) { setError("Passords don't match!"); return; } setError(""); setIsLoading(true); let data = { password: password, password2: passwordVer, }; updatePassword(data).then((response) => { if (!response) { setError("Try Again Later!"); setIsLoading(false); return; } else if (response && response.status >= 400) { setError(`${response.data ? response.data : "Try Again Later!"}`); setIsLoading(false); } else { setPassword(""); setPasswordVer(""); setError("") alert("Password saved successfully! "); setIsLoading(false); } }); }; const onChangeHandler = (e) => { const { name, value } = e.currentTarget; setError(""); if (name === "Password") { setPassword(value); } else if (name === "PasswordVer") { setPasswordVer(value); } }; return ( <Box mt={2}> <Card> <Box m={2}> <TextField placeholder="Your Password" label="Password" id="Password" name="Password" type="password" margin="normal" fullWidth required error={error ? true : false} helperText={error ? error : ""} value={password} onChange={(e) => onChangeHandler(e)} /> <TextField placeholder="Reapet your Password" label="Repeat Password" id="PasswordVer" name="PasswordVer" type="password" margin="normal" fullWidth required error={error ? true : false} helperText={error ? error : ""} value={passwordVer} onChange={(e) => onChangeHandler(e)} /> <Button variant="contained" color="primary" fullWidth disabled={isLoading ? true : false} onClick={(e) => { handleUpdatePassword(e); }} > Update Password </Button> </Box> </Card> </Box> ); }; export default ProfilePassword;
const express = require('express'); const router = express.Router(); const roleController = require('../Controllers/roleController'); const { verifyToken, isAdmin } = require('../middleware/authMiddleware'); // Importer les middlewares /** * @swagger * tags: * name: Roles * description: Roles CRUD */ /** * @swagger * components: * schemas: * Role: * type: object * required: * - nom_role * properties: * nom_role: * type: string * description: The role name * example: * nom_role: "admin" */ /** * @swagger * /api/roles: * get: * summary: Get a list of roles * tags: [Roles] * responses: * 200: * description: A list of roles * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/Role' */ router.get('/',verifyToken, isAdmin, roleController.getRoles); /** * @swagger * /api/roles/{id}: * get: * summary: Get a role by ID * tags: [Roles] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: The role ID * responses: * 200: * description: A single role * content: * application/json: * schema: * $ref: '#/components/schemas/Role' * 404: * description: Role not found */ router.get('/:id', verifyToken, isAdmin, roleController.getRoleById); /** * @swagger * /api/roles: * post: * summary: Create a new role * tags: [Roles] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/Role' * responses: * 201: * description: Role created successfully * 400: * description: Invalid input */ router.post('/', verifyToken, isAdmin, roleController.createRole); /** * @swagger * /api/roles/{id}: * put: * summary: Update an existing role * tags: [Roles] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: The role ID * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/Role' * responses: * 200: * description: Role updated successfully * 404: * description: Role not found */ router.put('/:id', verifyToken, isAdmin, roleController.updateRole); /** * @swagger * /api/roles/{id}: * delete: * summary: Delete a role * tags: [Roles] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: The role ID * responses: * 200: * description: Role deleted successfully * 404: * description: Role not found */ router.delete('/:id', verifyToken, isAdmin, roleController.deleteRole); module.exports = router;
import React, { useEffect, useState } from "react"; import { Form, FormGroup, Input, Button, Container, Row, Col, Label } from 'reactstrap'; import { IoIosAddCircleOutline } from "react-icons/io"; import { Modal, ModalHeader, ModalBody } from "reactstrap"; import { useNavigate } from "react-router-dom"; import Pagination from "../Employee/pagination.component"; import axios from "axios"; import base_url from "../../api/bootapi"; import Sidebar from "../sidebar/sidebar.component"; import Navbar from "../navbar/Navbar.component"; import Divisions from "./divisions.component"; import { useFormValidator } from "./inputValidator"; import './divisionList.css'; const DivisionList = () => { let navigate = useNavigate(); const [currentPage, setCurrentPage] = useState(1); const [recordsPerPage] = useState(5); // Modal open state const [modal, setModal] = React.useState(false); // Toggle for Modal const toggle = () => setModal(!modal); const reload=()=>window.location.reload(); const [optionList,setOptionList] = useState([]); const fetchOptionData = () => { axios.get(`${base_url}/api/department/search`) .then((response) => { const { data } = response; if(response.status === 200){ //check the api call is success by stats code 200,201 ...etc setOptionList(data) }else{ //error handle section } }) .catch((error) => console.log(error)); }; // Function to calling server const getDivisionListFromServer = () => { axios.get(`${base_url}/api/division/search`).then( (response) => { console.log(response.data); setDivisions(response.data); }, (error) => { console.log(error); } ) } useEffect(() => { getDivisionListFromServer(); fetchOptionData(); }, []) const handleSearch = (e) => { e.preventDefault(); const departname = e.target.elements.division_name.value; getSearchDivisionListFromServer(departname); e.target.reset(); } const getSearchDivisionListFromServer = (searchdata) => { axios.get(`${base_url}/api/division/kensaku?query=${searchdata}`).then( (response) => { console.log(response.data); setCurrentPage(1); setDivisions(response.data); }, (error) => { console.log(error); } ) } const [divisions, setDivisions] = useState([]); const indexOfLastRecord = currentPage * recordsPerPage; const indexOfFirstRecord = indexOfLastRecord - recordsPerPage; const currentRecords = divisions.slice(indexOfFirstRecord, indexOfLastRecord); const nPages = Math.ceil(divisions.length / recordsPerPage) const [division, setDivision] = useState(""); const { errors, validateForm} = useFormValidator(division); const onUpdateField = (e) => { const field = e.target.name; const value = e.target.type === "checkbox" ? e.target.checked : e.target.value; const nextFormState = { ...division, [field] : value }; setDivision(nextFormState); } const handleForm = (e) => { e.preventDefault(); const{isValid} = validateForm({division, errors, forceTouchErrors:true}); if(!isValid) return; alert(JSON.stringify(division, null, 2)); console.log(division); postToServer(division); e.target.reset(); } const postToServer = (data) => { axios.post(`${base_url}/api/division/register`, data).then( (response) => { console.log(response); toggle(); reload(); navigate("/divlist"); }, (error) => { console.log(error) } ) } useEffect(() => { document.title = "Division List || Expense management system" }, []) return ( <div className='home'> <Sidebar /> <div className='homeContainer'> <Navbar /> <div className='bodydesign'> <div className='expensecatlistmaindiv'> <Container> <Form onSubmit={handleSearch} className='expensecatlistmainform'> <Row> <Col md="12"> <FormGroup> <Label>課名</Label> <Input type="search" id="" name="division_name" className='listinputdesign' /> </FormGroup> </Col> </Row> <Row> <Col md="2"> <Row> <Col md="6"> <Button type="submit" className="searchbtn searchbtnwidth">検索</Button> </Col> <Col md="6"> </Col> </Row> </Col> <Col md="10"> </Col> </Row> </Form> <Row className="tablerow"> <Col md="12"> <Row className='margin-less'> <Col md="10"></Col> <Col md="2"> <Button color="danger" className="expcatregisterbtn" onClick={toggle}><IoIosAddCircleOutline className='icondesigncolor' /></Button> <Modal size="lg" isOpen={modal} toggle={toggle} className="mainModal"> <ModalHeader toggle={toggle}> <h1 className='headingdivisiondesign'>課の登録</h1> </ModalHeader> <ModalBody> <Form onSubmit={handleForm}> <Container > <Row> <Col md="2"> <FormGroup> <Label>所属部署</Label> </FormGroup> </Col> <Col md="10"> <FormGroup > <select aria-label="Default select example" className="form-control registerinputdesign" onChange={(e) => { setDivision({ ...division, department_name: e.target.value }) }} required> {optionList.map((item) => ( <option key={item.department_id} value={item.department_name}> {item.department_name} </option> ))} </select> </FormGroup> </Col> </Row> <Row className="my-3"> <Col md="2"> <FormGroup> <Label>課名</Label> </FormGroup> </Col> <Col md="10"> <FormGroup> <Input type="text" id="division_name" name="division_name" value={division.division_name} onChange={onUpdateField} /> {errors.division_name.dirty && errors.division_name.error ? (<span style={{ color: "red" }}>{errors.division_name.message}</span>) : null} </FormGroup> </Col> </Row> <Row className="my-2"> <Col md="2"> <FormGroup> <Label> アクセス </Label> </FormGroup> </Col> <Col md="10"> <FormGroup> <Input type="checkbox" name="auth_user_edit" id="auth_user_edit" onChange={onUpdateField} />{" "} ユーザー編集権限 </FormGroup> </Col> </Row> <Row className="my-2"> <Col md="2" /> <Col md="10"> <FormGroup> <Input type="checkbox" name="auth_expense_category" id="auth_expense_category" onChange={onUpdateField} />{" "} 勘定科目編集権限 </FormGroup> </Col> </Row> <Row className="my-2"> <Col md="2" /> <Col md="10"> <FormGroup> <Input type="checkbox" name="auth_payment_edit" id="auth_payment_edit" onChange={onUpdateField} />{" "} 支払編集権限 </FormGroup> </Col> </Row> <Row className="margindivisiontop"> <Col md="3"> <Button type="submit" className="registerbtn">登録</Button> </Col> <Col md="6"> </Col> <Col md="3"> <Button onClick={toggle} className="deletebtn">キャンセル</Button> </Col> </Row> </Container> </Form> </ModalBody> </Modal> </Col> </Row> <Row className='margin-less'> <Col md="12"> <Divisions divisions={currentRecords} /> <Pagination nPages={nPages} currentPage={currentPage} setCurrentPage={setCurrentPage} /> </Col> </Row> </Col> </Row> </Container> </div> </div> </div> </div> ) } export default DivisionList;
import { AdminRepo, IAdminAllResponse } from '../repo/admin' import Admin, { IAdmin } from '../../models/Admin' import { logger } from '../../config/logger' import AppError from '../../utils/appError' export class AdminStorage implements AdminRepo { private scope = 'storage.admin' async find(query: Object): Promise<IAdmin[]> { try { let dbObj = await Admin.find({ ...query }, { 'password': false }) return dbObj } catch (error) { logger.error(`${this.scope}.find: finished with error: ${error}`) throw error } } async findOne(query: Object): Promise<IAdmin> { try { let dbObj = await Admin.findOne({ ...query }, { 'password': false }) if (!dbObj) { logger.warn(`${this.scope}.get failed to findOne`) throw new AppError(404, 'admin_404') } return dbObj } catch (error) { logger.error(`${this.scope}.findOne: finished with error: ${error}`) throw error } } async findLogin(query: Object): Promise<IAdmin | null> { try { let dbObj = await Admin.findOne({ ...query }) return dbObj } catch (error) { logger.error(`${this.scope}.find: finished with error: ${error}`) throw error } } async findSuperAdmin(query: Object): Promise<IAdmin> { try { let dbObj = await Admin.findOne({ ...query }, { 'password': false }) if (!dbObj) { logger.warn(`${this.scope}.get failed to findOne`) throw new AppError(404, 'admin_404') } return dbObj } catch (error) { logger.error(`${this.scope}.findOne: finished with error: ${error}`) throw error } } async create(payload: IAdmin): Promise<IAdmin> { try { let dbObj = await Admin.create(payload) return dbObj } catch (error) { logger.error(`${this.scope}.create: finished with error: ${error}`) throw error } } async update(id: Object, payload: IAdmin): Promise<IAdmin> { try { let dbObj = await Admin.findByIdAndUpdate(id, payload, { new: true }) if (!dbObj) { logger.warn(`${this.scope}.update failed to findByIdAndUpdate`) throw new AppError(404, 'admin_404') } return dbObj } catch (error) { logger.error(`${this.scope}.update: finished with error: ${error}`) throw error } } async delete(id: Object): Promise<any> { try { let dbObj = await Admin.findByIdAndDelete(id) if (!dbObj) { logger.warn(`${this.scope}.delete failed to findByIdAndDelete`) throw new AppError(404, 'admin_404') } return dbObj } catch (error) { logger.error(`${this.scope}.delete: finished with error: ${error}`) throw error } } }
package function; public class Ex03 { // 함수 만들기 // 1. 함수의 호출부분이 있으면 복사해서 정의할 부분으로 가져온다. // 함수 호출 부분이 대입식이라면 좌변과 우변의 자료형이 같아야함을 이용하여 반환형을 결정함. static int summary(int from, int to) { int sum = 0; for(int i = from; i <= to; i++) { sum += i; } return sum; } // This method must return a result of type int static int getFee(int time) { int fee = 3000; // 첫 줄은 반환형의 변수 선언 및 초기화 if (time > 30) { // 중간에 제어문 및 연산자, 변수등으로 fee += (time - 21) / 10 * 500; // 매개변수를 포함한 } // 처리코드를 작성하면 된다. return fee; // 마지막 줄은 반환형 변수의 return } // 2) 함수 정의에서 기본 문형은 [반환자료형] [함수이름]([매개변수])이다. // 3) ()안에 있는 값은 인자이다. 인자를 받기 위한 매개변수를 선언한다. // 4) 함수 정의에서는 함수의 구체적인 실행 내용을 작성해야함으로 ; 대신 {}를 열어줌. // 5) 자바의 함수는 반환자료형의 값을 반드시 반환해야만한다. // 따라서, 첫 줄에는 반환형 타입의 변수를 선언 및 초기화하고 마지막줄에 return하도록 한다. // 6. 첫줄과 마지막줄이 만들어졌다면 그 사이에서 매개변수값을 활용한 코드를 작성해야함. public static void main(String[] args) { // 1) 두 정수를 전달하여 두 정수 사이의 합계를 반환하는 함수 int q1 = summary(1, 100); System.out.println("q1: " + q1); int t1 = summary(11, 20); System.out.println("t1: " + t1); // 2) 놀이기구의 이용시간을 전달하여 이용요금을 반환하는 함수 int q2 = getFee(30); int t2 = getFee(31); int t3 = getFee(39); int t4 = getFee(40); int t5 = getFee(41); System.out.println(q2); System.out.println(t2); System.out.println(t3); System.out.println(t4); System.out.println(t5); } }
/* * Copyright (c) 2023 Airbyte, Inc., all rights reserved. */ package io.airbyte.cdk.integrations.destination.s3.avro import io.airbyte.cdk.integrations.destination.s3.avro.JsonSchemaType.Companion.fromJsonSchemaType import java.util.stream.Stream import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource class JsonSchemaTypeTest { @ParameterizedTest @ArgumentsSource(JsonSchemaTypeProvider::class) fun testFromJsonSchemaType( type: String, airbyteType: String?, expectedJsonSchemaType: JsonSchemaType? ) { Assertions.assertEquals(expectedJsonSchemaType, fromJsonSchemaType(type, airbyteType)) } class JsonSchemaTypeProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext): Stream<out Arguments> { return Stream.of( Arguments.of( "WellKnownTypes.json#/definitions/Number", null, JsonSchemaType.NUMBER_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/String", null, JsonSchemaType.STRING_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/Integer", null, JsonSchemaType.INTEGER_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/Boolean", null, JsonSchemaType.BOOLEAN_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/BinaryData", null, JsonSchemaType.BINARY_DATA_V1 ), Arguments.of("WellKnownTypes.json#/definitions/Date", null, JsonSchemaType.DATE_V1), Arguments.of( "WellKnownTypes.json#/definitions/TimestampWithTimezone", null, JsonSchemaType.TIMESTAMP_WITH_TIMEZONE_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/TimestampWithoutTimezone", null, JsonSchemaType.TIMESTAMP_WITHOUT_TIMEZONE_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/TimeWithTimezone", null, JsonSchemaType.TIME_WITH_TIMEZONE_V1 ), Arguments.of( "WellKnownTypes.json#/definitions/TimeWithoutTimezone", null, JsonSchemaType.TIME_WITHOUT_TIMEZONE_V1 ), Arguments.of("number", "integer", JsonSchemaType.NUMBER_INT_V0), Arguments.of("string", "big_integer", JsonSchemaType.NUMBER_BIGINT_V0), Arguments.of("number", "float", JsonSchemaType.NUMBER_FLOAT_V0), Arguments.of("number", null, JsonSchemaType.NUMBER_V0), Arguments.of("string", null, JsonSchemaType.STRING_V0), Arguments.of("integer", null, JsonSchemaType.INTEGER_V0), Arguments.of("boolean", null, JsonSchemaType.BOOLEAN_V0), Arguments.of("null", null, JsonSchemaType.NULL), Arguments.of("object", null, JsonSchemaType.OBJECT), Arguments.of("array", null, JsonSchemaType.ARRAY), Arguments.of("combined", null, JsonSchemaType.COMBINED) ) } } }
import 'package:auto_route/auto_route.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:domain/domain.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../bloc/home_bloc.dart'; import 'widgets/book_card_item.dart'; import 'widgets/carousel_slider_item.dart'; @RoutePage(name: 'BookShelfTabRouter') class BookShelfTab extends StatelessWidget { const BookShelfTab({required this.onItemPressed, super.key}); final Function(NovelModel novel) onItemPressed; @override Widget build(BuildContext context) { return BlocBuilder<HomeBloc, HomeState>( buildWhen: (prev, cur) => prev.novelInShelf != cur.novelInShelf, builder: (context, state) { final novelInShelf = state.novelInShelf; return ListView( padding: const EdgeInsets.symmetric(horizontal: 5), children: [ if (novelInShelf.isNotEmpty) CarouselSlider.builder( options: CarouselOptions( aspectRatio: 2, autoPlay: true, autoPlayAnimationDuration: const Duration(seconds: 3), ), itemCount: novelInShelf.length < 3 ? novelInShelf.length : 3, itemBuilder: (context, itemIndex, pageViewIndex) { return CarouselSliderItem( novelModel: novelInShelf[itemIndex], onPressed: () => onItemPressed.call(novelInShelf[itemIndex]), ); }, ), const SizedBox(height: 10), if (novelInShelf.length - 3 > 0) GridView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 2 / 3, ), itemCount: novelInShelf.length - 3, itemBuilder: (context, index) { final novel = novelInShelf[index + 3]; return BookCardItem( imageUrl: novel.imgUrl, bookName: novel.name, totalChapter: novel.totalChapters, currentChapter: novel.currentChapter, onPressed: () => onItemPressed.call(novel), scrollPercent: novel.scrollPercent, ); }, ), ], ); }, ); } }
import React, { useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { selectProduct } from "../Feautures/products/productSlice"; const columns1 = [ { Header: "SELECT", accessor: "select", }, { Header: "ID", accessor: "id", }, { Header: "TITLE", accessor: "Title", }, { Header: "CATEGORY", accessor: "Category", }, { Header: "PRICE", accessor: "Price", }, { Header: "STOCK", accessor: "Stock", }, ]; const Table2 = () => { const { products, selectedProduct, searchedProducts } = useSelector( (state) => state.products ); const dispatch = useDispatch(); // console.log(searchedProducts); // console.log(products); const handleRowClick = (productId) => { const isSelected = selectedProduct.some( (selected) => selected.id === productId ); // If the product is already selected, remove it from the selectedProduct array if (isSelected) { const updatedSelectedProduct = selectedProduct.filter( (selected) => selected.id !== productId ); dispatch(selectProduct(updatedSelectedProduct)); } else { // If the product is not selected, add it to the selectedProduct array const selectedProductItem = ( searchedProducts.length > 0 ? searchedProducts : products ).find((product) => product.id === productId); dispatch(selectProduct([...selectedProduct, selectedProductItem])); } }; const handleSelectAll = () => { // Check if all products are already selected const allSelected = selectedProduct.length === products.length; if (allSelected) { // If all selected, clear selection dispatch(selectProduct([])); } else { // If not all selected, select all dispatch(selectProduct([...products])); } }; const [initialDispatchDone, setInitialDispatchDone] = useState(false); const defalutSelected = products?.filter((item) => item.id < 6); // console.log(defalutSelected); useEffect(() => { dispatch(selectProduct(defalutSelected)); setInitialDispatchDone(true); console.log("hi"); }, [initialDispatchDone]); return ( <> <section className="flex justify-center items-center flex-col mx-auto p-4 "> <table className="w-3/5"> <thead className="bg-black text-white"> <tr> {columns1.map((column) => ( <th key={column.accessor} className="py-2 px-4"> {column.Header === "SELECT" ? ( // Checkbox in header for "Select All" <input type="checkbox" checked={selectedProduct.length === products.length} onChange={handleSelectAll} /> ) : ( // Other headers column.Header )} </th> ))} </tr> </thead> <tbody className="bg-blue-900 cursor-pointer"> {(searchedProducts.length > 0 ? searchedProducts : products).map( (product) => ( <tr onClick={() => handleRowClick(product.id)} key={product.id} className={`${ selectedProduct.some( (selected) => selected.id === product.id ) ? "bg-lime-500 hover:bg-lime-700 border-b text-white" // Change to red if in selected products : "border-b hover:bg-lime-700 hover:text-black text-base" }`} > {columns1.map((column, index) => ( <td key={column.accessor} className={`py-2 text-center px-4 ${ // Add a class for the checkbox column index === 0 ? "text-white" : "" }`} > {column.accessor === "select" ? ( // Checkbox in each row <input type="checkbox" checked={selectedProduct.some( (selected) => selected.id === product.id )} onChange={() => handleRowClick(product.id)} /> ) : ( // Other columns product[column.accessor] )} </td> ))} </tr> ) )} </tbody> </table> </section> </> ); }; export default Table2;
<section> <div class="container mt-md-5"> <div class="d-flex justify-content-between mb-4 posts-header"> <div class="article-title"> My Posts </div> <a href="/new-post"> Write a post </a> </div> <div class="container-fluid py-1 mb-1 posts-nav border-bottom"> <ul class="nav container d-flex flex-row"> <li class="nav-item"> <%= link_to "#{draft_count} Drafts", my_drafts_path , class: "nav-link text-dark posts-tab current" %> </li> <li class="nav-item"> <%= link_to "#{published_count} Published", my_published_path , class: "nav-link text-dark" %> </li> </ul> </div> <% if @articles.present? %> <% @articles.each do |article| %> <div class="border-bottom post-card"> <div class="font-weight-bold pt-3 title"> <%= link_to article.title, edit_post_path(article.slug) %> </div> <div class="text-muted content"> <%= sanitize article.content.truncate(40) %> </div> <div class='d-flex text-muted pb-3'> <small> Last edited on <%= format_date(article.updated_at) %> </small> <small class="ml-1"> <%= format_read_time(article) %> </small> <small class="dropdown"> <a class="text-dark" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-chevron-down ml-2"></i> </a> <div class="dropdown-menu draft-link" aria-labelledby="dropdownMenuLink"> <%= link_to "Preview draft", preview_path(article.slug), class: "dropdown-item" %> <%= link_to "Edit draft", edit_post_path(article.slug), class: "dropdown-item" %> <%= link_to "Delete draft", modal_post_path(article.slug), class: "dropdown-item", data: { :remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window' } %> </div> <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> </small> </div> </div> <% end %> <% else %> <p class="mt-4 d-flex justify-content-center font-italic">You don't have any draft yet!</p> <% end %> </div> </section>
import React, { lazy,Suspense } from "react"; import ReactDOM from "react-dom/client" import reslogo from "../images/reslogo.jpg" import Header from "./components/Header"; import Body from "./components/Body"; import { createBrowserRouter,RouterProvider,Outlet } from "react-router-dom"; import About from "./components/About"; import ContactUs from "./components/ContactUs"; import RestroMenuComponent from "./components/RestroMenuComponent"; import Demo from "./components/Demo"; const Grocery =lazy(()=>import("./components/Grocery")); const AppLayout=()=>{ return(<div className="app"> <Header /> <Outlet /> </div> ) } const appRouter=createBrowserRouter([ { path:"/", element:<AppLayout/>, children: [ { path:"/", element:<Body/> }, { path:"/about", element:<About/>, }, { path:"/contactus", element:<ContactUs/>, }, { path:"/restaurants/:resId", element:<RestroMenuComponent/> }, { path:"/grocery", element:<Suspense fallback={<h2>loading....</h2>}><Grocery /></Suspense> }, { path:"/demo", element:<Demo /> } ], errorElement:<Error />, }, ]); const root=ReactDOM.createRoot(document.getElementById("root")); root.render(<RouterProvider router={appRouter}/>);
import { Link } from 'react-router-dom'; import Carousel from 'react-bootstrap/Carousel'; import KidsCloths from '../../../assets/images/kids-ethnic-dress.jpg'; import MensCloths from '../../../assets/images/men-shirt.jpg'; import WomenCloths from '../../../assets/images/women-dress.jpg'; import './LiveOffersCarousel.css'; const LiveOffersCarousel = () => { // data related to carousel const data = [ { id: 1, src: KidsCloths, caption: 'Kids Wear', url: '/products?category=Kids', description: 'Bright, cheerful & fun to wear styles for kids', altText: 'Kids Slide' }, { id: 2, src: MensCloths, caption: 'Men\'s Wear', url: '/products?category=Men', description: 'update your on-duty style, add a dose of cool to style', altText: 'Mens Slide' }, { id: 3, src: WomenCloths, caption: 'Women\'s Wear', url: '/products?category=Women', description: 'Stay stylish with colourful prints, effortless fits', altText: 'Womens Slide' } ]; return ( <Carousel interval={5000} data-bs-theme="dark"> {data.map((slide) => { return ( <Carousel.Item key={slide.id} className="justify-content-center"> <img src={slide.src} alt={slide.altText} /> <Carousel.Caption> <p>{slide.description}</p> <Link to={slide.url}>{slide.caption}</Link> </Carousel.Caption> </Carousel.Item> ); })} </Carousel> ); }; export default LiveOffersCarousel;
import pygame import os pygame.font.init() pygame.mixer.init() pygame.display.set_caption("SPACE INVADERS") WIDTH, HEIGHT = 900, 500 WINDOW = pygame.display.set_mode((WIDTH, HEIGHT)) SPACESHIP_WIDTH = 55 SPACESHIP_HEIGHT = 40 BORDER = pygame.Rect(WIDTH//2-5, 0, 10, HEIGHT) YELLOW_HIT = pygame.USEREVENT + 1 RED_HIT = pygame.USEREVENT + 2 WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) YELLOW = (0,255,0) HEALTH_FONT = pygame.font.SysFont('comicsans', 40) WINNER_FONT = pygame.font.SysFont('comicsans', 40) VEL = 5 FPS = 60 BULLETS_VEL = 7 MAX_BULLETS = 3 BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join("Python Projects", 'Pygame','Assets', "Grenade+1.mp3")) BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join("Python Projects", 'Pygame','Assets', "Gun+Silencer.mp3")) YELLOW_SPACESHIP = pygame.image.load( os.path.join("Python Projects", 'Pygame','Assets', "spaceship_yellow.png")) YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale( YELLOW_SPACESHIP, (SPACESHIP_WIDTH,SPACESHIP_HEIGHT)), 90) RED_SPACESHIP = pygame.image.load( os.path.join("Python Projects", 'Pygame','Assets', "spaceship_yellow.png")) RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale( RED_SPACESHIP, (SPACESHIP_WIDTH,SPACESHIP_HEIGHT)), -90) SPACE = pygame.transform.scale(pygame.image.load( os.path.join("Python Projects", 'Pygame','Assets', "space.png")), (WIDTH, HEIGHT)) def handle_bullets(yellow_bullets, red_bullets, yellow, red): for bullet in yellow_bullets: bullet.x += BULLETS_VEL if red.colliderect(bullet): pygame.event.post(pygame.event.Event(RED_HIT)) yellow_bullets.remove(bullet) elif bullet.x > WIDTH: yellow_bullets.remove(bullet) for bullet in red_bullets: bullet.x -= BULLETS_VEL if yellow.colliderect(bullet): pygame.event.post(pygame.event.Event(YELLOW_HIT)) red_bullets.remove(bullet) elif bullet.x < 0: red_bullets.remove(bullet) def yellow_handle_movement(keys_pressed, yellow): if keys_pressed[pygame.K_a] and yellow.x - VEL > 0: #LEFT yellow.x -= VEL if keys_pressed[pygame.K_d] and yellow.x + VEL + yellow.width < BORDER.x: #RIGHT yellow.x += VEL if keys_pressed[pygame.K_w] and yellow.y - VEL > 0: #UP yellow.y -= VEL if keys_pressed[pygame.K_s] and yellow.y + VEL + yellow.height < HEIGHT - 15: #DOWN yellow.y += VEL def red_handle_movement(keys_pressed, red): if keys_pressed[pygame.K_LEFT] and red.x - VEL > BORDER.x + BORDER.width: #LEFT red.x -= VEL if keys_pressed[pygame.K_RIGHT] and red.x + VEL + red.width < WIDTH: #RIGHT red.x += VEL if keys_pressed[pygame.K_UP] and red.y - VEL > 0: #UP red.y -= VEL if keys_pressed[pygame.K_DOWN] and red.y + VEL + red.height < HEIGHT - 15: #DOWN red.y += VEL def draw_window(red, yellow, red_bullets, yellow_bullets, red_health, yellow_health): WINDOW.blit(SPACE, (0,0)) pygame.draw.rect(WINDOW, BLACK, BORDER) red_health_text = HEALTH_FONT.render("Health: " + str(red_health), 1, WHITE) yellow_health_text = HEALTH_FONT.render("Health: " + str(yellow_health), 1, WHITE) WINDOW.blit(red_health_text, (WIDTH - red_health_text.get_width() - 10, 10)) WINDOW.blit(yellow_health_text, (10, 10)) WINDOW.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y)) WINDOW.blit(RED_SPACESHIP, (red.x, red.y)) for bullet in red_bullets: pygame.draw.rect(WINDOW, RED, bullet) for bullet in yellow_bullets: pygame.draw.rect(WINDOW, YELLOW, bullet) pygame.display.update() def draw_winner(text): draw_text = WINNER_FONT.render(text, 1, WHITE) WINDOW.blit(draw_text, (WIDTH/2 - draw_text.get_width() / 2, HEIGHT/2 - draw_text.get_height()/2)) pygame.display.update() pygame.time.delay(5000) def main(): red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) yellow_bullets = [] red_bullets = [] red_health = 10 yellow_health = 10 clock = pygame.time.Clock() run = True while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LCTRL and len(yellow_bullets) < MAX_BULLETS: bullet = pygame.Rect( yellow.x + yellow.width, yellow.y + yellow.height//2 - 2, 10, 5) yellow_bullets.append(bullet) BULLET_FIRE_SOUND.play() if event.key == pygame.K_RCTRL and len(red_bullets) < MAX_BULLETS: bullet = pygame.Rect( red.x, red.y + red.height//2 - 2, 10, 5) red_bullets.append(bullet) BULLET_FIRE_SOUND.play() if event.type == RED_HIT: red_health -= 1 BULLET_HIT_SOUND.play() if event.type == YELLOW_HIT: yellow_health -= 1 BULLET_HIT_SOUND.play() winner_text = "" if red_health <= 0: winner_text = "Yellow wins!" if yellow_health <= 0: winner_text = "Red wins!" if winner_text != "": draw_winner(winner_text) break keys_pressed = pygame.key.get_pressed() yellow_handle_movement(keys_pressed, yellow) red_handle_movement(keys_pressed, red) handle_bullets(yellow_bullets, red_bullets, yellow, red) draw_window(red, yellow, red_bullets, yellow_bullets, red_health, yellow_health) main() if __name__ == "__main__": main()
import { io } from "socket.io-client" import { useAuth } from "../hooks/auth" import { useEffect, useState } from "react" import { useParams} from "react-router-dom" import { CommentsList, Footer, Header, InputLarge } from "../components" import { FindByIdTopics } from "../services/topics.services" export const TopicPage = ()=> { const { customer } = useAuth() const [data, setData] = useState(null); const [message, setMessage] = useState("") const params = useParams() const handleSendMessage = (event) => { if(event.key === "Enter" || event._reactName === "onClick") { console.log(message) setMessage("") } } async function fetchTopic(){ const result = await FindByIdTopics(params).then(respons=>{return respons}) if(result){ setData(result.data) } return result.data; } useEffect(() => { fetchTopic().then(data=>{ const socket = io(import.meta.env.VITE_BACKEND_URL); socket.on('connection', () => { console.log('Connected to the Socket.IO server!'); }); socket.emit("select_topic",{ data, customer }) // Listen for the "customEvent" event from the server socket.on('customEvent', (data) => { console.log('Received customEvent from the server:', data); // Handle the data received from the server as needed }); // Clean up the socket connection on component unmount return () => { socket.disconnect(); }; }) }, []) return( <> <Header/> <main className="bg-naturalWhite"> {data? <div className=" mt-4 px-2"> <p className="uppercase font-bold text-xl">{data.title}</p> <p className="font-light">Autor {data.author.name}</p> <span className="text-xs">Assunto</span> <p>{data.content}</p> <div className="h-1 w-full bg-blue-100"/> <CommentsList comments={data.comments} customer={customer}/> </div> :<p>Carregando</p>} <InputLarge placeholder={"Menssagem"} paperAirPlane onKeyPress={handleSendMessage} onChange={e => setMessage(e.target.value)} value={message} onClick={handleSendMessage} /> </main> <Footer /> </> ) }
"use client"; // Error components must be Client Components import { Alert, Button, Center, Flex, Text } from "@chakra-ui/react"; import { useEffect, useState } from "react"; import { BloatcareIcon } from "./components/Icons/Components/IconComponents"; import { motion } from "framer-motion"; export default function Error({ error, reset }) { const [showError, setShowError] = useState(false); useEffect(() => { // Log the error to an error reporting service console.error(error); }, [error]); return ( <motion.div initial={{ opacity: 1 }} transition={{ duration: 1 }} style={{ width: "100vw", height: "100vh", backgroundColor: "rgba(0, 0, 0, 1)", position: "fixed", top: 0, left: 0, zIndex: 9999, }} > <Center h="100%"> <Flex direction="column" align="center"> <BloatcareIcon w="14" h="14" fill="#107cf1" cursor="pointer" /> <Text fontSize="3xl" fontWeight="bold" color="white"> Something went wrong! </Text> <Button mt="4" onClick={ // Attempt to recover by trying to re-render the segment () => reset() } > Try to recover </Button> <Text mt="3" cursor="pointer" color="white"> Show the Error </Text> {showError && ( <Alert mt="4" status="error"> {error.message} </Alert> )} </Flex> </Center> </motion.div> ); }
''' This algo is a homemade implemantation of the SVM Tutorial: https://pythonprogramming.net/svm-in-python-machine-learning-tutorial/?completed=/svm-constraint-optimization-machine-learning-tutorial/ ''' import matplotlib.pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') class SVM: def __init__(self, visualization=True): self.vis = visualization self.colors = {1: 'r', -1:'b'} if self.vis: self.fig = plt.figure() self.ax = self.fig.add_subplot(1, 1, 1) # Train def fit(self, data): self.data = data opt_dict = {} transforms = [[1,1], [-1, 1], [-1, -1], [1, -1]] # Finding the values to work with for our range all_data = [] for yi in self.data: for featureset in self.data[yi]: for feature in featureset: all_data.append(feature) self.max_feature_value = max(all_data) self.min_feature_value = min(all_data) all_data = None step_sizes = [self.max_feature_value * 0.1, self.max_feature_value * 0.01, self.max_feature_value * 0.001] b_range_multiple = 5 b_multiple = 5 lastest_optimum = self.max_feature_value * 10 for step in step_sizes: w = np.array([latest_optimum, latest_optimum]) # This is possible because the domain is convex optimized = False while not optimized: for b in np.arange(-1 * (self.max_feature_value * b_range_multiple), self.max_feature_value * b_range_multiple, step * b_multiple): for transform in transforms: w_t = w * transform found_option = True for i in self.data: for xi in self.data[i]: yi = i if not yi * (np.dot(w_t, xi) + b) >= 1: foud_option = False if found_option: opt_dict[np.linalg.norm(w_t)] = [w_t, b] if w[0] < 0: optimized = True print('Optimized a step') else: w = w - step norms = sorted([n for n in opt_dict]) opt_choice = opt_dict[norms[0]] self.w = opt_choice[0] self.b = opt_choice[1] latest_optimum = opt_choice[0][0] + step * 2 def predict(self, features): classification = np.sigm(np.dot(np.array(features), self.w) + self.b) if classification != 0 and self.vis: self.ax.scatter(features[0], features[1], s=200, marker='*', c=self.colors[classification]) else: print('featureset', features, 'is on the decision boundary') return classification def visualize(self): [[self.ax.scatter(x[0],x[1],s=100,color=self.colors[i]) for x in data_dict[i]] for i in data_dict] data_dict = {-1:np.array([[1,7],[2,8],[3,8],]), 1:np.array([[5,1],[6,-1],[7,3],])}
import React from "react"; import ButtonComponent from "@mui/material/Button"; type props = { width?: string; label: string; headlight?: boolean; disabled?: boolean; onClick?: () => void; type?: 'button' | 'submit'; }; export const Button = ({ width, label, headlight,disabled, onClick,type }: props) => { return ( <ButtonComponent style={{ width: `${width}`, height: "40px", borderRadius: 11, backgroundColor: `${headlight ? "#24CA68" : "#404040"}`, marginTop: "20px", paddingTop: "10px", fontSize: "15px", fontWeight: "bolder", boxShadow: "none", }} type={type} variant="contained" onClick={onClick} disabled={disabled} > {label} </ButtonComponent> ); };
import { Slide, Heading, Appear, Text, Notes } from "spectacle"; import { Draggable } from "../components/Draggable"; export const MemoSlide: React.FC = () => { return ( <Slide> <Heading>React.memo</Heading> <Appear> <Text> If your component is pure, you can avoid rendering it by using React.memo </Text> </Appear> <Appear> <Text> A pure component is one that given the same props and state, always return the same element </Text> </Appear> <Appear> <Draggable /> <Appear> <Text>How can we improve?</Text> </Appear> </Appear> <Notes> Show the dev mode and show it the child is being rendered because of parent Change the code to use React.memo Show the dev tools again </Notes> </Slide> ); };
#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <linux/fb.h> #include <sys/mman.h> int main() { int fbfd = 0; struct fb_var_screeninfo vinfo; struct fb_fix_screeninfo finfo; long int screensize = 0; char *fbp = 0; int x = 0, y = 0; long int location = 0; // Open the file for reading and writing fbfd = open("/dev/fb0", O_RDWR); // fb0 if (!fbfd) { printf("Error: cannot open framebuffer device.\n"); exit(1); } printf("The framebuffer device was opened successfully.\n"); // Get fixed screen information if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) { printf("Error reading fixed information.\n"); exit(2); } // Get variable screen information if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) { printf("Error reading variable information.\n"); exit(3); } printf("%dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel ); // Figure out the size of the screen in bytes screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8; printf("screensize=%d\n", screensize); //if(screensize > 65536) // screensize = 65536; printf("screensize=%d\n", screensize); // Map the device to memory fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0); if ((int)fbp == -1) { printf("Error: failed to map framebuffer device to memory.\n"); exit(4); } printf("The framebuffer device was mapped to memory successfully.\n"); x = 100; y = 100; // Where we are going to put the pixel // Figure out where in memory to put the pixel //memset(fbp, 0, screensize); //munmap(fbp, screensize); //close(fbfd); //return 0; for ( y = 0; y < 100; y++ ) for ( x = 0; x < 100; x++ ) { location = (x+vinfo.xoffset) * (vinfo.bits_per_pixel/8) + (y+vinfo.yoffset) * finfo.line_length; if ( vinfo.bits_per_pixel == 32 ) { *(fbp + location) = 0; // Some blue *(fbp + location + 1) = 0xff; // A little green *(fbp + location + 2) = 0xff; // A lot of red *(fbp + location + 3) = 0xff; // No transparency } else { //assume 16bpp int b = 0xff; int g = 0xff; // A little green int r = 0xff; // A lot of red unsigned short int t = r<<11 | g << 5 | b; *((unsigned short int*)(fbp + location)) = t; } } munmap(fbp, screensize); close(fbfd); return 0; }
## GP-Bart #' @useDynLib spBART7 #' @importFrom Rcpp sourceCpp #' # Getting the BART wrapped function #' @export rbart <- function(x_train, y, x_test, n_tree = 2, n_mcmc = 2000, n_burn = 500, alpha = 0.95, beta = 2, dif_order = 2, # df_splines = 10, nIknots = 1, df = 3, sigquant = 0.9, kappa = 2, scale_bool = TRUE, # Hyperparam for tau_b and tau_b_0 nu = 2, delta = 1, a_delta = 0.0001, d_delta = 0.0001, df_tau_b = 3, prob_tau_b = 0.9, intercept_model = TRUE, stump = FALSE ) { # Verifying if x_train and x_test are matrices if(!is.data.frame(x_train) || !is.data.frame(x_test)){ stop("Insert valid data.frame for both data and xnew.") } # Creating the col original_p <- 1:ncol(x_train)-1 # Getting the valid dummy_x <- caret::dummyVars(~.,data = x_train) col_names <- attr(dummy_x$terms,"term.labels") dummy_x_train_m <- predict(object = dummy_x,newdata = x_train) dummy_x_test_m <- predict(object = dummy_x,newdata = x_test) recode_names <- recode_vars(x_train = x_train,dummy_obj = dummy_x) n_levels <- c(table(recode_names)-1) # It also counts the zero x_train_scale <- dummy_x_train_m x_test_scale <- dummy_x_test_m # Scaling x x_min <- apply(as.matrix(x_train_scale),2,min) x_max <- apply(as.matrix(x_train_scale),2,max) # Storing the original x_train_original <- x_train x_test_original <- x_test # Normalising all the columns for(i in 1:ncol(x_train)){ x_train_scale[,i] <- normalize_covariates_bart(y = x_train_scale[,i],a = x_min[i], b = x_max[i]) x_test_scale[,i] <- normalize_covariates_bart(y = x_test_scale[,i],a = x_min[i], b = x_max[i]) } # Scaling the y min_y <- min(y) max_y <- max(y) # Getting the min and max for each column min_x <- apply(x_train_scale,2,min) max_x <- apply(x_train_scale, 2, max) # Getting the internal knots # knots <- apply(x_train_scale, # 2, # function(x){quantile(x,seq(0,1,length.out = nIknots+2))[-c(1,nIknots+2)]}) knots <- apply(x_train_scale, 2, function(x){seq(min(x),max(x),length.out = nIknots)}) # Creating a array of basis functions (only for continuous variables) continuous_vars <- col_names[!(col_names %in% dummy_x$facVars)] B_train_arr <- array(data = NA, dim = c(nrow(x_train_scale), nrow(knots)+3, # +3 here because is a natural spline ncol(x_train_scale[,continuous_vars, drop = FALSE]))) B_test_arr <- array(data = NA, dim = c(nrow(x_test_scale), nrow(knots)+3, # +3 here because is a natural spline ncol(x_test_scale[,continuous_vars, drop = FALSE]))) # Setting new parameters for the spline ndx <- nIknots dx <- 1/ndx # New_knots new_knots <- matrix() # new_knots <- mapply(min_x,max_x, FUN = function(MIN,MAX){seq(from = MIN-3*dx, to = MAX+3*dx, by = dx)}) # MIN and MAX are 0 and 1 respectively, because of the scale new_knots <- matrix(mapply(min_x,max_x, FUN = function(MIN,MAX){seq(from = -3*dx, to = 1+3*dx, by = dx)}), ncol = length(continuous_vars)) # MIN and MAX are 0 and 1 respectively, because of the scale colnames(new_knots) <- continuous_vars # print(new_knots) # Creating the natural B-spline for each predictor for(i in 1:length(continuous_vars)){ # B_train_obj <- splines::bs(x = x_train_scale[,continuous_vars[i], drop = FALSE],knots = knots[,continuous_vars[i]], # intercept = FALSE, # Boundary.knots = c((min_x[i]),max_x[i])) B_train_obj <- splines::spline.des(x = x_train_scale[,continuous_vars[i], drop = FALSE], knots = new_knots[,continuous_vars[i]], ord = 4, derivs = 0*x_train_scale[,continuous_vars[i], drop = FALSE],outer.ok = FALSE)$design B_train_arr[,,i] <- as.matrix(B_train_obj) # B_test_arr[,,i] <- as.matrix(predict(B_train_obj,newx = x_test_scale[,continuous_vars[i], drop = FALSE])) B_test_arr[,,i] <- splines::spline.des(x = x_test_scale[,continuous_vars[i], drop = FALSE], knots = new_knots[,continuous_vars[i]], ord = 4, derivs = 0*x_test_scale[,continuous_vars[i], drop = FALSE],outer.ok = TRUE)$design } # Plotting the basis # plot(x_train_scale[,1], B_train_arr[,1,1], ylim = range(B_train_obj), type = 'n', # ylab = "B") # for(j in 1:ncol(B_train_obj)) { # points(x_train_scale[,1], B_train_obj[,j], col = j) # } # R-th difference order matrix if(dif_order!=0){ D <- D_gen(p = ncol(B_train_arr[,,1]),n_dif = dif_order) } else { D <- diag(nrow = ncol(B_train_arr[,,1])) } # Scaling "y" if(scale_bool){ y_scale <- normalize_bart(y = y,a = min_y,b = max_y) tau_b_0 <- (4*n_tree*(kappa^2)) tau_b <- tau_mu <- (4*n_tree*(kappa^2)) # tau_b <- tau_mu <- 0.1 } else { y_scale <- y tau_b_0 <- tau_b <- tau_mu <- (4*n_tree*(kappa^2))/((max_y-min_y)^2) } # Getting the naive sigma value nsigma <- naive_sigma(x = x_train_scale,y = y_scale) # Calculating tau hyperparam a_tau <- df/2 # Calculating lambda qchi <- stats::qchisq(p = 1-sigquant,df = df,lower.tail = 1,ncp = 0) lambda <- (nsigma*nsigma*qchi)/df d_tau <- (lambda*df)/2 # Call the bart function tau_init <- nsigma^(-2) mu_init <- mean(y_scale) # tau_init <- 0.01 # Creating the vector that stores all trees all_tree_post <- vector("list",length = round(n_mcmc-n_burn)) # Another way to define the prior for \tau_b a_tau_b <- 0.5*df_tau_b # Getting the \tau_b # naive_tau_b <- optim(par = rep(1, 2), fn = nll, dat=y_scale, # x = x_train_scale, # B = B_train_arr, # P = crossprod(D),n_tree = n_tree, # tau_b_0_ = tau_b_0, # method = "L-BFGS-B", # hessian = TRUE, # lower = rep(0.0001, 2))$par[2] # # d_tau_b <- optim(par = 0.001,d_tau_b_rate,method = "L-BFGS-B", # lower = 0.001,df_tau_b = df_tau_b, # prob_tau_b = prob_tau_b, # naive_tau_b = naive_tau_b)$par # Getting the number of basis d_pred <- dim(B_train_arr)[3] a_tau_b <- d_tau_b <- 0.01 # Generating the BART obj bart_obj <- sbart(x_train_scale, y_scale, x_test_scale, B_train = B_train_arr, B_test = B_test_arr, n_tree, n_mcmc, n_burn, tau_init, mu_init, tau_mu, tau_b, tau_b_0, # Same initial value as tau_b alpha, beta, a_tau,d_tau, nu,delta, a_delta,d_delta, # Hypeparameters from delta a_tau_b,d_tau_b, original_p, # Getting the p available variables n_levels, # Getting the sample levels intercept_model = intercept_model, stump) if(scale_bool){ # Tidying up the posterior elements y_train_post <- unnormalize_bart(z = bart_obj[[1]],a = min_y,b = max_y) y_test_post <- unnormalize_bart(z = bart_obj[[2]],a = min_y,b = max_y) for(i in 1:round(n_mcmc-n_burn)){ all_tree_post[[i]] <- unnormalize_bart(z = bart_obj[[4]][,,i],a = min_y,b = max_y) } tau_post <- bart_obj[[3]]/((max_y-min_y)^2) tau_b_post <- bart_obj[[5]]/((max_y-min_y)^2) tau_b_post_intercept <- bart_obj[[6]]/((max_y-min_y)^2) } else { y_train_post <- bart_obj[[1]] y_test_post <- bart_obj[[2]] tau_post <- bart_obj[[3]] for(i in 1:round(n_mcmc-n_burn)){ all_tree_post[[i]] <- bart_obj[[4]][,,i] } tau_b_post <- bart_obj[[5]] tau_b_post_intercept <- bart_obj[[6]] } tree_list <- as.data.frame(bart_obj[[8]]) colnames(tree_list) <- c("tree","mcmc_iter","n_nodes","n_terminal","depth",paste0("x.",1:ncol(x_train))) # Return the list with all objects and parameters return(list(y_hat = y_train_post, y_hat_test = y_test_post, tau_post = tau_post, tau_b_post = tau_b_post, tau_b_post_intercept = tau_b_post_intercept, all_tree_post = all_tree_post, prior = list(n_tree = n_tree, alpha = alpha, beta = beta, tau_mu = tau_mu, a_tau = a_tau, d_tau = d_tau), mcmc = list(n_mcmc = n_mcmc, n_burn = n_burn), data = list(x_train = x_train, y = y, x_test = x_test, grow_accept = bart_obj[[7]], tree_list = tree_list))) } #
This file will contain links for additional materials that I found interesting while doing FSDL ### Lab 00: - [What is Serverless? (Blog Post)](https://sst.dev/chapters/what-is-serverless.html) ### Lab 01: - [Probability - Math for Machine Learning (Video)](https://www.youtube.com/watch?v=LBemXHm_Ops&ab_channel=Weights%26Biases) - [Making Deep Learning Go Brrrr From First Principles (Blog Post)](https://horace.io/brrr_intro.html) ### Lab 02b: - [A visual proof that neural nets can compute any function (Blog Post)](http://neuralnetworksanddeeplearning.com/chap4.html) - [Multiplication Made Convoluted, Part I: Math (Blog Post)](https://charlesfrye.github.io/math/2019/02/20/multiplication-convoluted-part-one.html) - [Multiplication Made Convoluted, Part II: Python (Blog Post)](https://charlesfrye.github.io/programming/2019/02/22/multiplication-convoluted-part-two.html) - [Conv Nets: A Modular Perspective 1/3 (Blog Post)](https://colah.github.io/posts/2014-07-Conv-Nets-Modular/) - [Understanding Convolutions 2/3 (Blog Post)](https://colah.github.io/posts/2014-07-Understanding-Convolutions/) - [Groups & Group Convolutions 3/3 (Blog Post)](https://colah.github.io/posts/2014-12-Groups-Convolution/) - [The Building Blocks of Interpretability (Blog Post)](https://distill.pub/2018/building-blocks/) - [Thread: Circuits (Blog Post Series)](https://distill.pub/2020/circuits/) - [Pruning Tutorial](https://pytorch.org/tutorials/intermediate/pruning_tutorial.html) - [Reduce the costs of ML workflows with preemptible VMs and GPUs (Blog Post)](https://cloud.google.com/blog/products/ai-machine-learning/reduce-the-costs-of-ml-workflows-with-preemptible-vms-and-gpus?hl=en) ### Lab 03: - [Transformer Circuits Thread (Blog Post Series)](https://transformer-circuits.pub/) - [Neural Networks, Types, and Functional Programming (Blog Post)](https://colah.github.io/posts/2015-09-NN-Types-FP/) - [Understanding LSTM Networks (Blog Post)](https://colah.github.io/posts/2015-08-Understanding-LSTMs/) - [Autoregressive models (Blog Post)](https://deepgenerativemodels.github.io/notes/autoregressive/) - [Transformer Circuit Exercises (Blog Post)](https://transformer-circuits.pub/2021/exercises/index.html) - [interpreting GPT: the logit lens (Blog Post)](https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens) - [A Gentle Introduction to the Bag-of-Words Model (Blog Post)](https://machinelearningmastery.com/gentle-introduction-bag-words-model/) - [The Annotated Transformer (Article)](http://nlp.seas.harvard.edu/annotated-transformer/) - [The Illustrated Transformer (Blog Post and Video)](https://jalammar.github.io/illustrated-transformer/) - [Transformers from Scratch (Blog Post)](https://e2eml.school/transformers.html) - [Transformers for software engineers (Blog Post)](https://blog.nelhage.com/post/transformers-for-software-engineers/) ### Lab 05: - [Making Deep Learning Go Brrrr From First Principles (Blog Post)](https://horace.io/brrr_intro.html) - [PyTorch internals (Blog Post)](http://blog.ezyang.com/2019/05/pytorch-internals/)
using FuryRent.Core.Contracts; using FuryRent.Core.Services; using FuryRent.Infrastructure.Data; using FuryRent.Infrastructure.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtension { //Adds services to the collection public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddScoped<ICarService, CarService>(); services.AddScoped<IVipService, VipService>(); services.AddScoped<IRentService, RentService>(); services.AddScoped<IPayService, PayService>(); return services; } //Adds FuryRentDbContext public static IServiceCollection AddApplicationDbContext(this IServiceCollection services, IConfiguration config) { var connectionString = config.GetConnectionString("DefaultConnection"); services.AddDbContext<FuryRentDbContext>(options => options.UseSqlServer(connectionString)); services.AddDatabaseDeveloperPageExceptionFilter(); return services; } //Adds extended IdentityUser public static IServiceCollection AddApplicationIdentity(this IServiceCollection services, IConfiguration config) { services.AddDefaultIdentity<ApplicationUser>(options => { options.SignIn.RequireConfirmedAccount = false; options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequiredLength = 7; options.Password.RequireNonAlphanumeric = false; }) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<FuryRentDbContext>(); return services; } } }
from oemof.thermal_building_model.tabula.tabula_reader import Building from oemof.thermal_building_model.m_5RC import M5RC from oemof.solph import views import oemof.solph as solph def test_building_optimization(): # create solver solver = "cbc" # 'glpk', 'gurobi',.... solver_verbose = False # show/hide solver output number_of_time_steps = 100 building_example = Building( tabula_building_code="DE.N.SFH.05.Gen.ReEx.001.002", class_building="average", number_of_time_steps=number_of_time_steps, ) building_example.calculate_all_parameters() internal_gains = [] t_outside = [] solar_gains = [] for _ in range(number_of_time_steps): internal_gains.append(100) t_outside.append(10) solar_gains.append(100) date_time_index = solph.create_time_index( 2012, number=number_of_time_steps) es = solph.EnergySystem(timeindex=date_time_index, infer_last_interval=False) # create electricity, heat and cooling flow b_heat = solph.buses.Bus(label="b_heat") es.add(b_heat) b_cool = solph.buses.Bus(label="b_cool") es.add(b_cool) b_elect = solph.buses.Bus(label="electricity_from_grid") es.add(b_elect) # add electricity from grid es.add( solph.components.Source( label="elect_from_grid", outputs={b_elect: solph.flows.Flow(variable_costs=30)}, ) ) # add heating and cooling components es.add( solph.components.Transformer( label="ElectricalHeater", inputs={b_elect: solph.flows.Flow()}, outputs={b_heat: solph.flows.Flow()}, conversion_factors={b_elect: 1}, ) ) es.add( solph.components.Transformer( label="ElectricalCooler", inputs={b_cool: solph.flows.Flow(), b_elect: solph.flows.Flow()}, outputs={}, conversion_factors={b_cool: 1, b_elect: 1}, ) ) # add building es.add( M5RC( label="GenericBuilding", inputs={b_heat: solph.flows.Flow(variable_costs=0)}, outputs={b_cool: solph.flows.Flow(variable_costs=0)}, solar_gains=solar_gains, t_outside=t_outside, internal_gains=internal_gains, t_set_heating=20, t_set_cooling=30, building_config=building_example.building_config, t_inital=26, ) ) model = solph.Model(es) model.solve(solver=solver, solve_kwargs={"tee": solver_verbose}) es.results["main"] = solph.processing.results(model) results = es.results["main"] assert ( views.node(results, "GenericBuilding")["sequences"][ (("GenericBuilding", "None"), "t_air") ][0] == 26 ) assert ( views.node(results, "GenericBuilding")["sequences"][ (("GenericBuilding", "None"), "t_air") ][5] == 22.367105 ) assert ( views.node(results, "GenericBuilding")["sequences"][ (("GenericBuilding", "None"), "t_air") ][9] == 20.403484 )
<?php namespace App\Http\Controllers; use App\Models\TipoDocumento; use App\Http\Requests\StoreTipoDocumentoRequest; use App\Http\Requests\UpdateTipoDocumentoRequest; use Inertia\Inertia; use Illuminate\Http\Request; class TipoDocumentoController extends Controller { /** * Display a listing of the resource. */ public function query(Request $request){ try{ $response = TipoDocumento::all(); return response()->json([ "isRequest"=> true, "success" => true, "messageError" => false, "message" => "Session cerrada conrrectamente..", "data" => $response ]); }catch(\Exception $e){ $message = $e->getMessage(); $code = $e->getCode(); return response()->json([ "isRequest"=> true, "success" => false, "messageError" => true, "message" => $message." Code: ".$code, "data" => [] ]); } } public function index() { $tipoDocumento = TipoDocumento::all(); return Inertia::render("TipoDocumento/Index", ['tipodocumentos'=> $tipoDocumento]); } /** * Show the form for creating a new resource. */ public function create() { return Inertia::render("TipoDocumento/Create"); } /** * Store a newly created resource in storage. */ public function store(StoreTipoDocumentoRequest $request) { try{ // return $request->all(); $tipoDocumento = TipoDocumento::create($request->all()); return response()->json([ "isRequest"=> true, "success" => $tipoDocumento != null, "messageError" => $tipoDocumento != null, "message" => $tipoDocumento != null ? "Registro completo" : "Error!!!", "data" => $tipoDocumento ]); }catch(\Exception $e){ $message = $e->getMessage(); $code = $e->getCode(); return response()->json([ "isRequest"=> true, "success" => false, "messageError" => true, "message" => $message." Code: ".$code, "data" => [] ]); } } /** * Display the specified resource. */ public function show(TipoDocumento $tipoDocumento) { // } /** * Show the form for editing the specified resource. */ public function edit(TipoDocumento $tipodocumento) { return Inertia::render("TipoDocumento/Edit", ['tipodocumento'=> $tipodocumento]); } /** * Update the specified resource in storage. */ public function update(UpdateTipoDocumentoRequest $request, TipoDocumento $tipodocumento) { try{ $response = $tipodocumento->update($request->all()); return response()->json([ "isRequest"=> true, "success" => $response, "messageError" => !$response, "message" => $response ? "Datos actualizados correctamente" : "Datos no actualizados", "data" => $response ]); }catch(\Exception $e){ $message = $e->getMessage(); $code = $e->getCode(); return response()->json([ "isRequest"=> true, "success" => false, "messageError" => true, "message" => $message." Code: ".$code, "data" => [] ]); } } /** * Remove the specified resource from storage. */ public function destroy(TipoDocumento $tipodocumento) { try{ $response = $tipodocumento->delete(); return response()->json([ "isRequest"=> true, "success" => $response, "messageError" => !$response, "message" => $response ? "Datos eliminados correctamente" : "Los datos no pudieron ser eliminados", "data" => $response ]); }catch(\Exception $e){ $message = $e->getMessage(); $code = $e->getCode(); return response()->json([ "isRequest"=> true, "success" => false, "messageError" => true, "message" => $message." Code: ".$code, "data" => [] ]); } } }
# Facades [[toc]] ## 简介 `facades` 为应用的核心功能提供一个「静态」接口,能够提供更加灵活、更加优雅、易于测试的语法。 Goravel 所有的 `facades` 都定义在 `github.com/goravel/framework/facades` 下。我们可以很轻松的使用 `facades`: ```go import "github.com/goravel/framework/facades" facades.Route().Run(facades.Config().GetString("app.host")) ``` ## facades 工作原理 `facades` 一般会在各模块 `ServerProvider` 的 `Register` 或 `Boot` 阶段进行实例化。 ```go func (config *ServiceProvider) Register() { app := Application{} facades.Config = app.Init() } ``` 如果该 `facades` 使用了其他 `facades`,那么就在 `ServerProvider` 的 `Boot` 阶段进行实例化: ```go func (database *ServiceProvider) Boot() { app := Application{} facades.DB = app.Init() } ``` ## facade 类参考 | Facade | 文档 | | -------- | -------------------------------------------------- | | App | [容器](../architecutre-concepts/service-container.md) | | Artisan | [命令行工具](../digging-deeper/artisan-console.md) | | Auth | [用户认证](../security/authentication.md) | | Cache | [缓存系统](../digging-deeper/cache.md) | | Config | [配置信息](../getting-started/configuration.md) | | Crypt | [加密解密](../security/encryption.md) | | Event | [事件系统](../digging-deeper/event.md) | | Gate | [用户授权](../security/authorization.md) | | Grpc | [Grpc](../the-basics/grpc.md) | | Hash | [哈希](../security/hashing.md) | | Log | [日志](../the-basics/logging.md) | | Mail | [邮件](../digging-deeper/mail.md) | | Orm | [ORM](../orm/getting-started.md) | | Queue | [队列](../digging-deeper/queues.md) | | RateLimiter | [限流器](../the-basics/routing.md) | | Route | [路由](../the-basics/routing.md) | | Seeder | [数据填充](../orm/seeding.md) | | Schedule | [任务调度](../digging-deeper/task-scheduling.md) | | Storage | [文件系统](../digging-deeper/filesystem.md) | | Testing | [测试](../testing/getting-started.md) | | Validation | [表单验证](../the-basics/validation.md) | <CommentService/>