text
stringlengths
184
4.48M
package main import ( "encoding/json" "net/http" "github.com/rs/cors" ) type Message struct { Text string `json:"text"` } func main() { // Create a new CORS middleware corsMiddleware := cors.New(cors.Options{ AllowedOrigins: []string{"http://localhost:3000"}, }) // Message Endpoint http.HandleFunc("/api/message", func(w http.ResponseWriter, r *http.Request) { handleMessage(w, r) }) // Other Endpoint // Wrap your handler with the CORS middleware handler := corsMiddleware.Handler(http.DefaultServeMux) // Start the server on port 8080 http.ListenAndServe(":8080", handler) } func handleMessage(w http.ResponseWriter, r *http.Request) { // create a simple message message := Message{Text: "Hello from Golang backend!"} // convert the message to JSON response, err := json.Marshal(message) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } // Set the Content-Type header and write the response w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(response) }
/* * Tupaia * Copyright (c) 2017 - 2023 Beyond Essential Systems Pty Ltd */ import React, { useState } from 'react'; import { Button, ListItemProps, CircularProgress, List, ListItem } from '@material-ui/core'; import styled from 'styled-components'; import { FlexColumn } from '@tupaia/ui-components'; import { Link, useParams } from 'react-router-dom'; import { useEntitySearch } from '../../api/queries'; const Container = styled.div` padding: 1rem; `; const ScrollBody = styled(List)` overflow: auto; max-height: 20rem; `; const ResultLink = styled(ListItem).attrs({ component: Link, })<ListItemProps>` display: block; text-transform: none; padding: 0.8rem; font-size: 0.875rem; `; const MessageBody = styled(FlexColumn)` padding: 1rem; min-height: 7rem; align-items: center; justify-content: center; .MuiCircularProgress-root { margin-bottom: 1.5rem; } `; const Loader = () => { return ( <MessageBody> <CircularProgress /> <div>Loading results...</div> </MessageBody> ); }; const LoadMoreButton = styled(Button).attrs({ variant: 'outlined', color: 'default', })` display: block; width: 100%; padding: 0.6rem; margin-top: 0.6rem; font-size: 0.8125rem; text-transform: none; `; const NoDataMessage = ({ searchValue }: { searchValue: string }) => { return <MessageBody>No results found for search "{searchValue}"</MessageBody>; }; interface SearchResultsProps { searchValue: string; onClose: () => void; } const PAGE_LENGTHS = { INITIAL: 5, LOAD_MORE: 5, MAX: 20, }; export const SearchResults = ({ searchValue, onClose }: SearchResultsProps) => { const { projectCode } = useParams(); const [prevSearchValue, setPrevSearchValue] = useState(searchValue); const [pageSize, setPageSize] = useState(PAGE_LENGTHS.INITIAL); const { data: searchResults = [], isLoading } = useEntitySearch( projectCode, searchValue, pageSize, ); if (searchValue !== prevSearchValue) { setPrevSearchValue(searchValue); setPageSize(PAGE_LENGTHS.INITIAL); } if (isLoading) { return <Loader />; } if (searchResults.length === 0) { return <NoDataMessage searchValue={searchValue} />; } const onLoadMore = () => { setPageSize(pageSize + PAGE_LENGTHS.LOAD_MORE); }; return ( <Container> <ScrollBody> {searchResults.map(({ code, qualifiedName }) => { return ( <ResultLink button key={code} onClick={onClose} to={{ ...location, pathname: `/${projectCode}/${code}` }} > {qualifiedName} </ResultLink> ); })} </ScrollBody> {pageSize < PAGE_LENGTHS.MAX && ( <LoadMoreButton onClick={onLoadMore}>Load more results</LoadMoreButton> )} </Container> ); };
<template> <div> <div class="rightBox"> <h4 class="title">注册</h4> <el-form :model="addForm" :rules="addFromRules" ref="addFormRef" label-width="85px" > <el-form-item label="用户名:" prop="username"> <el-input v-model="addForm.username" placeholder="请输入用户名" ></el-input> </el-form-item> <el-form-item label="注册密码:" prop="password"> <el-input type="password" v-model="addForm.password" show-password placeholder="请输入密码" ></el-input> </el-form-item> <el-form-item label="确认密码:" prop="confirmPassword"> <el-input type="password" v-model="addForm.confirmPassword" show-password placeholder="请再次输入密码" ></el-input> </el-form-item> <el-form-item label="手机号:" prop="phone"> <el-input v-model="addForm.phone" placeholder="请输入手机号" ></el-input> </el-form-item> <el-form-item label="手机验证:"> <el-input class="phoneCode" placeholder="请输入手机验证码"></el-input> <el-button class="sendPhoneCode" @click="sendsms" :disabled="disabled" >{{ sendPhoneCode }}</el-button > </el-form-item> <el-form-item label="任教学校:" prop="school"> <el-input v-model="addForm.school" placeholder="请输入任教学校" ></el-input> </el-form-item> <el-form-item> <el-button class="registerBtn" @click="goRegister" >立即注册</el-button > <p> 已经注册账号?<router-link to="/index/loginAndRegistration/login" >立即登录</router-link > </p> </el-form-item> </el-form> </div> </div> </template> <script> export default { name: 'Register', data() { var checkPhone = (rule, value, cb) => { const regPhone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ if (regPhone.test(value.trim())) { return cb() } cb(new Error('请输入合法的手机号')) } var checkPassword = (rule, value, cb) => { const regPassword = /^[a-zA-Z]\w{5,17}$/ if (regPassword.test(value.trim())) { return cb() } cb(new Error('字母开头,长度6~18之间,只包含字母、数字和下划线')) } var equalToPassword = (rule, value, cb) => { if (this.addForm.password == value) { return cb() } cb(new Error('两次密码输入不一致')) } return { addForm: { username: '', phone: '', password: '', confirmPassword: '', school: '', }, addFromRules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 2, max: 10, message: '用户名的长度在2~10个字符之间', trigger: 'blur', }, ], phone: [ { required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur', }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { validator: checkPassword, trigger: 'blur', }, ], confirmPassword: [ { required: true, message: '请输入密码', trigger: 'blur' }, { validator: equalToPassword, trigger: 'blur', }, ], school: [{ required: true, message: '请输入学校名', trigger: 'blur' }], }, sendPhoneCode: '发送验证码', disabled: false, } }, methods: { sendsms() { this.$refs.addFormRef.validateField('phone', (phoneError) => { if (!phoneError) { this.disabled = true this.sendPhoneCode = 60 let timer = setInterval(() => { if (this.sendPhoneCode == 1) { this.sendPhoneCode = '发送验证码' clearInterval(timer) timer = null this.disabled = false } else { this.sendPhoneCode-- } }, 1000) } else { return } }) }, goRegister() { this.$refs.addFormRef.validate(async (valid) => { if (!valid) return this.$message.error('用户信息格式不正确!') const { data: res } = await this.$http.post('/user/addUser', { username: this.addForm.username, phone: this.addForm.phone, password: this.addForm.password, school: this.addForm.school, }) if (res.status !== 201 && res.status !== 412) { return this.$message.error('添加用户失败!') } else if (res.status == 412) { return this.$message.warning(res.message) } else if (res.status == 201) { this.$message.success(res.message) } }) }, }, } </script> <style lang="less" scoped> .rightBox { width: 422px; height: 522px; border: 1px solid #e8e8e8d2; border-radius: 3px; .title { height: 55px; font-size: 20px; font-weight: 400; line-height: 55px; background-color: #f6f7f9; color: #fe7300; padding: 0 20px; } } .el-form { width: 380px; margin: 15px auto 0; .sendPhoneCode { position: absolute; right: 0; top: 0; color: #fff; background-color: #ff7d27; border: 1px solid #ff7d27; border-radius: 1px; width: 112px; } .sendPhoneCode:hover, .registerBtn:hover { background: #f60; border: 1px solid #f60; } .registerBtn { width: 100%; background-color: #ff7d27; border: 1px solid #ff7d27; color: #fff; border-radius: 1px; } p { text-align: center; margin-top: 5px; height: 20px; line-height: 20px; color: #606266; a { color: #028ec2; padding-left: 4px; cursor: pointer; } } } </style>
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:teamproject/others/constants.dart'; class MembersScreen extends StatefulWidget { const MembersScreen({Key? key}) : super(key: key); @override _MembersScreenState createState() => _MembersScreenState(); } class _MembersScreenState extends State<MembersScreen> { // late List<Map<String,String>> _list = []; final scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { double screenWidth = MediaQuery.of(context).size.width; double screenHeight = MediaQuery.of(context).size.height; return Scaffold( key: scaffoldKey, backgroundColor: Theme.of(context).canvasColor, appBar: AppBar( backgroundColor: Colors.purple.shade300, title: Text( 'Members', style: TextStyle( fontFamily: 'Outfit', color: Colors.white, fontSize: 22, ), ), actions: [], centerTitle: true, elevation: 2, ), body: SafeArea( top: true, child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance .collection(USERS_COLLECTION) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.hasError) { return const Center( child: CircularProgressIndicator(), ); } return ListView.builder( itemCount: snapshot.data!.docs.length, padding: EdgeInsets.zero, scrollDirection: Axis.vertical, itemBuilder: (context, index) { return Padding( padding: EdgeInsetsDirectional.fromSTEB(5, 5, 5, 5), child: ListTile( leading: CircleAvatar( backgroundImage: NetworkImage(snapshot.data!.docs[index]['picurl']), ), title: Text( snapshot.data!.docs[index]['name'], style: Theme.of(context).textTheme.titleLarge, ), subtitle: Text( snapshot.data!.docs[index]['Email'], style: TextStyle( fontFamily: 'Readex Pro', color: Colors.black, ), ), tileColor: Color(0x92A400FF), dense: false, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), ); }, ); }), ), ); } }
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #ifdef PAIR_CLASS PairStyle(multi/lucy,PairMultiLucy) #else #ifndef LMP_PAIR_MULTI_LUCY_H #define LMP_PAIR_MULTI_LUCY_H #include "pair.h" namespace LAMMPS_NS { class PairMultiLucy : public Pair { public: PairMultiLucy(class LAMMPS *); virtual ~PairMultiLucy(); virtual void compute(int, int); void settings(int, char **); void coeff(int, char **); double init_one(int, int); void write_restart(FILE *); void read_restart(FILE *); void write_restart_settings(FILE *); void read_restart_settings(FILE *); int pack_forward_comm(int, int *, double *, int, int *); void unpack_forward_comm(int, int, double *); int pack_reverse_comm(int, int, double *); void unpack_reverse_comm(int, int *, double *); void computeLocalDensity(); double rho_0; protected: enum{LOOKUP,LINEAR}; int nmax; int tabstyle,tablength; struct Table { int ninput,rflag,fpflag,match; double rlo,rhi,fplo,fphi,cut; double *rfile,*efile,*ffile; double *e2file,*f2file; double innersq,delta,invdelta,deltasq6; double *rsq,*drsq,*e,*de,*f,*df,*e2,*f2; }; int ntables; Table *tables; int **tabindex; void allocate(); void read_table(Table *, char *, char *); void param_extract(Table *, char *); void bcast_table(Table *); void spline_table(Table *); void compute_table(Table *); void null_table(Table *); void free_table(Table *); void spline(double *, double *, int, double, double, double *); double splint(double *, double *, double *, int, double); }; } #endif #endif /* ERROR/WARNING messages: E: Pair multi/lucy command requires atom_style with density (e.g. dpd, meso) Self-explanatory E: Density < table inner cutoff The local density inner is smaller than the inner cutoff E: Density > table inner cutoff The local density inner is greater than the inner cutoff E: Only LOOKUP and LINEAR table styles have been implemented for pair multi/lucy Self-explanatory E: Illegal ... command Self-explanatory. Check the input script syntax and compare to the documentation for the command. You can use -echo screen as a command-line option when running LAMMPS to see the offending line. E: Illegal number of pair table entries There must be at least 2 table entries. E: Illegal pair_coeff command All pair coefficients must be set in the data file or by the pair_coeff command before running a simulation. E: Invalid pair table length Length of read-in pair table is invalid E: All pair coeffs are not set All pair coefficients must be set in the data file or by the pair_coeff command before running a simulation. E: Cannot open file %s The specified file cannot be opened. Check that the path and name are correct. E: Did not find keyword in table file Keyword used in pair_coeff command was not found in table file. E: Invalid keyword in pair table parameters Keyword used in list of table parameters is not recognized. E: Pair table parameters did not set N List of pair table parameters must include N setting. E: Pair table cutoffs must all be equal to use with KSpace When using pair style table with a long-range KSpace solver, the cutoffs for all atom type pairs must all be the same, since the long-range solver starts at that cutoff. */
//useState,useEffect,useContext,useReducer,useCallback,useMemo,useRef import { useState } from "react"; function App() { // let count =0; // console.log(useState(0)); // const [count,setCounter] = useState(0); // second way const [state, setState] = useState({ count: 0, isClickButton: false }); const [isClickButton, setIsClickButton] = useState(false); const ClickButton = () => { // setIsClickButton(true); // second way setState({ ...state, isClickButton: true }); } // const increment = () => { // setCounter(count+1); // setTimeout(()=>{console.log(count)}); // // if you need to increase by 3 do in follow way count+=1 version in js // setCounter(count => count+1); // setCounter(count => count+1); // } // second way const increment = () => { setState({ ...state, count: state.count + 1 }); setTimeout(() => { console.log(state.count) }); } return ( <div className="App"> <div style={{ fontSize: "26px", fontWeight: "bold", color: "red" }}>{state.count}</div> <button onClick={increment}>Increment</button> <button onClick={ClickButton}>Click This</button> </div> ); } export default App;
#ifndef ALLUVION_DG_KD_TREE_HPP #define ALLUVION_DG_KD_TREE_HPP #include <Eigen/Dense> #include <algorithm> #include <array> #include <functional> #include <iostream> #include <list> #include <numeric> #include <queue> #include <stack> #include <vector> #include "alluvion/dg/bounding_sphere.hpp" namespace alluvion { namespace dg { template <typename HullType, typename TF> class KDTree { public: using TraversalPredicate = std::function<bool(unsigned int node_index, unsigned int depth)>; using TraversalCallback = std::function<void(unsigned int node_index, unsigned int depth)>; using TraversalPriorityLess = std::function<bool(std::array<int, 2> const& nodes)>; struct Node { Node(unsigned int b_, unsigned int n_) : children({{-1, -1}}), begin(b_), n(n_) {} Node() = default; bool isLeaf() const { return children[0] < 0 && children[1] < 0; } // Index of child nodes in nodes array. // -1 if child does not exist. std::array<int, 2> children; // Index according entries in entity list. unsigned int begin; // Number of owned entries. unsigned int n; }; struct QueueItem { unsigned int n, d; }; using TraversalQueue = std::queue<QueueItem>; KDTree(std::size_t n) : m_lst(n) {} virtual ~KDTree() {} Node const& node(unsigned int i) const { return m_nodes[i]; } HullType const& hull(unsigned int i) const { return m_hulls[i]; } unsigned int entity(unsigned int i) const { return m_lst[i]; } void construct(); void update(); void traverseDepthFirst(TraversalPredicate pred, TraversalCallback cb, TraversalPriorityLess const& pless = nullptr) const; void traverseBreadthFirst(TraversalPredicate const& pred, TraversalCallback const& cb, unsigned int start_node = 0, TraversalPriorityLess const& pless = nullptr, TraversalQueue& pending = TraversalQueue()) const; protected: void construct(unsigned int node, AlignedBox3r<TF> const& box, unsigned int b, unsigned int n); void traverseDepthFirst(unsigned int node, unsigned int depth, TraversalPredicate pred, TraversalCallback cb, TraversalPriorityLess const& pless) const; void traverseBreadthFirst(TraversalQueue& pending, TraversalPredicate const& pred, TraversalCallback const& cb, TraversalPriorityLess const& pless = nullptr) const; unsigned int addNode(unsigned int b, unsigned int n); virtual Vector3r<TF> const& entityPosition(unsigned int i) const = 0; virtual void computeHull(unsigned int b, unsigned int n, HullType& hull) const = 0; protected: std::vector<unsigned int> m_lst; std::vector<Node> m_nodes; std::vector<HullType> m_hulls; }; template <typename HullType, typename TF> void KDTree<HullType, TF>::construct() { m_nodes.clear(); m_hulls.clear(); if (m_lst.empty()) return; std::iota(m_lst.begin(), m_lst.end(), 0); // Determine bounding box of considered domain. auto box = AlignedBox3r<TF>{}; for (auto i = 0u; i < m_lst.size(); ++i) box.extend(entityPosition(i)); auto ni = addNode(0, static_cast<unsigned int>(m_lst.size())); construct(ni, box, 0, static_cast<unsigned int>(m_lst.size())); } template <typename HullType, typename TF> void KDTree<HullType, TF>::construct(unsigned int node, AlignedBox3r<TF> const& box, unsigned int b, unsigned int n) { // If only one element is left end recursion. // if (n == 1) return; if (n < 10) return; // Determine longest side of bounding box. auto max_dir = 0; auto d = box.diagonal().eval(); if (d(1) >= d(0) && d(1) >= d(2)) max_dir = 1; else if (d(2) >= d(0) && d(2) >= d(1)) max_dir = 2; // Sort range according to center of the longest side. std::sort(m_lst.begin() + b, m_lst.begin() + b + n, [&](unsigned int a, unsigned int b) { return entityPosition(a)(max_dir) < entityPosition(b)(max_dir); }); auto hal = n / 2; auto n0 = addNode(b, hal); auto n1 = addNode(b + hal, n - hal); m_nodes[node].children[0] = n0; m_nodes[node].children[1] = n1; auto c = 0.5 * (entityPosition(m_lst[b + hal - 1])(max_dir) + entityPosition(m_lst[b + hal])(max_dir)); auto l_box = box; l_box.max()(max_dir) = c; auto r_box = box; r_box.min()(max_dir) = c; construct(m_nodes[node].children[0], l_box, b, hal); construct(m_nodes[node].children[1], r_box, b + hal, n - hal); } template <typename HullType, typename TF> void KDTree<HullType, TF>::traverseDepthFirst( TraversalPredicate pred, TraversalCallback cb, TraversalPriorityLess const& pless) const { if (m_nodes.empty()) return; if (pred(0, 0)) traverseDepthFirst(0, 0, pred, cb, pless); } template <typename HullType, typename TF> void KDTree<HullType, TF>::traverseDepthFirst( unsigned int node_index, unsigned int depth, TraversalPredicate pred, TraversalCallback cb, TraversalPriorityLess const& pless) const { // auto pending = std::stack<QueueItem>{}; // pending.push({node_index, depth}); // while (!pending.empty()) //{ // auto n = pending.top().n; // auto d = pending.top().d; // auto const& node = m_nodes[n]; // pending.pop(); // cb(n, d); // auto is_pred = pred(n, d); // if (!node.is_leaf() && is_pred) // { // if (pless && !pless(node.children)) // { // pending.push({ static_cast<unsigned int>(node.children[1]), d + // 1 }); pending.push({ static_cast<unsigned // int>(node.children[0]), d + 1 }); // } // else // { // pending.push({ static_cast<unsigned int>(node.children[0]), d + // 1 }); pending.push({ static_cast<unsigned // int>(node.children[1]), d + 1 }); // } // } //} Node const& node = m_nodes[node_index]; cb(node_index, depth); auto is_pred = pred(node_index, depth); if (!node.isLeaf() && is_pred) { if (pless && !pless(node.children)) { traverseDepthFirst(m_nodes[node_index].children[1], depth + 1, pred, cb, pless); traverseDepthFirst(m_nodes[node_index].children[0], depth + 1, pred, cb, pless); } else { traverseDepthFirst(m_nodes[node_index].children[0], depth + 1, pred, cb, pless); traverseDepthFirst(m_nodes[node_index].children[1], depth + 1, pred, cb, pless); } } // auto n = pending.front().n; // auto d = pending.front().d; // auto const& node = m_nodes[n]; // pending.pop(); // cb(n, d); // auto is_pred = pred(n, d); // if (!node.is_leaf() && is_pred) //{ // if (pless && !pless(node.children)) // { // pending.push({ static_cast<unsigned int>(node.children[1]), d + 1 // }); pending.push({ static_cast<unsigned int>(node.children[0]), d + // 1 }); // } // else // { // pending.push({ static_cast<unsigned int>(node.children[0]), d + 1 // }); pending.push({ static_cast<unsigned int>(node.children[1]), d + // 1 }); // } //} } template <typename HullType, typename TF> void KDTree<HullType, TF>::traverseBreadthFirst( TraversalPredicate const& pred, TraversalCallback const& cb, unsigned int start_node, TraversalPriorityLess const& pless, TraversalQueue& pending) const { // auto pending = TraversalQueue{}; cb(start_node, 0); if (pred(start_node, 0)) pending.push({start_node, 0}); traverseBreadthFirst(pending, pred, cb, pless); } template <typename HullType, typename TF> unsigned int KDTree<HullType, TF>::addNode(unsigned int b, unsigned int n) { HullType hull; computeHull(b, n, hull); m_hulls.push_back(hull); m_nodes.push_back({b, n}); return static_cast<unsigned int>(m_nodes.size() - 1); } template <typename HullType, typename TF> void KDTree<HullType, TF>::update() { traverseDepthFirst([&](unsigned int, unsigned int) { return true; }, [&](unsigned int node_index, unsigned int) { auto const& nd = node(node_index); computeHull(nd.begin, nd.n, hull(node_index)); }); } template <typename HullType, typename TF> void KDTree<HullType, TF>::traverseBreadthFirst( TraversalQueue& pending, TraversalPredicate const& pred, TraversalCallback const& cb, TraversalPriorityLess const& pless) const { while (!pending.empty()) { auto n = pending.front().n; auto d = pending.front().d; auto const& node = m_nodes[n]; pending.pop(); cb(n, d); auto is_pred = pred(n, d); if (!node.is_leaf() && is_pred) { if (pless && !pless(node.children)) { pending.push({static_cast<unsigned int>(node.children[1]), d + 1}); pending.push({static_cast<unsigned int>(node.children[0]), d + 1}); } else { pending.push({static_cast<unsigned int>(node.children[0]), d + 1}); pending.push({static_cast<unsigned int>(node.children[1]), d + 1}); } } } } } // namespace dg } // namespace alluvion #endif
import { useEffect, useState } from 'react'; import { Route, Switch, useRouteMatch, } from 'react-router-dom'; import '../styles/App.scss'; import getTweets from '../services/api'; import ls from '../services/local-storage'; import Profile from './Profile'; import Header from './Header'; import ComposeModal from './ComposeModal'; import Tweets from './Tweets'; import Home from './Home'; import Search from './Search'; import TweetDetail from './TweetDetail'; function App() { // state const [composeIsOpen, setComposeIsOpen] = useState(false); const [composeText, setComposeText] = useState(ls.get("composeText", "")); const [tweets, setTweets] = useState([]); // effect useEffect(() => { getTweets().then(data => { setTweets(data); }); }, []); useEffect(() => { ls.set("composeText", composeText); }, [composeText]); const handleToggleCompose = () => { setComposeIsOpen(!composeIsOpen); } const handleComposeText = (value) => { setComposeText(value); } const handleComposeSubmit = (ev) => { tweets.unshift({ "id": "1243sdf", "avatar": "http://localhost:3000/assets/avatars/user-me.jpg", "user": "Adalab", "username": "adalab_digital", "date": "8 sep. 2021", "text": composeText, "comments": 0, "retweets": 0, "likes": 0 }); setTweets([...tweets]); setComposeIsOpen(false); setComposeText(""); } const renderComposeModal = () => { if(composeIsOpen) { return <ComposeModal handleToggleCompose={handleToggleCompose} composeText={composeText} handleComposeText={handleComposeText} handleComposeSubmit={handleComposeSubmit}/> } } const routeTweetData = useRouteMatch('/tweet1/:tweetId') const getRouteTweet = () => { if(routeTweetData) { const routeTweetId = routeTweetData.params.tweetId; return tweets.find(tweet => { return tweet.id === routeTweetId; }) } } return ( <div className="page"> <Header handleToggleCompose={handleToggleCompose}/> <main className="main"> <Switch> <Route path="/home" exact> <Home /> <Tweets tweets={tweets} /> </Route> <Route path="/search"> <Search /> <Tweets tweets={tweets} /> </Route> <Route path="/profile"> <Profile /> <Tweets tweets={tweets} /> </Route> <Route path='/tweet1/:tweetId'>< TweetDetail tweet1 = {getRouteTweet()}/></Route> </Switch> {renderComposeModal()} </main> </div> ); } export default App;
import 'package:app_leohis/controllers/FCMController.dart'; import 'package:app_leohis/controllers/LocalData.dart'; import 'package:app_leohis/controllers/ThongBaoController.dart'; import 'package:app_leohis/models/ThongBao.dart'; import 'package:app_leohis/views/components/button.dart'; import 'package:app_leohis/views/components/notification_manager/firebase_notification.dart'; import 'package:app_leohis/views/screens/home/screen_Dashboard.dart'; import 'package:app_leohis/views/utils/contants.dart'; import 'package:app_leohis/views/screens/doctor/screen_DieuTriBenhNhan.dart'; // import 'package:app_leohis/views/screens/home/screen_TrangChu.dart'; import 'package:app_leohis/views/screens/nursing/screen_ChamSocBenhNhan.dart'; import 'package:app_leohis/views/screens/patient/screen_DSNamVien.dart'; import 'package:app_leohis/views/components/drawerInfo.dart'; import 'package:app_leohis/views/utils/theme.dart'; import 'package:convex_bottom_bar/convex_bottom_bar.dart'; import 'package:badges/badges.dart' as badges; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:unicons/unicons.dart'; // import 'package:badges/badges.dart' as badges; // ignore: must_be_immutable class NavBars extends StatefulWidget { @override _NavBarsState createState() => _NavBarsState(); _NavBarsState root = _NavBarsState(); } class _NavBarsState extends State<NavBars> { var scaffoldKey = GlobalKey<ScaffoldState>(); ThongBaoController _thongBaoController = ThongBaoController(); bool _haveNotification = false; static List<Widget> _widgetOptions = <Widget>[ Screen_Dashboard(), Screen_DSNamVien(), Screen_DieuTriBenhNhan(), Screen_ChamSocBenhNhan(), ]; CheckThongBao() async { var _listTb = await _thongBaoController.getThongBao(); if (_listTb.isNotEmpty) setState(() { _haveNotification = true; }); } @override void initState() { super.initState(); CheckThongBao(); } @override Widget build(BuildContext context) { final themeProvider = Provider.of<ThemeProvider>(context); return DefaultTabController( length: _widgetOptions.length, initialIndex: 0, child: Scaffold( key: scaffoldKey, appBar: AppBar( toolbarHeight: 70, // iconTheme: IconThemeData(color: IconThemeData(color: )), leading: IconButton( icon: Icon(UniconsLine.list_ui_alt), onPressed: () { scaffoldKey.currentState!.isDrawerOpen ? scaffoldKey.currentState!.closeDrawer() : scaffoldKey.currentState!.openDrawer(); }, ), title: Text( "Leohis", // style: TextStyle(color: textColor2), ), // backgroundColor: themeModeColor, scrolledUnderElevation: 0.3, elevation: 0, actions: [ // NotificationDrawer(), Builder( builder: (context) => IconButton( onPressed: () { Scaffold.of(context).openEndDrawer(); }, icon: badges.Badge( position: badges.BadgePosition.custom(top: -3, end: -2), badgeStyle: badges.BadgeStyle( shape: badges.BadgeShape.circle, badgeColor: _haveNotification ? Colors.red : Colors.transparent, ), child: Icon(Icons.notifications_none), ), ), ) ], ), endDrawer: NotificationDrawer(), drawer: DrawerInfo(), body: TabBarView(children: _widgetOptions), bottomNavigationBar: ConvexAppBar( backgroundColor: themeProvider.isDarkMode || themeProvider.isSysDark(context) ? Color(0xff2B3038) : themeModeColor, elevation: 20, shadowColor: const Color.fromARGB(22, 0, 0, 0), color: Colors.grey, height: 60, activeColor: primaryColor.withOpacity(.15), curveSize: 100, items: <TabItem>[ TabItem( icon: Icon(UniconsLine.estate, color: Colors.grey), activeIcon: Icon(UniconsLine.estate, color: primaryColor), title: "Trang chủ"), TabItem( icon: Icon(UniconsLine.users_alt, color: Colors.grey), activeIcon: Icon(UniconsLine.users_alt, color: primaryColor), title: "Bệnh nhân"), TabItem( icon: Icon(UniconsLine.stethoscope, color: Colors.grey), activeIcon: Icon(UniconsLine.stethoscope, color: primaryColor), title: "Bác sĩ"), TabItem( icon: Icon(UniconsLine.user_nurse, color: Colors.grey), activeIcon: Icon(UniconsLine.user_nurse, color: primaryColor), title: "Điều dưỡng"), ], ), ), ); } } class NotificationDrawer extends StatefulWidget { const NotificationDrawer({super.key}); @override State<NotificationDrawer> createState() => _NotificationDrawerState(); } class _NotificationDrawerState extends State<NotificationDrawer> { List<ThongBaoData> _listTb = []; ThongBaoController _thongBaoController = ThongBaoController(); getThongBao() async { _listTb = await _thongBaoController.getThongBao(); setState(() { _listTb; }); } @override void initState() { super.initState(); getThongBao(); } @override Widget build(BuildContext context) { return Drawer( elevation: 0, width: screen(context).width / 1.2, backgroundColor: Colors.transparent, child: SingleChildScrollView( physics: NeverScrollableScrollPhysics(), child: SafeArea( child: InkWell( onTap: () => Navigator.pop(context), child: SizedBox( height: screen(context).height, child: Column( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: const EdgeInsets.only(top: 50, right: 10), child: InkWell( onTap: () {}, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(15), bottomLeft: Radius.circular(15), bottomRight: Radius.circular(15), ), ), child: Container( padding: EdgeInsets.only(left: 15, bottom: 0), // clipBehavior: Clip.hardEdge, height: 450, width: screen(context).width, child: Column( children: [ SizedBox( height: 70, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Thông báo", style: TextStyle( fontSize: 16, fontWeight: FontWeight.w500), ), Padding( padding: EdgeInsets.only(right: 10), child: MyButton( width: 160, height: 35, label: "Xóa thông báo", textColor: primaryColor, radius: 10, padding: EdgeInsets.all(5), onPressed: () async { // _listTb.clear(); // await _localData // .Shared_clearThongBao(); FCMController.sendNotification( receiverToken: deviceToken, body: "Phong", title: "..."); }, color: primaryColor.withOpacity(.2), subfixIcon: Icon( Icons.check_circle_outline, color: primaryColor, ), ), ), ], ), ), Expanded( child: Scrollbar( radius: Radius.circular(5), thickness: 7, child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Padding( padding: const EdgeInsets.only(right: 10.0), child: Column( children: _listTb.isEmpty ? [ SizedBox(height: 100), Image.asset( "assets/images/icons/inbox_64px.png", color: Colors.grey, ), SizedBox(height: 10), Text( "Chưa có thông báo mới nào", style: TextStyle( color: Colors.grey), ) ] : [ for (var item in _listTb) buildThongBao(item), ], ), ), ), ), ), ], ), ), ), ), ), ], ), ), ), ), ), ); } buildThongBao(ThongBaoData data) { return Padding( padding: const EdgeInsets.symmetric(vertical: 7), child: ListTile( onTap: () async {}, minLeadingWidth: 0, minVerticalPadding: 0, contentPadding: EdgeInsets.zero, leading: CircleAvatar( radius: 20, backgroundColor: primaryColor, child: Icon( Icons.notifications, color: Theme.of(context).cardColor, size: 24, ), ), title: Row( children: [ Expanded( child: RichText( text: TextSpan(children: [ WidgetSpan( child: Text( "${checkString(data.tieude)} ", style: TextStyle( fontWeight: FontWeight.w500, ), )), WidgetSpan( child: Text( "${formatTime(data.ngaythongbao)} ${formatDate(data.ngaythongbao)}", maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(color: primaryColor, fontSize: 14), )), if (data.ngayhen != null) WidgetSpan( child: Text( "Ngày hẹn: ${formatTime(data.ngayhen)} ${formatDate(data.ngayhen)}", maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle( color: primaryColor, fontSize: 14, fontWeight: FontWeight.bold), )), ])), ), ], ), subtitle: Text( "${checkString(data.noidung)}", maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ); } }
// // MovieDetailsViewModel.swift // TeldaMovies // // Created by Ahmed M. Hassan on 24/11/2022. // import Foundation // MARK: MovieDetailsViewModel // final class MovieDetailsViewModel { let networking = TMDBNetworking() let converter = MovieViewModelConverter() let movie: MovieEntity private var sections: [Section] = [] private var onSync: () -> Void = { } private(set) var movieOverview: MovieOverviewTableViewCell.ViewModel private(set) var similarMoviesList: MoviesTableViewCell.ViewModel = [] private(set) var actorsList: CastsTableViewCell.ViewModel = [] private(set) var directorsList: CastsTableViewCell.ViewModel = [] init(movie: MovieEntity) { self.movie = movie self.movieOverview = MovieOverviewTableViewCell.ViewModel(movie: movie) self.similarMoviesList = [MovieCollectionViewCell.ViewModel(movie: movie, isFavorite: false)] } } // MARK: MovieDetailsViewModel Input // extension MovieDetailsViewModel: MovieDetailsViewModelInput { func viewDidLoad() { reloadSectionsAndSync() loadMovieOverview() loadSimilarMovies() } } // MARK: MovieDetailsViewModelOutput // extension MovieDetailsViewModel: MovieDetailsViewModelOutput { var title: String { return movieOverview.title } func onSync(onSync: @escaping () -> Void) { self.onSync = onSync } func numberOfSections() -> Int { return sections.count } func numberOfRows(at section: Int) -> Int { return sections[section].rows.count } func sectionTitle(at section: Int) -> String? { return sections[section].title } func row(at indexPath: IndexPath) -> MovieDetailsViewModel.RowType { return sections[indexPath.section].rows[indexPath.row] } } // MARK: Private Handlers // private extension MovieDetailsViewModel { func reloadSectionsAndSync() { reloadSections() onSync() } func loadMovieOverview() { networking.movieDetails(id: String(movie.id)) { [weak self] result in guard let self = self, case .success(let movie) = result else { return } let movieOverview = MovieOverviewTableViewCell.ViewModel(movie: movie) self.movieOverview = movieOverview self.reloadSectionsAndSync() } } func loadSimilarMovies() { networking.similarMovies(id: String(movie.id)) { [weak self] result in guard let self = self, case .success(let value) = result else { return } let movies = Array(value.results.prefix(5)) self.loadSimilarMoviesCast(movies) self.similarMoviesList = self.converter.movieCellViewModels(of: movies) self.reloadSectionsAndSync() } } } // MARK: Similar Movies Cast Handlers // private extension MovieDetailsViewModel { func loadSimilarMoviesCast(_ movies: [MovieEntity]) { DispatchQueue.global().async { self.loadActorsAndDirectors(in: movies) { actors, directors in self.actorsList = actors.map(CastCollectionViewCell.ViewModel.init) self.directorsList = directors.map(CastCollectionViewCell.ViewModel.init) DispatchQueue.main.async { self.reloadSectionsAndSync() } } } } func loadActorsAndDirectors(in movies: [MovieEntity], completion: @escaping ([CastEntity], [CastEntity]) -> Void) { var actors: Set<CastEntity> = [] var directors: Set<CastEntity> = [] let dispatchGroup = DispatchGroup() movies.forEach { movie in dispatchGroup.enter() loadMovieCast(movie) { credits in defer { dispatchGroup.leave() } let cast = credits?.cast ?? [] for item in cast where item.knownForDepartment == .acting { actors.insert(item) } for item in cast where item.knownForDepartment == .directing { directors.insert(item) } } } dispatchGroup.notify(queue: .global()) { let sortedActors = actors .sorted(by: { $0.popularity ?? .zero > $1.popularity ?? .zero }) .prefix(5) let sortedDirectors = directors .sorted(by: { $0.popularity ?? .zero > $1.popularity ?? .zero }) .prefix(5) completion(Array(sortedActors), Array(sortedDirectors)) } } func loadMovieCast(_ movie: MovieEntity, completion: @escaping (MovieCreditsEntity?) -> Void) { networking.movieCredits(id: String(movie.id)) { result in let credits = try? result.get() completion(credits) } } } // MARK: Reload Sections // private extension MovieDetailsViewModel { func reloadSections() { self.sections = { var sections: [Section] = [] sections.append(Section(rows: [.overview, .tagline, .revenue, .releaseDate, .status])) if similarMoviesList.isNotEmpty { sections.append(Section(title: "Similar Movies", rows: [.similarMovies])) } if actorsList.isNotEmpty { sections.append(Section(title: "Actors", rows: [.actors])) } if directorsList.isNotEmpty { sections.append(Section(title: "Directors", rows: [.directors])) } return sections }() } } // MARK: Nested Types // extension MovieDetailsViewModel { struct Section { let title: String? let rows: [RowType] init(title: String? = nil, rows: [MovieDetailsViewModel.RowType]) { self.title = title self.rows = rows } } enum RowType { case overview case tagline case revenue case releaseDate case status case similarMovies case actors case directors var reuseIdentifier: String { switch self { case .overview: return MovieOverviewTableViewCell.reuseIdentifier case .tagline, .revenue, .releaseDate, .status: return KeyValueTableViewCell.reuseIdentifier case .similarMovies: return MoviesTableViewCell.reuseIdentifier case .actors, .directors: return CastsTableViewCell.reuseIdentifier } } } }
<chapter id="sidebar"> <chapterinfo> <authorgroup> <author>&Pamela.Roberts;</author> <!-- TRANS:ROLES_OF_TRANSLATORS --> </authorgroup> <date>2011-11-22</date> <releaseinfo>&kde; 4.8</releaseinfo> </chapterinfo> <title>The Sidebar</title> <para>The Sidebar appears as a separate view at the left of &konqueror;'s window. It can be invoked with <menuchoice><guimenu>Settings </guimenu><guimenuitem>Show Sidebar</guimenuitem></menuchoice> or toggled on and off with the <keycap>F9</keycap> key.</para> <mediaobject> <imageobject><imagedata format="PNG" fileref="dirtree.png"/></imageobject> <textobject> <phrase>With the Sidebar</phrase> </textobject> </mediaobject> <para>It contains a number of tabbed pages; <mousebutton>left</mousebutton> click on a tab's icon to view that page. <mousebutton>Left</mousebutton> clicking on the icon for the visible page will collapse the Sidebar so that only the tab icons are visible.</para> <variablelist> <varlistentry> <term><guilabel>Bookmarks</guilabel></term> <listitem><para>This page shows a tree view of your Bookmarks. <mousebutton> Left</mousebutton> click on an item to open it in the main view.</para> </listitem> </varlistentry> <varlistentry> <term><guilabel>History</guilabel></term> <listitem><para>This page shows a tree view of your browsing History. <mousebutton>Left</mousebutton> clicking on an item will open it in the main view, or you can open it in a new &konqueror; window by <mousebutton>right </mousebutton> clicking and selecting <guimenuitem>Open in New Window</guimenuitem> from the pop up menu.</para> <para>You can remove an item from the history by <mousebutton>right </mousebutton> clicking on it and selecting <guimenuitem>Remove Entry</guimenuitem>. Selecting <guimenuitem>Clear History</guimenuitem> will clear out the entire history.</para> <para>The pop up menu you get when you <mousebutton>right</mousebutton> click on any entry in the History page also gives you the option of choosing whether the entire history is sorted by name or by date.</para> <para>Selecting <guimenuitem>Preferences...</guimenuitem> from this pop up menu brings up the <guilabel>History Sidebar</guilabel> control module. This can be used to set the maximum size of your history and set a time after which items are automatically removed. You can also set different fonts for new and old &URL;s. The <guilabel>Detailed tooltips</guilabel> checkbox controls how much information is displayed when you hover the mouse pointer over an item in the history page.</para></listitem> </varlistentry> <varlistentry> <term><guilabel>Home Folder</guilabel></term> <listitem><para>This page shows a tree view of the subfolders of your home folder. Note that <quote>hidden</quote> folders (those with names beginning with a dot) are not shown. <mousebutton>Left</mousebutton> click on an item to open it in the main view, or <mousebutton>right</mousebutton> click to display a pop up menu allowing you to open the subfolder in a new window or as a new tab page of the main view. </para></listitem> </varlistentry> <varlistentry> <term><guilabel>Network</guilabel></term> <listitem><para>This page is intended to show a tree view of your important network connections, although local folders can also be included. Again, you can <mousebutton>left</mousebutton> click on an item to open it in the main view or <mousebutton>right</mousebutton> click to bring up a menu with a wider range of possibilities.</para> <para>The folders shown in the <guilabel>Network</guilabel> page are held in the folder <filename class="directory"> ~/.kde/share/apps/konqsidebartng/virtual_folders/remote/</filename>, and you can make new ones just as you would make any other subfolder. The items within these folders are held as <literal role="extension">.desktop</literal> files and can be created with &konqueror;'s <menuchoice><guisubmenu>Create New</guisubmenu> <guimenuitem>Link to Location (URL)...</guimenuitem></menuchoice> option in the <guimenu>Edit</guimenu> menu.</para> </listitem> </varlistentry> <varlistentry> <term><guilabel>Root Folder</guilabel></term> <listitem><para>The <guilabel>Root Folder</guilabel> tree has the path <filename class="directory">/</filename>, and is the base folder of your system's local files. If you expand the <quote>Root</quote> folder you will find another folder called <filename class="directory">root</filename>. This belongs to the system administrator or Super User and is her home folder. You will also find a folder called <filename class="directory">home</filename>, in which you should be able to find your own <quote>Home</quote> folder again.</para> </listitem> </varlistentry> <varlistentry> <term><guilabel>Services</guilabel></term> <listitem><para>This page provides quick access to the following services: </para> <para><guilabel>Applications</guilabel>, <guilabel>Audio CD Browser</guilabel> and <guilabel>Fonts</guilabel>.</para> <!-- not in 4.4 <para><guilabel>Devices</guilabel>. This shows your hard disc partitions, floppy and &CD-ROM;. <mousebutton>Left</mousebutton> click on a device or partition name to mount it and display its contents in the main view. A mounted device or partition can be unmounted by <mousebutton>right </mousebutton> clicking on the device name and selecting <guimenuitem>Unmount </guimenuitem> from the pop up menu. </para> <para>The <guilabel>LAN Browser</guilabel> allows you to browse other machines connected to your Local Area Network.</para> <para>The <guilabel>Print System Browser</guilabel> tree gives you quick access to &kde;'s print manager <application>Kprinter</application>.</para> --> </listitem> </varlistentry> <!-- begin copy from dolphin docbook--> <varlistentry> <term><guilabel>Places</guilabel></term> <listitem><para> The <guilabel>Places</guilabel> panel is located at the left of the window by default. The <guilabel>Places</guilabel> panel shows any locations you have bookmarked. It also shows any disk or media attached to the computer. </para> <para> The easiest way to add a folder to the <guilabel>Places</guilabel> panel is to drag it and drop it in the panel. Moreover, you can click inside the panel with the &RMB; and choose <menuchoice><guimenuitem>Add Entry...</guimenuitem></menuchoice> from the context menu. </para> </listitem> </varlistentry> <!-- end copy from dolphin docbook--> </variablelist> <para>The sidebar configuration can be changed by <mousebutton>right </mousebutton> clicking on the empty area below the bottom tab icon or by <mousebutton>left</mousebutton> clicking on the <guilabel>Configuration Button</guilabel> icon, this is enabled in the contextmenu. Doing this brings up a menu with the following options:</para> <variablelist> <varlistentry> <term><guisubmenu>Add New</guisubmenu></term> <listitem><para>This option lets you add a new tab page to the Sidebar. The new page can contain different sidebar modules or a new <guimenuitem>Folder</guimenuitem> tree view. The last option in this submenu allows you to rollback to system default.</para> </listitem> </varlistentry> <varlistentry> <term><guimenuitem>Multiple Views</guimenuitem></term> <listitem><para>Selecting this option splits the Sidebar so that two tab pages can be seen at once.</para> </listitem> </varlistentry> <varlistentry> <term><guimenuitem>Show Tabs Left</guimenuitem>, <guimenuitem>Show Tabs Right</guimenuitem></term> <listitem><para>This option lets you choose whether the tab icons are shown at the left or right of the sidebar.</para> </listitem> </varlistentry> <varlistentry> <term><guimenuitem>Show Configuration Button</guimenuitem></term> <listitem><para>Use this option to show or hide the <guilabel>Configuration Button</guilabel> icon.</para> </listitem> </varlistentry> </variablelist> <para><mousebutton>Right</mousebutton> clicking on a tab icon brings up a menu with the following options:</para> <variablelist> <varlistentry> <term><guimenuitem>Set Name</guimenuitem></term> <listitem><para>This option lets you change the Name of that page.</para></listitem> </varlistentry> <varlistentry> <term><guimenuitem>Set URL</guimenuitem></term> <listitem><para>This option lets you change the &URL; (path) of the folder viewed in that page.</para></listitem> </varlistentry> <varlistentry> <term><guimenuitem>Set Icon</guimenuitem></term> <listitem><para>To change the tab icon.</para></listitem> </varlistentry> <varlistentry> <term><guimenuitem>Remove</guimenuitem></term> <listitem><para>To remove the tab page from the sidebar.</para> </listitem> </varlistentry> <varlistentry> <term><guimenuitem>Configure Sidebar</guimenuitem></term> <listitem><para>The last item offers a configuration submenu of the sidebar as described above.</para> </listitem> </varlistentry> </variablelist> </chapter> <!-- Local Variables: mode: sgml sgml-omittag: nil sgml-shorttag: t sgml-minimize-attributes: nil sgml-general-insert-case: lower sgml-parent-document:("index.docbook" "book" "chapter") End: -->
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AuthService } from '../auth/auth.service'; import { LocalStrategy } from '../auth/local.strategy'; import { JwtStrategy } from '../auth/jwt.strategy'; import { ConfigService, ConfigModule } from '@nestjs/config'; import { JwtModule } from '@nestjs/jwt'; import { UserController } from './user.controller'; import { User } from './User.entity'; import { UserService } from './user.service'; import { PassportModule } from '@nestjs/passport'; import { EncryptionService } from '../auth/encryption.service'; @Module({ imports: [ /** * Imports */ TypeOrmModule.forFeature([User]), PassportModule, /** * Configure the JwtModule to handle JWT token creation and validation. */ JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ secret: configService.get('SECRET_KEY'), signOptions: { expiresIn: '1d' }, }), inject: [ConfigService], }), ], /** * Controllers associated with the UserModule. */ controllers: [UserController], /** * Providers for services used within the UserModule. */ providers: [ UserService, AuthService, EncryptionService, LocalStrategy, JwtStrategy, ], /** * Expose the UserService for potential use in other modules. */ exports: [UserService], }) export class UserModule {}
import React, { useState, useEffect } from 'react'; import { collection, addDoc, serverTimestamp, getDocs, doc, updateDoc } from 'firebase/firestore'; import { database } from '../firebaseConfig'; import '../styles/moneyTransfer.scss'; import AOS from 'aos'; import 'aos/dist/aos.css'; const MoneyTransfer = () => { useEffect(() => { AOS.init({ duration: 1000, }); }, []); const data = collection(database, 'customers'); const transactions = collection(database, 'transactions'); const [done, setDone] = useState([]); const [showPopup, setShowPopup] = useState(false); const [popupMessage, setPopupMessage] = useState(''); const getCustomers = async () => { const res = await getDocs(data); const done = res.docs.map((item) => { return { ...item.data(), id: item.id }; }); setDone(done); }; getCustomers(); const getAccountBalance = (accNo, arr) => { for (let i = 0; i < arr.length; i++) { if (arr[i].accNo === accNo) { return arr[i].currBal; } } }; const showPopupWithDuration = (message, duration) => { setPopupMessage(message); setShowPopup(true); setTimeout(() => { setShowPopup(false); }, duration); }; const transferFunds = async (e) => { e.preventDefault(); var select1 = document.getElementById('accounts1'); var value1 = select1.options[select1.selectedIndex].value; var select2 = document.getElementById('accounts2'); var value2 = select2.options[select2.selectedIndex].value; let amount = document.getElementById('amt').value; if (value1 === value2) { showPopupWithDuration('❌ Transaction cannot be done between the same accounts!', 2000); return; } else { if (getAccountBalance(value1, done) < amount) { showPopupWithDuration('❌ Insufficient balance', 2000); return; } let account1 = done.find((item) => item.accNo === value1); let account2 = done.find((item) => item.accNo === value2); let balanceOfAccount1 = account1.currBal - amount; let balanceOfAccount2 = account2.currBal + Number(amount); let docToUpdate1 = doc(database, 'customers', account1.id); let docToUpdate2 = doc(database, 'customers', account2.id); updateDoc(docToUpdate1, { currBal: balanceOfAccount1, }); updateDoc(docToUpdate2, { currBal: balanceOfAccount2, }) .then(async () => { // Record the successful transaction with a timestamp await addDoc(transactions, { from: account1.accNo, from_name:account1.cusName, to: account2.accNo, to_name:account2.cusName, Amount_transfered: amount, timestamp: serverTimestamp(), // Server timestamp for the time of the transaction }); showPopupWithDuration('✅ Transaction Successfully', 2000); }) .catch((err) => { showPopupWithDuration('❌ Technical Error! Try Again', 2000); console.log('ERRR' + err); }); } }; return ( <section className="transfer_sec"> <div className="container"> <div className="transfer_box" data-aos="fade-up" data-aos-delay="100"> <form onSubmit={transferFunds}> <h2 className='heading'>Transfer Money</h2> <select name="accounts" id="accounts1" placeholder="Debited from"> <option value="">Debit from</option> {done.map((item, i) => ( <option key={i} value={item.accNo}> {item.cusName} ({item.accNo}) (Aval. Bal ₹{item.currBal}) </option> ))} </select> <select name="accounts" id="accounts2" placeholder="Credited to"> <option value="">Credit to</option> {done.map((item, i) => ( <option key={i} value={item.accNo}> {item.cusName} ({item.accNo}) (Aval. Bal ₹{item.currBal}) </option> ))} </select> <input type="number" id="amt" className="amount" placeholder="Enter Amount (in ₹)" required /> <input type="submit" className="submitBtn" value="Submit" /> </form> </div> </div> {showPopup && ( <div className="popup"> <p className="success">{popupMessage}</p> </div> )} </section> ); }; export default MoneyTransfer;
class Api::V1::BondsController < ApplicationController before_action :authenticate_user! def index @bonds = Bond.all render json: @bonds end def show @bond = Bond.find(params[:id]) if @bond render json: @bond else render json: @bond, status: :unprocessable_entity end end def create @bond = Bond.new(bond_params) @bond.validate_name @bond.validate_quantity @bond.validate_selling_price if @bond.save render json: @bond else render json: { status: 422, errors: bond.errors.full_messages } end end def destroy @bond = Bond.find(params[:id]) @bond.destroy render json: @bond, status: :destroyed end def update @bond = Bond.find(params[:id]) if @bond.update(bond_params) render json: @bond else render json: @bond, status: :unprocessable_entity end end def user_bonds @bonds = Bond.where(user_id: current_user.id) if @bonds render json: @bonds else render json: @bonds, status: :unprocessable_entity end end def bonds_for_buy @bonds = Bond.where.not(user_id: current_user.id) if @bonds render json: @bonds else render json: @bonds, status: :unprocessable_entity end end def buy_bonds @bond = Bond.find(params[:id]) @bond.buy_bond render json: @bond end private def bond_params params.require(:bond).permit(:name, :quantity, :selling_price) end end
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import { EventsListComponent, EventThumbnailComponent, EventService, EventDetailsComponent, CreateEventComponent, EventListResolver, CreateSessionComponent, SessionListComponent, DurationPipe, UpvoteComponent, VoterService, LocationValidator, EventResolver } from './events/index'; import {EventsAppComponent} from './events-app.component'; import {NavBarComponent} from './nav/navbar.component'; import { JQ_TOKEN, TOASTR_TOKEN, Toastr, CollapsibleWellComponent, SimpleModalComponent, ModalTriggerDirective } from './common/index'; import {RouterModule} from '@angular/router'; import {appRoutes} from './routes'; import {Error404Component} from './errors/404.component'; import {AuthService} from './user/auth.service'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; let toastr: Toastr = window['toastr']; let jQuery = window['$']; @NgModule({ declarations: [ EventsAppComponent, EventsListComponent, EventThumbnailComponent, EventDetailsComponent, NavBarComponent, CreateEventComponent, Error404Component, CreateSessionComponent, SessionListComponent, CollapsibleWellComponent, DurationPipe, SimpleModalComponent, ModalTriggerDirective, UpvoteComponent, LocationValidator ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), HttpClientModule ], providers: [ EventService, { provide: TOASTR_TOKEN, useValue: toastr }, { provide: JQ_TOKEN, useValue: jQuery }, EventResolver, EventListResolver, AuthService, { provide: 'canDeactivateCreateEvent', useValue: checkDirtyState }, VoterService ], bootstrap: [EventsAppComponent] }) export class AppModule { } export function checkDirtyState(component: CreateEventComponent) { if (component.isDirty) { return window.confirm('You have not saved this event, do you really want to cancel?'); } return true; }
package day16 import day16.Direction.* import println import readInput import java.lang.IllegalArgumentException fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("day16/Day16_test") check(part1(testInput).also { it.println() } == 46) check(part2(testInput).also { it.println() } == 51) val input = readInput("day16/Day16") println("Part 1 Answer: ${part1(input)}") println("Part 2 Answer: ${part2(input)}") } fun part1(input: List<String>): Int { return tilesEnergized(input, Beam(Position(0, -1), East)) } fun part2(input: List<String>): Int { val initialBeams = input.indices.flatMap { row -> listOf( Beam(Position(row, -1), East), Beam(Position(row, input[row].length), West) ) } + input.first().indices.flatMap { col -> listOf( Beam(Position(-1, col), South), Beam(Position(input.size, col), North) ) } return initialBeams.maxOf { initialBeam -> tilesEnergized(input, initialBeam) } } private fun tilesEnergized(input: List<String>, initialBeam: Beam): Int { val entryDirections = Array(input.size) { Array(input.first().length) { HashSet<Direction>() } } val initialBeams = listOf(initialBeam) val beamsSequence = generateSequence(initialBeams) { beams -> beams.flatMap { beam -> val nextPosition = beam.nextPosition // Are we headed of the grid? if (nextPosition.row !in entryDirections.indices || nextPosition.col !in entryDirections[nextPosition.row].indices ) return@flatMap emptyList<Beam>() // Have we entered this position going in this direction already? val entryDirectionsHere = entryDirections[nextPosition.row][nextPosition.col] if (beam.direction in entryDirectionsHere) return@flatMap emptyList<Beam>() entryDirectionsHere += beam.direction // Outgoing beams input[nextPosition.row][nextPosition.col] .exitDirections(entryDirection = beam.direction) .map { exitDirection -> Beam(nextPosition, exitDirection) } } } beamsSequence.find { beams -> beams.isEmpty() } return entryDirections.sumOf { row -> row.count { directions -> directions.isNotEmpty() } } } fun Char.exitDirections(entryDirection: Direction): List<Direction> = when (this) { '.' -> listOf(entryDirection) '\\' -> listOf( when (entryDirection) { North -> West South -> East East -> South West -> North } ) '/' -> listOf( when (entryDirection) { North -> East South -> West East -> North West -> South } ) '|' -> when (entryDirection) { North, South -> listOf(entryDirection) East, West -> listOf(North, South) } '-' -> when (entryDirection) { East, West -> listOf(entryDirection) North, South -> listOf(East, West) } else -> throw IllegalArgumentException() } data class Position(val row: Int, val col: Int) enum class Direction(val rowDelta: Int, val colDelta: Int) { North(rowDelta = -1, colDelta = 0), South(rowDelta = 1, colDelta = 0), East(rowDelta = 0, colDelta = 1), West(rowDelta = 0, colDelta = -1); } infix fun Position.move(direction: Direction) = Position( row = row + direction.rowDelta, col = col + direction.colDelta ) data class Beam( var position: Position, var direction: Direction ) val Beam.nextPosition get() = position move direction
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- Reset CSS --> <link rel="stylesheet" href="./assets/css/resest.css"> <!-- Embed fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:wght@700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="assets/fonts/stylesheet.css"> <!-- style --> <link rel="stylesheet" href="./assets/css/styles.css"> </head> <body> <main id="home"> <header class="fixed-header"> <div class="content"> <nav class="navbar"> <a href="#"> <img src="./assets/img/Logo.svg" alt="BESNIK"> </a > <ul> <li><a href="#home">Home</a></li> <li><a href="#services">Services</a></li> <li><a href="#features">Features</a></li> <li><a href="#resources">Resources</a></li> <li><a href="#contact">contact</a></li> </ul> <div class="actions"> <a href="#!" class="action-link">Sig in</a> <a href="#!" class="btn action-btn">Sig up</a> </div> </nav> </div> </header> <!-- ====HEADER==== --> <div class="hero-wrap"> <div class="content"> <!-- HERO --> <div class="hero"> <div class="info"> <p class="sub-title">Welcome to Besnik Agency</p> <h1 class="title">Discover a place you'll love to live.</h1> <p class="desc">Get the best real estate deals first, before they hit the mass market! HOT FORECLOSURE DEALS with one simple search.</p> <a href="#!" class="btn hero-btn">More About Us</a> </div> <img class="hero-img" src="./assets/img/hero.svg" alt="Discover a place you'll love to live."> </div> </div> </div> <!-- ====CLIENTS==== --> <div class="client"> <div class="content"> <div class="row"> <div class="logo"> <img src="./assets/img/Logo.svg" alt="Bensnik"> </div> <div class="stars" > <img src="./assets/img/stars.svg" alt="stars"> <img src="./assets/img/stars.svg" alt="stars"> <img src="./assets/img/stars.svg" alt="stars"> <img src="./assets/img/stars.svg" alt="stars"> <img src="./assets/img/stars.svg" alt="stars"> </div> </div> <div class="row row-desc"> <p class="desc">More than 45,000+ companies trust besnik</p> <p class="desc">5 Star Ratings (2k+ Review)</p> </div> <div class="images"> <a href="#!"> <img src="./assets/img/client 1.svg" alt="Bensnik"> </a> <a href="#!"> <img src="./assets/img/client 2.svg" alt="Bensnik"> </a> <a href="#!"> <img src="./assets/img/client 3.svg" alt="Bensnik"> </a> <a href="#!"> <img src="./assets/img/client 4.svg" alt="Bensnik"> </a> <a href="#!"> <img src="./assets/img/client 5.svg" alt="Bensnik"> </a> </div> </div> </div> <!-- ====GUIDES==== --> <div id="services" class="guides"> <div class="content"> <h2 class="sub-title">How its works?</h2> <p class="desc"> Everything you need to know when you're looking to buy, rent, or sell - all in one place. </p> <ul class="list-guide"> <li class="guide-item"> <img src="./assets/img/buyer.svg" alt="buyer" class="icon"> <h3 class="title">Buyer Guides</h3> <a href="" class="link"> <span >How to buy</span> <img src="./assets/img/arrow right.svg" alt="arrown right" class="arrow"> </a> </li> <li class="guide-item"> <img src="./assets/img/rent.svg" alt="rent" class="icon"> <h3 class="title">Renter Guides</h3> <a href="" class="link"> <span >How to buy</span> <img src="./assets/img/arrow right.svg" alt="arrown right" class="arrow"> </a> </li> <li class="guide-item"> <img src="./assets/img/sell.svg" alt="buyer" class="icon"> <h3 class="title">Seller Guides</h3> <a href="" class="link"> <span >How to buy</span> <img src="./assets/img/arrow right.svg" alt="arrown right" class="arrow"> </a> </li> </ul> <div class="guide-cta"> <a href="" class="btn">Sell Full Guidelines</a> </div> </div> </div> <!-- ====FEATURED==== --> <div id="features" class="featured"> <div class="content"> <header> <h2 class="sub-title">Featured Properties</h2> <div class="row"> <p class="desc">Everything you need to know when you're looking</p> <a href="" class="link"> <span>View All Properties</span> <img src="./assets/img/arrow right.svg" alt="arrow right" class="arrow"> </a> </div> </header> <div class="list"> <!-- ===ITEM 1=== --> <div class="item"> <a href="#!"> <img src="./assets/img/feature 1.jpg" alt="Nikko Apartments" class="thumb"> </a > <div class="body"> <h3 class="title"> <a href="#!" class="line-clamp">Nikko Apartments</a> </h3> <p class="desc line-clamp" > 8502 Preston Rd. Inglewood, Maine 98280</p> <div class="info"> <img src="./assets/img/beds.svg" alt="" class="icon"> <span class="lable">5 Beds</span> <img src="./assets/img/both.svg" alt="" class="icon"> <span class="lable">2 both</span> <img src="./assets/img/sqft.svg" alt="" class="icon"> <span class="lable">2000 Sqft</span> </div> </div> </div> <!-- ===ITEM 2=== --> <div class="item"> <a href="#!"><img src="./assets/img/feature 2.jpg" alt="CouCou Homestead" class="thumb"></a > <div class="body"> <h3 class="title"><a href="#!"class="line-clamp">CouCou Homestead</a ></h3> <p class="desc line-clamp">8502 Preston Rd. Inglewood, Maine 98280</p> <div class="info"> <img src="./assets/img/beds.svg"alt="" class="icon"> <span class="lable">5 Beds</span> <img src="./assets/img/both.svg" alt="" class="icon"> <span class="lable">2 both</span> <img src="./assets/img/sqft.svg" alt="" class="icon"> <span class="lable">2000 Sqft</span> </div> </div> </div> <!-- ===ITEM 3=== --> <div class="item"> <a href="#!"> <img src="./assets/img/feature 3.jpg" alt="Lavis 18 Residence" class="thumb"></a > <div class="body"> <h3 class="title"><a href="#!" class="line-clamp">Lavis 18 Residence</a ></h3> <p class="desc line-clamp">8502 Preston Rd. Inglewood, Maine 98280</p> <div class="info"> <img src="./assets/img/beds.svg" alt="" class="icon"> <span class="lable">5 Beds</span> <img src="./assets/img/both.svg" alt="" class="icon"> <span class="lable">2 both</span> <img src="./assets/img/sqft.svg" alt="" class="icon"> <span class="lable">2000 Sqft</span> </div> </div> </div> </div> </div> </div> <!-- ====STATS==== --> <div id="resources" class="stats"> <div class="content"> <div class="row"> <div class="img-block"> <img class="image"src="./assets/img/stat-img.jpg" alt=""> <!-- trend --> <div class="stats-trend"> <div class="row"> <strong class="value">40,000+</strong> <img src="./assets/img/arrow-trend-top.svg" alt="" class="icon"> </div> <p class="desc">By avarage for 2 bedroom apments in San Francisco, CA</p> <div class="separate"></div> <div class="avatar-block"> <div class="avatar-group"> <img src="./assets/img/avatar-1.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-2.jpg" alt="" class="avatar"> </div> <div class="avatar-group"> <img src="./assets/img/avatar-3.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-4.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-5.webp" alt="" class="avatar"> <div class="avatar" style="--bg-color:#1F3BB1">R</div> </div> <div class="avatar-group"> <div class="avatar" style="--bg-color:#24D6D9">FJ</div> <img src="./assets/img/avatar-8.jpg" alt="" class="avatar"> <div class="avatar" style="--bg-color:#F8C120">S</div> </div> <div class="avatar-group"> <img src="./assets/img/avatar-7.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-2.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-2.jpg" alt="" class="avatar"> <div class="avatar" style="--bg-color:#F97F6B">JJ</div> </div> <div class="avatar-group"> <img src="./assets/img/avatar-1.jpg" alt="" class="avatar"> <div class="avatar" style="--bg-color:#73A242">QV</div> </div> <div class="avatar-group"> <img src="./assets/img/avatar-1.jpg" alt="" class="avatar"> <img src="./assets/img/avatar-2.jpg" alt="" class="avatar"> </div> <div class="avatar-group"> <img src="./assets/img/avatar-6.jfif" alt="" class="avatar"> <div class="avatar" style="--bg-color:#1F3BB0">IU</div> </div> </div> </div> </div> <div class="info"> <h2 class="sub-title">You’ve found a neighborhood you love.</h2> <p class="desc">When you own a home, you’re committing to living in one location for a while. In a recent Trulia survey, we found that five out of six respondents said finding the right neighborhood </p > </div> </div> <div class="row row-qty"> <div class="qty-item"> <strong class="qty">2,500</strong> <p class="qty-desc">Homes For Sale</p> </div> <div class="qty-item"> <strong class="qty">5,000+</strong> <p class="qty-desc">Homes Recently Sold</p> </div> <div class="qty-item"> <strong class="qty">170+</strong> <p class="qty-desc">Price Reduced</p> </div> </div> </div> </div> <!-- ====SUBSCRIPTION==== --> <div id="contact" class="subscription"> <div class="content"> <div class="body"> <div class="info"> <h2 class="sub-title line-clamp">Subscribe to our Newsletter!</h2> <p class="desc line-clamp" style="--line-clamp:3;">Subscribe to our newsletter and stay updated.</p> <a href="#!" class="btn">Subscribe</a> </div> <img src="./assets/img/new-letter.svg" alt="Subscribe to our Newsletter!" class="image"> </div> </div> </div> <!-- ====FOOTER==== --> <footer class="footer"> <div class="content"> <div class="row row-top"> <!-- product column --> <div class="column"> <h3 class="heading">Product</h3> <ul class="list"> <li class="item"><a href="">Listing</a></li> <li class="item"><a href="">Property</a></li> <li class="item"><a href="">Agents</a></li> <li class="item"><a href="">Blog</a></li> </ul> </div> <!-- Resources column --> <div class="column"> <h3 class="heading">Resources</h3> <ul class="list"> <li class="item"><a href="">Our Homes</a></li> <li class="item"><a href="">Member Stories</a></li> <li class="item"><a href="">Video</a></li> <li class="item"><a href="">Free trial </a></li> </ul> </div> <!-- Company column --> <div class="column"> <h3 class="heading">Company</h3> <ul class="list"> <li class="item"><a href="">Patnerships</a></li> <li class="item"><a href="">Terms of use</a></li> <li class="item"><a href="">Privacy</a></li> <li class="item"><a href="">Sitemap</a></li> </ul> </div> <!-- Get in touch column --> <div class="column"> <h3 class="heading">Get in touch</h3> <p class="desc">You’ll find your next home, in any style you prefer.</p> <div class="social"> <a href="" class="social-link"><img src="./assets/img/facebook.svg" alt=""></a> <a href="" class="social-link"><img src="./assets/img/twitter.svg" alt=""></a> <a href="" class="social-link"><img src="./assets/img/in.svg" alt=""></a> </div> </div> </div> <div class="row row-bottom"> <img src="./assets/img/Logo.svg" alt="Bensnik" class="logo"> <p class="copyright">Copyright 2020.com, All rights reserved.</p> </div> </div> </footer> </main> </body> </html>
"use server"; import { RegisterProps, UserProps } from "@/types"; import axios from "axios"; import { revalidatePath } from "next/cache"; export const fetchUserData = async ({ take, skip, search, }: { take: number; skip: number; search: string | null; }) => { try { const res = await axios.get( process.env.NEXT_PUBLIC_API_URL + "/api/user/all", { params: { take, skip, search: search ? search : null, }, } ); revalidatePath("/dashboard/manage-user"); return res.data.data; } catch (error: any) { if (error.response) { return { mesasge: error.response.data.message, status: 500, }; } } }; export const fetchRoleData = async () => { try { const res = await fetch( process.env.NEXT_PUBLIC_API_URL + "/api/user/role/all", { cache: "no-cache", } ); revalidatePath("/dashboard/manage-user"); const data = await res.json(); return data.data; } catch (error: any) { if (error.response) { return { message: error.response.data.message, status: 500, }; } } }; export const fetchUserDataById = async ({ id }: { id: string }) => { try { const res = await axios.post( process.env.NEXT_PUBLIC_API_URL + `/api/user/get/${id}`, { id: id, } ); revalidatePath("/dashboard/manage-user"); return res.data.data; } catch (error: any) { if (error.response) { return { message: error.response.data.message, status: error.response.status, }; } } }; export const registerUser = async ({ name, email, profile_picture, role, shift, password, confirmPassword, }: RegisterProps) => { try { const res = await axios.post( process.env.NEXT_PUBLIC_API_URL + "/api/auth/register", { name, email, profile_picture, role, shift, password, confPassword: confirmPassword, } ); revalidatePath("/dashboard/manage-user/add-user"); revalidatePath("/dashboard/manage-user"); return { message: res.data.message, status: res.status, }; } catch (error: any) { if (error.response) { return { message: error.response.data.message, status: 500, }; } } }; export const editUserAccount = async ({ id, name, email, profile_picture, role, shift, }: UserProps) => { try { const res = await axios.patch( process.env.NEXT_PUBLIC_API_URL + `/api/user/update/${id}`, { id, name, email, profile_picture, role, shift, } ); revalidatePath("/dashboard/manage-user/edit-user"); revalidatePath("/dashboard/manage-user"); return { message: res.data.message, status: 200 }; } catch (error: any) { if (error.response) { return { message: error.response.data.message, status: 500, }; } } }; export const deleteUserAccount = async ({ id } : { id: string }) => { try { const res = await axios.post(process.env.NEXT_PUBLIC_API_URL + `/api/user/delete/${id}`, { id }); revalidatePath("/dashboard/manage-user"); return res.data } catch (error: any) { if (error.response) { return { message: error.response.data.message, status: 500, }; } } }
// portion of https://github.com/odin-lang/Odin/raw/master/examples/demo/demo.odin package main import "core:fmt" import "core:mem" import "core:os" /* The Odin programming language is fast, concise, readable, pragmatic and open sourced. It is designed with the intent of replacing C with the following goals: * simplicity * high performance * built for modern systems * joy of programming */ the_basics :: proc() { fmt.println("\n# the basics"); { // The Basics fmt.println("Hellope"); // Lexical elements and literals // A comment my_integer_variable: int; // A comment for documentaton // Multi-line comments begin with /* and end with */. Multi-line comments can // also be nested (unlike in C): /* You can have any text or code here and have it be commented. */ // Note: `:=` is two tokens, `:` and `=`. The following are equivalent, /* i: int = 123; i: = 123; i := 123; */ _ = my_integer_variable; _ = x; } } control_flow :: proc() { fmt.println("\n# control flow"); { // Control flow // For loop // Odin has only one loop statement, the `for` loop // Basic for loop for i := 0; i < 10; i += 1 { fmt.println(i); } // NOTE: Unlike other languages like C, there are no parentheses `( )` surrounding the three components. // Braces `{ }` or a `do` are always required> for i := 0; i < 10; i += 1 { } for i := 0; i < 10; i += 1 do fmt.print(); // The initial and post statements are optional i := 0; for ; i < 10; { i += 1; } // You can defer an entire block too: { bar :: proc() {} defer { fmt.println("1"); fmt.println("2"); } cond := false; defer if cond { bar(); } } // Defer statements are executed in the reverse order that they were declared: { defer fmt.println("1"); defer fmt.println("2"); defer fmt.println("3"); } // Will print 3, 2, and then 1. if false { f, err := os.open("my_file.txt"); if err != 0 { // handle error } defer os.close(f); // rest of code } } { // When statement /* The when statement is almost identical to the if statement but with some differences: * Each condition must be a constant expression as a when statement is evaluated at compile time. * The statements within a branch do not create a new scope * The compiler checks the semantics and code only for statements that belong to the first condition that is true * An initial statement is not allowed in a when statement * when statements are allowed at file scope */ // Example when ODIN_ARCH == "386" { fmt.println("32 bit"); } else when ODIN_ARCH == "amd64" { fmt.println("64 bit"); } else { fmt.println("Unsupported architecture"); } // The when statement is very useful for writing platform specific code. // This is akin to the #if construct in C’s preprocessor however, in Odin, // it is type checked. } { // Branch statements cond, cond1, cond2 := false, false, false; one_step :: proc() { fmt.println("one_step"); } beyond :: proc() { fmt.println("beyond"); } // Break statement for cond { switch { case: if cond { break; // break out of the `switch` statement } } break; // break out of the `for` statement } loop: for cond1 { for cond2 { break loop; // leaves both loops } } // Continue statement for cond { if cond2 { continue; } fmt.println("Hellope"); } // Fallthrough statement // Odin’s switch is like one in C or C++, except that Odin only runs the selected // case. This means that a break statement is not needed at the end of each case. // Another important difference is that the case values need not be integers nor // constants. // fallthrough can be used to explicitly fall through into the next case block: switch i := 0; i { case 0: one_step(); fallthrough; case 1: beyond(); } } }
from flask_cors import cross_origin from functools import wraps from flask import request, jsonify from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request, create_access_token, jwt_required from app.models import Funcion, Grupo, Productor, User, Venta from app import app, db from app.schemas import ( funcion_schema,funciones_schema, grupo_schema, grupos_schema, productor_schema, productores_schema, usuarios_schema, user_schema, venta_schema, ventas_schema ) from flask import jsonify, request from flask_security import login_user, logout_user, current_user, login_required from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy.exc import SQLAlchemyError def admin_required(fn): @wraps(fn) def wrapper(*args, **kwargs): try: verify_jwt_in_request() user_id = get_jwt_identity() user = User.query.get(user_id) user_roles = [role.name for role in user.roles] if 'administrador' in user_roles: return fn(*args, **kwargs) else: return jsonify({'message': 'Acceso no autorizado'}), 403 except Exception as e: return jsonify({'message': 'Error de autenticación'}), 401 return wrapper @app.route('/', methods=['GET']) def index(): return jsonify({'Holamundo': 'Proyecto Backend para el TPO de Codo a Codo 4.0'}) @app.route('/usuarios', methods=['GET']) def get_usuarios(): try: if request.method == 'GET': usuarios = User.query.all() usuarios_serializados = usuarios_schema.dump(usuarios) return jsonify({'usuarios': usuarios_serializados}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/funciones', methods=['GET']) def get_funciones(): if request.method == 'GET': funciones = Funcion.query.all() return jsonify({'funciones': funciones_schema.dump(funciones)}) @app.route('/funciones/<int:funcion_id>', methods=['GET']) def mostrar_funciones(funcion_id): funcion = Funcion.query.get(funcion_id) if not funcion: return jsonify({'message': 'Función no encontrada'}), 404 if request.method == 'GET': return jsonify({'funcion': funcion_schema.dump(funcion)}) @app.route('/dashboard/funciones/crear', methods=['GET', 'POST']) @admin_required def create_funciones(): if request.method == 'POST': nueva_funcion = Funcion( titulo=request.json['titulo'], fecha=request.json['fecha'], hora=request.json['hora'], imagen=request.json['imagen'], precio=request.json['precio'], activa=request.json['activa'], grupo_id=request.json['grupo_id'], productor_id=request.json['productor_id'] ) db.session.add(nueva_funcion) db.session.commit() return jsonify({'message': 'Función creada'}), 201 @app.route('/dashboard/funciones/<int:funcion_id>', methods=['GET', 'PUT', 'DELETE']) @admin_required def modify_funcion(funcion_id): funcion = Funcion.query.get(funcion_id) if not funcion: return jsonify({'message': 'Función no encontrada'}), 404 if request.method == 'GET': return jsonify({'funcion': funcion_schema.dump(funcion)}) elif request.method == 'PUT': try: funcion.titulo = request.json.get('titulo') funcion.fecha = request.json.get('fecha') funcion.hora = request.json.get('hora') funcion.imagen = request.json.get('imagen') funcion.precio = request.json.get('precio') funcion.activa = request.json.get('activa') funcion.grupo_id = request.json.get('grupo_id') funcion.productor_id = request.json.get('productor_id') db.session.commit() return jsonify({'message': 'Función actualizada', 'funcion_id': funcion.id}) except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 500 elif request.method == 'DELETE': db.session.delete(funcion) db.session.commit() return jsonify({'message': 'Función eliminada'}) @app.route('/grupos', methods=['GET']) def get_grupos(): if request.method == 'GET': grupos = Grupo.query.all() return jsonify({'grupos': grupos_schema.dump(grupos)}) @app.route('/grupos/<int:grupo_id>', methods=['GET']) def gestionar_grupo(grupo_id): grupo = Grupo.query.get(grupo_id) if not grupo: return jsonify({'message': 'Grupo no encontrado'}), 404 if request.method == 'GET': return jsonify({'grupo': grupo_schema.dump(grupo)}) @app.route('/dashboard/grupos', methods=['GET', 'POST']) @admin_required def get_grupos_admin(): if request.method == 'POST': nuevo_grupo = Grupo( nombre=request.json['nombre'], integrantes=request.json['integrantes'] ) db.session.add(nuevo_grupo) db.session.commit() return jsonify({'message': 'Grupo creado'}), 201 @app.route('/dashboard/grupos/<int:grupo_id>', methods=['GET', 'PUT', 'DELETE']) @admin_required def gestionar_grupo_admin(grupo_id): grupo = Grupo.query.get(grupo_id) if not grupo: return jsonify({'message': 'Grupo no encontrado'}), 404 if request.method == 'GET': return jsonify({'grupo': grupo_schema.dump(grupo)}) elif request.method == 'PUT': grupo.nombre = request.json['nombre'] grupo.integrantes = request.json['integrantes'] db.session.commit() return jsonify({'message': 'Grupo actualizado'}) elif request.method == 'DELETE': db.session.delete(grupo) db.session.commit() return jsonify({'message': 'Grupo eliminado'}) @app.route('/productores', methods=['GET']) def get_productores(): if request.method == 'GET': productores = Productor.query.all() return jsonify({'productores': productores_schema.dump(productores)}) @app.route('/productores/<int:productor_id>', methods=['GET']) def gestionar_productor(productor_id): productor = Productor.query.get(productor_id) if not productor: return jsonify({'message': 'Productor no encontrado'}), 404 if request.method == 'GET': return jsonify({'productor': productor_schema.dump(productor)}) @app.route('/dashboard/productores', methods=['GET', 'POST']) @admin_required def get_productores_admin(): if request.method == 'GET': productores = Productor.query.all() return jsonify({'productores': productores_schema.dump(productores)}) elif request.method == 'POST': nuevo_productor = Productor( nombre=request.json['nombre'] ) db.session.add(nuevo_productor) db.session.commit() return jsonify({'message': 'Productor creado'}), 201 @app.route('/dashboard/productores/<int:productor_id>', methods=['GET', 'PUT', 'DELETE']) @admin_required def gestionar_productor_admin(productor_id): productor = Productor.query.get(productor_id) if not productor: return jsonify({'message': 'Productor no encontrado'}), 404 if request.method == 'GET': return jsonify({'productor': productor_schema.dump(productor)}) elif request.method == 'PUT': productor.nombre = request.json['nombre'] db.session.commit() return jsonify({'message': 'Productor actualizado'}) elif request.method == 'DELETE': db.session.delete(productor) db.session.commit() return jsonify({'message': 'Productor eliminado'}) @app.route('/dashboard/usuarios', methods=['GET', 'POST']) @admin_required def get_usuarios_admin(): from app import user_datastore if request.method == 'GET': usuarios = User.query.all() return jsonify({'usuarios': usuarios_schema.dump(usuarios)}) elif request.method == 'POST': try: data = request.get_json() email = data.get('email') nombre = data.get('nombre') apellido = data.get('apellido') password = data.get('password') # Validación de datos de entrada if not email or not password: return jsonify({'message': 'Datos de usuario incompletos'}), 400 existing_user = user_datastore.find_user(email=email) if existing_user: return jsonify({'message': 'El usuario ya existe'}), 400 new_user = user_datastore.create_user( email=email, nombre=nombre, apellido=apellido, password=generate_password_hash(password) ) user_datastore.add_role_to_user(new_user, 'usuario') db.session.commit() return jsonify({'message': 'Usuario creado'}), 201 except Exception as e: return jsonify({'message': f'Error al crear usuario: {str(e)}'}), 500 @app.route('/dashboard/usuarios/<int:usuario_id>', methods=['GET', 'PUT', 'DELETE']) @admin_required def gestionar_usuario(usuario_id): from app import user_datastore usuario = User.query.get(usuario_id) if not usuario: return jsonify({'message': 'Usuario no encontrado'}), 404 if request.method == 'GET': return jsonify({'usuario': user_schema.dump(usuario)}) elif request.method == 'PUT': try: usuario = User.query.get(usuario_id) if not usuario: return jsonify({'message': 'Usuario no encontrado'}), 404 usuario.nombre = request.json['nombre'] usuario.apellido = request.json['apellido'] usuario.email = request.json['email'] db.session.commit() print('aaaaaaaaaaa') db.session.commit() return jsonify({'message': 'Usuario actualizado'}), 200 except SQLAlchemyError as e: # Manejo de errores específicos de SQLAlchemy db.session.rollback() # Revierte los cambios en caso de error print(str(e)) return jsonify({'message': f'Error de SQLAlchemy al actualizar usuario: {str(e)}'}), 500 except Exception as e: # Manejo de otros errores no especificados print(str(e)) return jsonify({'message': f'Error al actualizar usuario: {str(e)}'}), 500 elif request.method == 'DELETE': try: # Eliminar cualquier asignación de roles asociada con el usuario user_datastore.remove_role_from_user(usuario, 'usuario') user_datastore.remove_role_from_user(usuario, 'administrador') db.session.delete(usuario) db.session.commit() return jsonify({'message': 'Usuario eliminado'}), 200 except Exception as e: return jsonify({'message': f'Error al eliminar usuario: {str(e)}'}), 500 # Ruta de registro @app.route('/register', methods=['POST']) def register(): from app import user_datastore if request.method == 'POST': data = request.get_json() email = data.get('email') password = data.get('password') nombre = data.get('nombre') apellido = data.get('apellido') if not email or not password: return jsonify({'message': 'Correo electrónico y contraseña son obligatorios'}), 400 existing_user = user_datastore.find_user(email=email) if existing_user: return jsonify({'message': 'El usuario ya existe'}), 400 new_user = user_datastore.create_user( email=email, nombre=nombre, apellido=apellido, password=generate_password_hash(password) ) user_datastore.add_role_to_user(new_user, 'usuario') db.session.commit() user_roles = [role.name for role in new_user.roles] access_token = create_access_token(identity=new_user.id, additional_claims={'roles': user_roles}) return jsonify({'message': 'Registro exitoso', 'access_token': access_token}), 201 # Ruta de inicio de sesión @app.route('/login', methods=['POST']) def login(): from app import user_datastore data = request.get_json() email = data.get('email') password = data.get('password') user = user_datastore.find_user(email=email) if user and check_password_hash(user.password, password): login_user(user) user_roles = [role.name for role in user.roles] access_token = create_access_token(identity=user.id, additional_claims={'roles': user_roles}) return jsonify({'message': 'Inicio de sesión exitoso', 'access_token': access_token}), 200 else: return jsonify({'message': 'Credenciales incorrectas'}), 401 # Ruta de logout @app.route('/logout', methods=['POST']) @login_required @cross_origin(supports_credentials=True) def logout(): if current_user.is_authenticated: logout_user() return jsonify({'message': 'Cierre de sesión exitoso'}), 200 else: return jsonify({'message': 'No hay usuario autenticado'}), 401 # Ruta para usuarios logueados @app.route('/ventas', methods=['POST']) @jwt_required() def create_venta(): try: # Obtener la identidad del usuario desde el token JWT usuario_id = get_jwt_identity() nueva_venta = Venta( funcion_id=request.json['funcion_id'], productor_id=request.json['productor_id'], grupo_id=request.json['grupo_id'], usuario_id=usuario_id, fecha_venta=request.json['fecha_venta'], hora_venta=request.json['hora_venta'], monto=request.json['monto'] ) db.session.add(nueva_venta) db.session.commit() return jsonify({'message': 'Venta creada'}), 201 except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 500 # Rutas para administradores desde el dashboard @app.route('/dashboard/ventas', methods=['GET']) def get_ventas_admin(): if request.method == 'GET': ventas = Venta.query.all() return jsonify({'ventas': ventas_schema.dump(ventas)}) @app.route('/dashboard/ventas/<int:venta_id>', methods=['GET', 'PUT', 'DELETE']) @admin_required def manage_venta(venta_id): venta = Venta.query.get(venta_id) if not venta: return jsonify({'message': 'Venta no encontrada'}), 404 if request.method == 'GET': return jsonify({'venta': venta_schema.dump(venta)}) elif request.method == 'PUT': try: # Actualizar los campos necesarios venta.funcion_id = request.json.get('funcion_id') venta.productor_id = request.json.get('productor_id') venta.grupo_id = request.json.get('grupo_id') venta.usuario_id = request.json.get('usuario_id') venta.fecha_venta = request.json.get('fecha_venta') venta.hora_venta = request.json.get('hora_venta') venta.monto = request.json.get('monto') db.session.commit() return jsonify({'message': 'Venta actualizada', 'venta_id': venta.id}) except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 500 elif request.method == 'DELETE': db.session.delete(venta) db.session.commit() return jsonify({'message': 'Venta eliminada'})
import { Injectable } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { IUserGroupUsers, NewUserGroupUsers } from '../user-group-users.model'; /** * A partial Type with required key is used as form input. */ type PartialWithRequiredKeyOf<T extends { id: unknown }> = Partial<Omit<T, 'id'>> & { id: T['id'] }; /** * Type for createFormGroup and resetForm argument. * It accepts IUserGroupUsers for edit and NewUserGroupUsersFormGroupInput for create. */ type UserGroupUsersFormGroupInput = IUserGroupUsers | PartialWithRequiredKeyOf<NewUserGroupUsers>; type UserGroupUsersFormDefaults = Pick<NewUserGroupUsers, 'id'>; type UserGroupUsersFormGroupContent = { id: FormControl<IUserGroupUsers['id'] | NewUserGroupUsers['id']>; group: FormControl<IUserGroupUsers['group']>; user: FormControl<IUserGroupUsers['user']>; }; export type UserGroupUsersFormGroup = FormGroup<UserGroupUsersFormGroupContent>; @Injectable({ providedIn: 'root' }) export class UserGroupUsersFormService { createUserGroupUsersFormGroup(userGroupUsers: UserGroupUsersFormGroupInput = { id: null }): UserGroupUsersFormGroup { const userGroupUsersRawValue = { ...this.getFormDefaults(), ...userGroupUsers, }; return new FormGroup<UserGroupUsersFormGroupContent>({ id: new FormControl( { value: userGroupUsersRawValue.id, disabled: true }, { nonNullable: true, validators: [Validators.required], } ), group: new FormControl(userGroupUsersRawValue.group), user: new FormControl(userGroupUsersRawValue.user), }); } getUserGroupUsers(form: UserGroupUsersFormGroup): IUserGroupUsers | NewUserGroupUsers { return form.getRawValue() as IUserGroupUsers | NewUserGroupUsers; } resetForm(form: UserGroupUsersFormGroup, userGroupUsers: UserGroupUsersFormGroupInput): void { const userGroupUsersRawValue = { ...this.getFormDefaults(), ...userGroupUsers }; form.reset( { ...userGroupUsersRawValue, id: { value: userGroupUsersRawValue.id, disabled: true }, } as any /* cast to workaround https://github.com/angular/angular/issues/46458 */ ); } private getFormDefaults(): UserGroupUsersFormDefaults { return { id: null, }; } }
// ignore_for_file: deprecated_member_use, avoid_print import 'package:angry_coach_beta/extract/my_button.dart'; import 'package:angry_coach_beta/pages/log_in/signup3age.dart'; import 'package:angry_coach_beta/providers/user_properties_provider.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:provider/provider.dart'; class SignUp2Purpose extends StatefulWidget { const SignUp2Purpose({Key? key}) : super(key: key); @override State<SignUp2Purpose> createState() => _SignUp2PurposeState(); } class _SignUp2PurposeState extends State<SignUp2Purpose> { var box = Hive.box("userProperties"); @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, resizeToAvoidBottomInset: false, backgroundColor: Colors.white, appBar: AppBar( foregroundColor: Colors.black, elevation: 0, brightness: Brightness.light, backgroundColor: Colors.transparent, ), body: Container( decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("assets/background.png"), fit: BoxFit.cover, ), ), padding: const EdgeInsets.symmetric(horizontal: 40), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.end, children: [ const SizedBox( height: 25, ), const Text( "Benim amacım Çekirgelerime istedikler hedefe ulaşana kadar destek olmak. Peki senin hedefin ne?", textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.w600, fontSize: 22)), const SizedBox( height: 25, ), MyButton( onPressedFunction: () { setState(() { box.put("userPurpose", "Weight loss"); }); //context.read<UserProperties>().getUserDietGoal("Weight loss"); }, text: "Weight loss", buttonColor: box.get("userPurpose") == "Weight loss" ? const Color.fromARGB(255, 162, 194, 249) : Colors.white, ), const SizedBox( height: 15, ), MyButton( onPressedFunction: () { setState(() { box.put("userPurpose", "Slow weight loss"); }); // context // .read<UserProperties>() // .getUserDietGoal("Slow weight loss"); }, text: "Slow weight loss", buttonColor: box.get("userPurpose") == "Slow weight loss" ? const Color.fromARGB(255, 162, 194, 249) : Colors.white, ), const SizedBox( height: 15, ), MyButton( onPressedFunction: () { setState(() { box.put("userPurpose", "Maintain my current weight"); }); // context // .read<UserProperties>() // .getUserDietGoal("Maintain my current weight"); }, text: "Maintain my current weight", buttonColor: box.get("userPurpose") == "Maintain my current weight" ? const Color.fromARGB(255, 162, 194, 249) : Colors.white, ), const SizedBox( height: 15, ), MyButton( onPressedFunction: () { setState(() { box.put("userPurpose", "Slow weight gain"); }); // context // .read<UserProperties>() // .getUserDietGoal("Slow weight gain"); }, text: "Slow weight gain", buttonColor: box.get("userPurpose") == "Slow weight gain" ? const Color.fromARGB(255, 162, 194, 249) : Colors.white, ), const SizedBox( height: 15, ), MyButton( onPressedFunction: () { setState(() { box.put("userPurpose", "Weight gain"); }); // context.read<UserProperties>().getUserDietGoal("Weight gain"); }, text: "Weight gain", buttonColor: box.get("userPurpose") == "Weight gain" ? const Color.fromARGB(255, 162, 194, 249) : Colors.white, ), SizedBox( height: MediaQuery.of(context).size.height * 0.1, ), MyButton( onPressedFunction: () { if (box.get("userPurpose") != null) { Navigator.push( context, MaterialPageRoute(builder: (context) => const SignUp3Age()), ); // print(Provider.of<UserProperties>(context, listen: false) // .userDietGoal); debugPrint(box.toMap().toString()); } else { Fluttertoast.showToast( msg: "You have to choose your purpose.", fontSize: 18, gravity: ToastGravity.TOP, backgroundColor: Colors.white, textColor: Colors.black, timeInSecForIosWeb: 2); } }, text: "Keep meeting", buttonColor: Colors.deepOrange, ), SizedBox( height: MediaQuery.of(context).size.height * 0.07, ), ], ), ), ); } }
<template> <div> <v-container class="book" style="max-width: 1000px"> <div class="book-title"> <h2 style="color: #ef5350">THE</h2> <h1 style="color: #ef5350">HOLY BIBLE</h1> <h3 style="color: #ef5350">TRANSLATED FROM<br />THE LATIN VULGATE</h3> <h4>Diligently conferred with the Hebrew, Greek,<br />and other Editions in diverse languages.</h4> <p class="mt-8">THE OLD TESTAMENT</p> <p>First Published by the English College at Douay</p> <p>A.D. 1609 and 1610</p> <p class="my-4">and</p> <p>THE NEW TESTAMENT</p> <p>First Published by the English College at Rheims</p> <p>A.D. 1582</p> <p class="my-4">With Annotations</p> <p>The Whole Revised and Diligently Compared with<br />the Latin Vulgate by Bishop Richard Challoner A.D. 1749-1752</p> <v-divider class="my-12"></v-divider> </div> <div class="book-contents"> <h2 style="color: #ef5350">CONTENTS</h2> <v-row> <v-col cols="12" md="6"> <h3 style="color: #ef5350">THE OLD TESTAMENT</h3> <div v-for="group in oldgroups" class="mb-6"> <h4 class="font-italic">{{ group }}</h4> <p v-for="book in books.filter((i) => i.group == group)"> <router-link :to="`/bible/${book.id}`">{{ book.name }}</router-link> </p> </div> </v-col> <v-col cols="12" md="6"> <h3 style="color: #ef5350">THE NEW TESTAMENT<br />OF OUR LORD AND SAVIOR<br />JESUS CHRIST</h3> <div v-for="group in newgroups" class="mb-6"> <h4 class="font-italic">{{ group }}</h4> <p v-for="book in books.filter((i) => i.group == group)"> <router-link :to="`/bible/${book.id}`">{{ book.name }}</router-link> </p> </div> <h3 style="color: #ef5350">ADDITIONAL BOOKS</h3> <p>The Prayer of Manasses King of Judah</p> <p>The Third Book of Esdras</p> <p>The Fourth Book of Esdras</p> <p>The Prophecy of Abdias</p> <h3 style="color: #ef5350">SUPPLEMENTAL MATERIAL</h3> <p>The Preface to the Reader</p> <p>Hard Words Explicated</p> </v-col> </v-row> </div> </v-container> <header class="book-ctrl" :class="{ 'mt-12': Capacitor.isNativePlatform() }"> <v-divider style="max-width: 200px; margin-left: auto" class="mt-0 mb-3 hidden-sm-and-down"></v-divider> <v-menu offset-y> <template v-slot:activator="{ props }"> <a class="mx-2" v-bind="props">Contents</a> </template> <v-list density="compact" style="max-height: 50vh" class="mt-2"> <v-list-item link to="/bible" title="Contents"></v-list-item> <v-list-item v-for="b in books" :key="b.id" link :to="`/bible/${b.id}`" :title="b.name"></v-list-item> </v-list> </v-menu> <span class="mx-2 text-grey">Chapter</span> </header> </div> </template> <script setup lang="ts"> import { Capacitor } from "@capacitor/core"; import books from "@/assets/books.json"; import { useRoute } from "vue-router"; const route = useRoute(); let oldgroups: any = []; let newgroups: any = []; for (let book of books) { if (book.testament == "o") { if (!oldgroups.includes(book.group)) oldgroups.push(book.group); } else if (book.testament == "n") { if (!newgroups.includes(book.group)) newgroups.push(book.group); } } </script>
package org.piramalswasthya.cho.work import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import androidx.hilt.work.HiltWorker import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import dagger.assisted.Assisted import dagger.assisted.AssistedInject import org.piramalswasthya.cho.database.shared_preferences.PreferenceDao import org.piramalswasthya.cho.network.interceptors.TokenInsertTmcInterceptor import org.piramalswasthya.cho.repositories.PatientRepo import timber.log.Timber import java.net.SocketTimeoutException import java.util.Date import java.sql.Timestamp @HiltWorker class PrescripTemplateWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted params: WorkerParameters, private val patientRepo: PatientRepo, private val preferenceDao: PreferenceDao, ) : CoroutineWorker(appContext, params) { companion object { const val name = "PrescripTemplateWorker" } @RequiresApi(Build.VERSION_CODES.O) override suspend fun doWork(): Result { init() return try { val workerResult = patientRepo.downloadAndSyncPatientRecords() if (workerResult) { Timber.d("Patient Download Worker completed") Result.success() } else { Timber.d("Patient Download Worker Failed as usual!") Result.failure() } } catch (e: SocketTimeoutException) { Timber.e("Caught Exception for Patient Download worker $e") Result.retry() } } private fun init() { if (TokenInsertTmcInterceptor.getToken() == "") preferenceDao.getPrimaryApiToken()?.let{ TokenInsertTmcInterceptor.setToken(it) } } }
import { getStock, updateStock, deleteStock } from "@/lib/api/stock"; import Cors from "cors"; import initMiddleware from "@/lib/init-middleware"; import { callTokenValidate } from "@/lib/utils/token"; // Initialize the cors middleware const cors = initMiddleware( Cors({ methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], }) ); import { HttpMethod } from "@/types"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function stock(req: NextApiRequest, res: NextApiResponse) { await cors(req, res); // Validate the CORS to protect the calls await callTokenValidate(req, res); // Validate the token to protect the API switch (req.method) { case HttpMethod.GET: return getStock(req, res); case HttpMethod.PUT: return updateStock(req, res); case HttpMethod.DELETE: return deleteStock(req, res); default: res.setHeader("Allow", [ HttpMethod.GET, HttpMethod.DELETE, HttpMethod.PUT, ]); return res.status(405).end(`Method ${req.method} Not Allowed`); } }
<div align="center"> # Alura - Formação - Desenvolva seu primeiro app com Flutter ## O que foi Proposto Domine um dos frameworks de desenvolvimento mobile mais populares atualmente e, já no primeiro curso sobre Flutter, aprenda a criar aplicativos para Android e iOS. ## Mergulhe em Flutter O Flutter é um framework de desenvolvimento de aplicativos mobile, web e desktop que utiliza a linguagem de programação Dart, permitindo criar apps com facilidade. Uma das principais vantagens do Flutter no desenvolvimento mobile, é a possibilidade de utilizar uma única base de código para a criação de aplicativos que rodam em Android e iOS (conhecido como single codebase). Nesta formação, você vai percorrer uma jornada do Curso Flutter: Widgets, Stateless, Stateful, Imagens e Animações até o Curso Flutter: gerenciamento de estados com Provider para entender como criar aplicativos do zero. Ao mergulhar em cursos de Flutter completos, vamos passar por temas como: instalação das ferramentas, implementação de animações, navegação entre telas e gerenciamento de estados, além de outras habilidades que você precisa aprender para desenvolver o seu primeiro app. <!-- <div align="start"> Benefícios desta formação: * Dominar as principais bibliotecas e frameworks utilizados no mercado, como React, React Native, TypeScript, Native-base, MUI; * Utilizar o Figma para consultar o design e protótipos da aplicação; * Aprender a realizar requisições a APIs e gerenciar estados com Axios, Fetch e MobX; * Implementar rotas privadas e navegação eficiente com o React Router Dom; * Criar gráficos atraentes com a biblioteca Recharts. * Criar aplicações mobile e web de alta qualidade e desempenho. </div> --> ## O que eu fiz | :placard: Vitrine.Dev | [Minha Vitrine Dev](https://cursos.alura.com.br/vitrinedev/dyeghocunha) | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | :sparkles: Nome | **Formação Flutter** | | :label: Tecnologias | <img src="https://img.shields.io/badge/Flutter-02569B?style=for-the-badge&logo=flutter&logoColor=white"> <img src="https://img.shields.io/badge/Dart-00B4AB?style=for-the-badge&logo=dart&logoColor=white"> | | <!-- | 🎇: Bibliotecas | [Vanilla-Tilt](https://cdnjs.com/libraries/vanilla-tilt), [EXPO](https://expo.dev/), [Native-Base](https://nativebase.io/), [ReactNavigation](https://reactnavigation.org/) --> | :rocket: URL | [Projeto]() | | <!-- | :fire: Desafio | [Conheça o Challenge Alura] --> | <!-- | :laughing: Upgrades que fiz | **Foi alterado todo o conceito da proposta, mantendo os desafios do Challange...fiz igual, mas diferente** --> </div> # 💪 Sobre os Professores <div align="center"> <img src="https://github.com/DyeghoCunha/Estudo_Flutter/blob/main/assets/images/professorKako.png" alt="professor"> | :placard: Professor | [Kako (Caio Couto Moreira)](https://www.linkedin.com/in/caio-couto-moreira-638a61106/) | | ------------------- | -------------------------------------------------------------------------------------- | | :label: | [LinkedIn](https://www.linkedin.com/in/caio-couto-moreira-638a61106/) | | :label: | [GitHub](https://github.com/Kakomo) | <img src="https://github.com/DyeghoCunha/Estudo_Flutter/blob/main/assets/images/professorRicarth.png" alt="professor"> | :placard: Professor | [Ricarth Lima](http://ricarth.me/#/) | | ------------------- | ----------------------------------------------------- | | :label: | [LinkedIn](https://www.linkedin.com/in/ricarth-lima/) | | :label: | [GitHub](https://github.com/ricarthlima) | </div> ## Objetivo # 🎨 Projeto no Figma Acesse esse projeto aqui [Projeto](https://www.figma.com/file/61CRNXlUmooMttGVa0GvML/React-fullstack---Voll.med?node-id=444%3A5625&mode=dev) [//]: # (<div align="center">) [//]: # (<img src="https://github.com/DyeghoCunha/voll-mobile/blob/master/assets/image/figma1.png?raw=true" alt="projeto no Figma">) [//]: # (</div>) [//]: # () [//]: # (<div align="center">) [//]: # (<img src="https://github.com/DyeghoCunha/voll-mobile/blob/master/assets/image/figma2.png?raw=true" alt="projeto no Figma">) [//]: # (</div>) # :one: Primeiro Passo | <!-- :construction:**Em progresso** --> :white_check_mark:**Feito** Neste primeiro momento, você vai descobrir o que é o Flutter e como criar aplicativos Android e iOS com esse framework de desenvolvimento mobile, web e desktop. No Curso Flutter: Widgets, Stateless, Stateful, Imagens e Animações você vai criar o seu primeiro projeto e mergulhar em widgets, stateless, stateful e conceitos de navegação e de estado. Além disso, no Curso Flutter: Controller, navegação e estados, você vai aprender a criar formulários, validar informações, navegar entre diferentes telas em um app e explorar o Inherited Widget. ## Primeiro Curso - Flutter: Widgets, Stateless, Stateful, Imagens e Animações | :white_check_mark: <!-- :construction:--> - :white_check_mark: <!-- :construction: --> Aula 1 | Flutter e Android Studio - :white_check_mark: <!-- :construction: --> Aula 2 | Widgets - :white_check_mark: <!-- :construction: --> Aula 3 | Stateless vs Stateful - :white_check_mark: <!-- :construction: --> Aula 4 | Imagens e animações - :white_check_mark: <!-- :construction: --> Aula 5 | Boas Praticas ## Resultados do Primeiro Curso: <div align="center"> ![Meu Projeto na Semana 1](https://raw.githubusercontent.com/DyeghoCunha/Estudo_Flutter/main/assets/gifs/projeto1.gif) </div> ## Segundo Curso - Flutter: Controller, navegação e estados |:construction: <!--:white_check_mark:--> - :white_check_mark: Aula 1 | Validação e Keyboard - :white_check_mark: Aula 2 | Navegação e Rotas - :white_check_mark: Aula 3 | Conversa entre Widgets - :white_check_mark: Aula 4 | Refinando nosso Projeto ## Resultados do Segundo Curso: # :two: Segundo Passo | :construction:**Em progresso** <!-- :white_check_mark:**Feito** --> Neste segundo passo, prepare-se para mergulhos ainda mais profundos no desenvolvimento de aplicativos com Flutter e linguagem Dart. Nos conteúdos desta trilha, você vai entender o que acontece com os dados do aplicativo quando fechamos ele. Ou seja, vai trabalhar com persistência interna na criação de aplicativos, que é responsável por manter, salvar e armazenar os dados. ## Terceiro Curso - Flutter: aplicando persistência de dados | x :white_check_mark: <!-- :construction: --> - :white_check_mark: Aula 1 | Persistência Interna - :white_check_mark: Aula 2 | Lidando com Dados - :white_check_mark: Aula 3 | CRUD: ler arquivos - :white_check_mark: Aula 4 | CRUD: criar, atualizar, deletar - :white_check_mark: Aula 5 | Finalizando ## Resultados do Terceiro Curso: ## Quarto Curso - Flutter com WebApi: integrando sua aplicação | <!-- :white_check_mark: --> :construction: - :white_check_mark: Aula 1 | Projeto base e Api Rest - :white_check_mark: Aula 2 | Api Local e Interceptadores - :white_check_mark: Aula 3 | Cadastro com API - :white_check_mark: Aula 4 | Listando na Tela Inicial ## Resultados do Quarto Curso: [//]: # (<div align="center">) [//]: # () [//]: # (![Meu Projeto na Semana 1]&#40;https://raw.githubusercontent.com/DyeghoCunha/Estudo_Flutter/main/assets/gifs/projeto1.gif&#41; ) [//]: # () [//]: # (</div>) # 🤯 Minha experiência ## Projeto em Desenvolvimento ### Primeiro Passo # 🖼️ Sobre o Autor <div align="center"> <img src="https://github.com/DyeghoCunha/what_the_fox/blob/master/public/vitrinedex.png?raw=true" alt="projeto no Figma"> </div> <!-- ## ⭐ Representação do projeto em diversas telas <div align="center"> ![Demonstração]() </div> --> # 🖼️ Banner do VitrineDev <div align="center"> <img src="https://github.com/DyeghoCunha/voll-mobile/blob/master/assets/image/figma7.png?raw=true" alt="Banner para o VitriniDev"> </div> # 🖼️ Foto do Projeto <!-- <div align="center"> <img src="https://github.com/DyeghoCunha/what_the_fox/blob/master/public/PaginaInicial_288x882.png?raw=true" alt="imagem do projeto"> </div> --> <!-- @media screen and (max-width: 1024px) { .cabecalho_container{ background-color: red; } } /* Para smartphones com largura de 375px */ @media screen and (max-width: 767px) { .cabecalho_container{ background-color: blue; }
"use strict"; /****************************************************************************** * Copyright 2021 TypeFox GmbH * This program and the accompanying materials are made available under the * terms of the MIT License, which is available in the project root. ******************************************************************************/ Object.defineProperty(exports, "__esModule", { value: true }); exports.Formatting = exports.FormattingRegion = exports.DefaultNodeFormatter = exports.AbstractFormatter = void 0; const grammar_util_1 = require("../utils/grammar-util"); const syntax_tree_1 = require("../syntax-tree"); const ast_util_1 = require("../utils/ast-util"); const cst_util_1 = require("../utils/cst-util"); const stream_1 = require("../utils/stream"); class AbstractFormatter { constructor() { this.collector = () => { }; } /** * Creates a formatter scoped to the supplied AST node. * Allows to define fine-grained formatting rules for elements. * * Example usage: * * ```ts * export class CustomFormatter extends AbstractFormatter { * protected override format(node: AstNode): void { * if (isPerson(node)) { * const formatter = this.getNodeFormatter(node); * formatter.property('name').prepend(Formatting.oneSpace()); * } * } * } * ``` * @param node The specific node the formatter should be scoped to. Every call to properties or keywords will only select those which belong to the supplied AST node. */ getNodeFormatter(node) { return new DefaultNodeFormatter(node, this.collector); } formatDocument(document, params) { return this.doDocumentFormat(document, params.options); } formatDocumentRange(document, params) { return this.doDocumentFormat(document, params.options, params.range); } formatDocumentOnType(document, params) { // Format the current line after typing something return this.doDocumentFormat(document, params.options, { start: { character: 0, line: params.position.line }, end: params.position }); } get formatOnTypeOptions() { return undefined; } doDocumentFormat(document, options, range) { const map = new Map(); const collector = (node, mode, formatting) => { var _a, _b; const key = this.nodeModeToKey(node, mode); const existing = map.get(key); const priority = (_a = formatting.options.priority) !== null && _a !== void 0 ? _a : 0; const existingPriority = (_b = existing === null || existing === void 0 ? void 0 : existing.options.priority) !== null && _b !== void 0 ? _b : 0; if (!existing || existingPriority <= priority) { map.set(key, formatting); } }; this.collector = collector; this.iterateAstFormatting(document, range); const edits = this.iterateCstFormatting(document, map, options, range); return this.avoidOverlappingEdits(document.textDocument, edits); } avoidOverlappingEdits(textDocument, textEdits) { const edits = []; for (const edit of textEdits) { const last = edits[edits.length - 1]; if (last) { const currentStart = textDocument.offsetAt(edit.range.start); const lastEnd = textDocument.offsetAt(last.range.end); if (currentStart < lastEnd) { edits.pop(); } } edits.push(edit); } return edits; } iterateAstFormatting(document, range) { const root = document.parseResult.value; this.format(root); const treeIterator = (0, ast_util_1.streamAllContents)(root).iterator(); let result; do { result = treeIterator.next(); if (!result.done) { const node = result.value; const inside = this.insideRange(node.$cstNode.range, range); if (inside) { this.format(node); } else { treeIterator.prune(); } } } while (!result.done); } nodeModeToKey(node, mode) { return `${node.offset}:${node.end}:${mode}`; } insideRange(inside, total) { if (!total) { return true; } if ((inside.start.line <= total.start.line && inside.end.line >= total.end.line) || (inside.start.line >= total.start.line && inside.end.line <= total.end.line) || (inside.start.line <= total.end.line && inside.end.line >= total.end.line)) { return true; } return false; } isNecessary(edit, document) { const existing = document.getText(edit.range); return existing !== edit.newText; } iterateCstFormatting(document, formattings, options, range) { const context = { indentation: 0, options, document: document.textDocument }; const edits = []; const cstTreeStream = this.iterateCstTree(document, context); const iterator = cstTreeStream.iterator(); let lastNode; let result; do { result = iterator.next(); if (!result.done) { const node = result.value; const isLeaf = (0, syntax_tree_1.isLeafCstNode)(node); const prependKey = this.nodeModeToKey(node, 'prepend'); const prependFormatting = formattings.get(prependKey); formattings.delete(prependKey); if (prependFormatting) { const nodeEdits = this.createTextEdit(lastNode, node, prependFormatting, context); for (const edit of nodeEdits) { if (edit && this.insideRange(edit.range, range) && this.isNecessary(edit, document.textDocument)) { edits.push(edit); } } } const appendKey = this.nodeModeToKey(node, 'append'); const appendFormatting = formattings.get(appendKey); formattings.delete(appendKey); if (appendFormatting) { const nextNode = (0, cst_util_1.getNextNode)(node); if (nextNode) { const nodeEdits = this.createTextEdit(node, nextNode, appendFormatting, context); for (const edit of nodeEdits) { if (edit && this.insideRange(edit.range, range) && this.isNecessary(edit, document.textDocument)) { edits.push(edit); } } } } if (!prependFormatting && node.hidden) { const hiddenEdits = this.createHiddenTextEdits(lastNode, node, undefined, context); for (const edit of hiddenEdits) { if (edit && this.insideRange(edit.range, range) && this.isNecessary(edit, document.textDocument)) { edits.push(edit); } } } if (isLeaf) { lastNode = node; } } } while (!result.done); return edits; } createHiddenTextEdits(previous, hidden, formatting, context) { var _a; // Don't format the hidden node if it is on the same line as its previous node const startLine = hidden.range.start.line; if (previous && previous.range.end.line === startLine) { return []; } const edits = []; const startRange = { start: { character: 0, line: startLine }, end: hidden.range.start }; const hiddenStartText = context.document.getText(startRange); const move = this.findFittingMove(startRange, (_a = formatting === null || formatting === void 0 ? void 0 : formatting.moves) !== null && _a !== void 0 ? _a : [], context); const hiddenStartChar = this.getExistingIndentationCharacterCount(hiddenStartText, context); const expectedStartChar = this.getIndentationCharacterCount(context, move); const characterIncrease = expectedStartChar - hiddenStartChar; if (characterIncrease === 0) { return []; } let newText = ''; if (characterIncrease > 0) { newText = (context.options.insertSpaces ? ' ' : '\t').repeat(characterIncrease); } const lines = hidden.text.split('\n'); lines[0] = hiddenStartText + lines[0]; for (let i = 0; i < lines.length; i++) { const currentLine = startLine + i; const pos = { character: 0, line: currentLine }; if (characterIncrease > 0) { edits.push({ newText, range: { start: pos, end: pos } }); } else { const currentText = lines[i]; let j = 0; for (; j < currentText.length; j++) { const char = currentText.charAt(j); if (char !== ' ' && char !== '\t') { break; } } edits.push({ newText: '', range: { start: pos, end: { line: currentLine, // Remove as much whitespace characters as necessary // In some cases `characterIncrease` is actually larger than the amount of whitespace available // So we simply remove all whitespace characters `j` character: Math.min(j, Math.abs(characterIncrease)) } } }); } } return edits; } getExistingIndentationCharacterCount(text, context) { const tabWhitespace = ' '.repeat(context.options.tabSize); const normalized = context.options.insertSpaces ? text.replaceAll('\t', tabWhitespace) : text.replaceAll(tabWhitespace, '\t'); return normalized.length; } getIndentationCharacterCount(context, formattingMove) { let indentation = context.indentation; if (formattingMove && formattingMove.tabs) { indentation += formattingMove.tabs; } return (context.options.insertSpaces ? context.options.tabSize : 1) * indentation; } createTextEdit(a, b, formatting, context) { var _a; if (b.hidden) { return this.createHiddenTextEdits(a, b, formatting, context); } const betweenRange = { start: (_a = a === null || a === void 0 ? void 0 : a.range.end) !== null && _a !== void 0 ? _a : { character: 0, line: 0 }, end: b.range.start }; const move = this.findFittingMove(betweenRange, formatting.moves, context); if (!move) { return []; } const chars = move.characters; const lines = move.lines; const tabs = move.tabs; const existingIndentation = context.indentation; context.indentation += (tabs !== null && tabs !== void 0 ? tabs : 0); const edits = []; if (chars !== undefined) { edits.push(this.createSpaceTextEdit(betweenRange, chars, formatting.options)); } else if (lines !== undefined) { edits.push(this.createLineTextEdit(betweenRange, lines, context, formatting.options)); } else if (tabs !== undefined) { edits.push(this.createTabTextEdit(betweenRange, !!a, context)); } if ((0, syntax_tree_1.isLeafCstNode)(b)) { context.indentation = existingIndentation; } return edits; } createSpaceTextEdit(range, spaces, options) { if (range.start.line === range.end.line) { const existingSpaces = range.end.character - range.start.character; spaces = this.fitIntoOptions(spaces, existingSpaces, options); } const newText = ' '.repeat(spaces); return { newText, range }; } createLineTextEdit(range, lines, context, options) { const existingLines = range.end.line - range.start.line; lines = this.fitIntoOptions(lines, existingLines, options); const indent = context.options.insertSpaces ? ' '.repeat(context.options.tabSize) : '\t'; const nodeIndent = indent.repeat(context.indentation); const newText = `${'\n'.repeat(lines)}${nodeIndent}`; return { newText, range }; } createTabTextEdit(range, hasPrevious, context) { const indent = context.options.insertSpaces ? ' '.repeat(context.options.tabSize) : '\t'; const nodeIndent = indent.repeat(context.indentation); const minimumLines = hasPrevious ? 1 : 0; const lines = Math.max(range.end.line - range.start.line, minimumLines); const newText = `${'\n'.repeat(lines)}${nodeIndent}`; return { newText, range }; } fitIntoOptions(value, existing, options) { if (options.allowMore) { value = Math.max(existing, value); } else if (options.allowLess) { value = Math.min(existing, value); } return value; } findFittingMove(range, moves, _context) { if (moves.length === 0) { return undefined; } else if (moves.length === 1) { return moves[0]; } const existingLines = range.end.line - range.start.line; for (const move of moves) { if (move.lines !== undefined && existingLines <= move.lines) { return move; } else if (move.lines === undefined && existingLines === 0) { return move; } } // Return the last move return moves[moves.length - 1]; } iterateCstTree(document, context) { const root = document.parseResult.value; const rootCst = root.$cstNode; if (!rootCst) { return stream_1.EMPTY_STREAM; } return new stream_1.TreeStreamImpl(rootCst, node => this.iterateCst(node, context)); } iterateCst(node, context) { if (!(0, syntax_tree_1.isCompositeCstNode)(node)) { return stream_1.EMPTY_STREAM; } const initial = context.indentation; return new stream_1.StreamImpl(() => ({ index: 0 }), (state) => { if (state.index < node.children.length) { return { done: false, value: node.children[state.index++] }; } else { // Reset the indentation to the level when we entered the node context.indentation = initial; return stream_1.DONE_RESULT; } }); } } exports.AbstractFormatter = AbstractFormatter; class DefaultNodeFormatter { constructor(astNode, collector) { this.astNode = astNode; this.collector = collector; } node(node) { return new FormattingRegion(node.$cstNode ? [node.$cstNode] : [], this.collector); } nodes(...nodes) { const cstNodes = []; for (const node of nodes) { if (node.$cstNode) { cstNodes.push(node.$cstNode); } } return new FormattingRegion(cstNodes, this.collector); } property(feature, index) { const cstNode = (0, grammar_util_1.findNodeForProperty)(this.astNode.$cstNode, feature, index); return new FormattingRegion(cstNode ? [cstNode] : [], this.collector); } properties(...features) { const nodes = []; for (const feature of features) { const cstNodes = (0, grammar_util_1.findNodesForProperty)(this.astNode.$cstNode, feature); nodes.push(...cstNodes); } return new FormattingRegion(nodes, this.collector); } keyword(keyword, index) { const cstNode = (0, grammar_util_1.findNodeForKeyword)(this.astNode.$cstNode, keyword, index); return new FormattingRegion(cstNode ? [cstNode] : [], this.collector); } keywords(...keywords) { const nodes = []; for (const feature of keywords) { const cstNodes = (0, grammar_util_1.findNodesForKeyword)(this.astNode.$cstNode, feature); nodes.push(...cstNodes); } return new FormattingRegion(nodes, this.collector); } cst(nodes) { return new FormattingRegion([...nodes], this.collector); } interior(start, end) { const startNodes = start.nodes; const endNodes = end.nodes; if (startNodes.length !== 1 || endNodes.length !== 1) { return new FormattingRegion([], this.collector); } let startNode = startNodes[0]; let endNode = endNodes[0]; if (startNode.offset > endNode.offset) { const intermediate = startNode; startNode = endNode; endNode = intermediate; } return new FormattingRegion((0, cst_util_1.getInteriorNodes)(startNode, endNode), this.collector); } } exports.DefaultNodeFormatter = DefaultNodeFormatter; class FormattingRegion { constructor(nodes, collector) { this.nodes = nodes; this.collector = collector; } /** * Prepends the specified formatting to all nodes of this region. */ prepend(formatting) { for (const node of this.nodes) { this.collector(node, 'prepend', formatting); } return this; } /** * Appends the specified formatting to all nodes of this region. */ append(formatting) { for (const node of this.nodes) { this.collector(node, 'append', formatting); } return this; } /** * Sorrounds all nodes of this region with the specified formatting. * Functionally the same as invoking `prepend` and `append` with the same formatting. */ surround(formatting) { for (const node of this.nodes) { this.collector(node, 'prepend', formatting); this.collector(node, 'append', formatting); } return this; } /** * Creates a copy of this region with a slice of the selected nodes. * For both start and end, a negative index can be used to indicate an offset from the end of the array. * For example, -2 refers to the second to last element of the array. * @param start The beginning index of the specified portion of the region. If start is undefined, then the slice begins at index 0. * @param end The end index of the specified portion of the region. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the region. */ slice(start, end) { return new FormattingRegion(this.nodes.slice(start, end), this.collector); } } exports.FormattingRegion = FormattingRegion; /** * Contains utilities to easily create formatting actions that can be applied to a {@link FormattingRegion}. */ var Formatting; (function (Formatting) { /** * Creates a new formatting that tries to fit the existing text into one of the specified formattings. * @param formattings All possible formattings. */ function fit(...formattings) { return { options: {}, moves: formattings.flatMap(e => e.moves).sort(compareMoves) }; } Formatting.fit = fit; /** * Creates a new formatting that removes all spaces */ function noSpace(options) { return spaces(0, options); } Formatting.noSpace = noSpace; /** * Creates a new formatting that creates a single space */ function oneSpace(options) { return spaces(1, options); } Formatting.oneSpace = oneSpace; /** * Creates a new formatting that creates the specified amount of spaces * * @param count The amount of spaces to be inserted */ function spaces(count, options) { return { options: options !== null && options !== void 0 ? options : {}, moves: [{ characters: count }] }; } Formatting.spaces = spaces; /** * Creates a new formatting that moves an element to the next line */ function newLine(options) { return newLines(1, options); } Formatting.newLine = newLine; /** * Creates a new formatting that creates the specified amount of new lines. */ function newLines(count, options) { return { options: options !== null && options !== void 0 ? options : {}, moves: [{ lines: count }] }; } Formatting.newLines = newLines; /** * Creates a new formatting that moves the element to a new line and indents that line. */ function indent(options) { return { options: options !== null && options !== void 0 ? options : {}, moves: [{ tabs: 1, lines: 1 }] }; } Formatting.indent = indent; /** * Creates a new formatting that removes all indentation. */ function noIndent(options) { return { options: options !== null && options !== void 0 ? options : {}, moves: [{ tabs: 0 }] }; } Formatting.noIndent = noIndent; function compareMoves(a, b) { var _a, _b, _c, _d, _e, _f; const aLines = (_a = a.lines) !== null && _a !== void 0 ? _a : 0; const bLines = (_b = b.lines) !== null && _b !== void 0 ? _b : 0; const aTabs = (_c = a.tabs) !== null && _c !== void 0 ? _c : 0; const bTabs = (_d = b.tabs) !== null && _d !== void 0 ? _d : 0; const aSpaces = (_e = a.characters) !== null && _e !== void 0 ? _e : 0; const bSpaces = (_f = b.characters) !== null && _f !== void 0 ? _f : 0; if (aLines < bLines) { return -1; } else if (aLines > bLines) { return 1; } else if (aTabs < bTabs) { return -1; } else if (aTabs > bTabs) { return 1; } else if (aSpaces < bSpaces) { return -1; } else if (aSpaces > bSpaces) { return 1; } else { return 0; } } })(Formatting = exports.Formatting || (exports.Formatting = {})); //# sourceMappingURL=formatter.js.map
using System.Runtime.CompilerServices; using IPT.Common.API; using Rage; [assembly: InternalsVisibleTo("CalloutInterface")] [assembly: InternalsVisibleTo("GrammarPolice")] namespace IPT.Common.Handlers { /// <summary> /// Used for managing player status. /// </summary> public static class PlayerHandler { private static PlayerStatus status = PlayerStatus.Available; private static string callsign = "1-LINCOLN-18"; private static int callsignSetterPriority = -1; /// <summary> /// Gets the player's callsign. /// </summary> /// <returns>A string representing the player's callsign.</returns> public static string GetCallsign() { return callsign; } /// <summary> /// Gets the current player status. /// </summary> /// <returns>The player's status.</returns> public static PlayerStatus GetStatus() { return status; } /// <summary> /// Sets the player's callsign. /// </summary> /// <param name="playerCallsign">The new callsign.</param> /// <param name="priority">The priority of the caller, higher priority takes precedence.</param> internal static void SetCallsign(string playerCallsign, int priority = 0) { if (priority > callsignSetterPriority) { callsign = playerCallsign; callsignSetterPriority = priority; } } /// <summary> /// Sets the player's status. /// </summary> /// <param name="playerStatus">The new status.</param> /// <param name="sendNotification">Sends a notification when true.</param> /// <param name="handleAvailability">Update the availability based on the status..</param> internal static void SetStatus(PlayerStatus playerStatus, bool sendNotification = true, bool handleAvailability = true) { if (status == playerStatus) { return; } status = playerStatus; if (status == PlayerStatus.EnRoute) { var callout = LSPD_First_Response.Mod.API.Functions.GetCurrentCallout(); if (callout == null) { Logging.Warning("player attempted to go en route without a callout"); Game.DisplaySubtitle("There is no active or pending callout."); return; } if (LSPD_First_Response.Mod.API.Functions.GetCalloutAcceptanceState(callout) == LSPD_First_Response.Mod.Callouts.CalloutAcceptanceState.Pending) { try { LSPD_First_Response.Mod.API.Functions.AcceptPendingCallout(callout); } catch (System.Exception ex) { Logging.Error("could not accept callout", ex); } } } if (handleAvailability) { playerStatus.SetPlayerAvailability(); } if (sendNotification) { Notifications.StatusNotification(); } API.Events.FirePlayerStatusChange(playerStatus); } } }
package br.com.financeiro.api.v1.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import br.com.financeiro.api.v1.model.ContaModel; import br.com.financeiro.api.v1.model.ContaValorTotalPagoModel; import br.com.financeiro.api.v1.model.input.ContaInput; import br.com.financeiro.api.v1.model.input.ContaSituacaoInput; import br.com.financeiro.api.v1.modelmapper.ContaModelMapper; import br.com.financeiro.domain.exception.ContaNaoEncontradaException; import br.com.financeiro.domain.filter.ContaFilter; import br.com.financeiro.domain.model.Conta; import br.com.financeiro.domain.repository.ContaRepository; import br.com.financeiro.domain.service.ContaService; /** * @author: GILMAR * @since: 30 de mai. de 2024 */ @ExtendWith(MockitoExtension.class) public class ContaControllerTests { @InjectMocks private ContaController contaController; @Mock private ContaModelMapper contaModelMapper; @Mock private ContaRepository contaRepository; @Mock private ContaService contaService; private ContaInput contaInput; private Conta conta; private ContaModel contaModel; @BeforeEach void setUp() { this.contaInput = ContaInput.builder() .dataVencimento(LocalDate.of(2024, 5, 24)) .dataPagamento(LocalDate.of(2024, 5, 25)) .valor(new BigDecimal("100.00")) .descricao("CONTA DE TELEFONE") .situacao("Paga").build(); conta = new Conta(); conta.setId(1L); conta.setDataVencimento(contaInput.getDataVencimento()); conta.setDataPagamento(contaInput.getDataPagamento()); conta.setValor(contaInput.getValor()); conta.setDescricao(contaInput.getDescricao()); conta.setSituacao(contaInput.getSituacao()); contaModel = new ContaModel(); contaModel.setId(conta.getId()); contaModel.setDataVencimento(conta.getDataVencimento()); contaModel.setDataPagamento(conta.getDataPagamento()); contaModel.setValor(conta.getValor()); contaModel.setDescricao(conta.getDescricao()); contaModel.setSituacao(conta.getSituacao()); } @Test void Dado_uma_contaInput_Quando_adicionar_Entao_deve_adicionar_uma_conta() { when(this.contaModelMapper.toDomainObject(any(ContaInput.class))).thenReturn(this.conta); when(this.contaService.salvar(any(Conta.class))).thenReturn(this.conta); when(this.contaModelMapper.toModel(any(Conta.class))).thenReturn(this.contaModel); ContaModel result = contaController.adicionar(contaInput); assertEquals(this.contaModel.getId(), result.getId()); assertEquals(this.contaModel.getDataVencimento(), result.getDataVencimento()); assertEquals(this.contaModel.getDataPagamento(), result.getDataPagamento()); assertEquals(this.contaModel.getValor(), result.getValor()); assertEquals(this.contaModel.getDescricao(), result.getDescricao()); assertEquals(this.contaModel.getSituacao(), result.getSituacao()); verify(this.contaModelMapper).toDomainObject(this.contaInput); verify(this.contaService).salvar(this.conta); verify(this.contaModelMapper).toModel(this.conta); } @Test void Dado_uma_contaId_valido_Quando_buscar_Entao_deve_retornar_uma_ContaModel() { when(this.contaService.recuperar(anyLong())).thenReturn(this.conta); when(this.contaModelMapper.toModel(conta)).thenReturn(this.contaModel); ContaModel result = contaController.buscar(1L); assertEquals(this.contaModel.getId(), result.getId()); assertEquals(this.contaModel.getDataVencimento(), result.getDataVencimento()); assertEquals(this.contaModel.getDataPagamento(), result.getDataPagamento()); assertEquals(this.contaModel.getValor(), result.getValor()); assertEquals(this.contaModel.getDescricao(), result.getDescricao()); assertEquals(this.contaModel.getSituacao(), result.getSituacao()); verify(this.contaService).recuperar(1L); verify(this.contaModelMapper).toModel(conta); } @Test void Dado_uma_contaId_invalida_Quando_buscar_Entao_deve_retornar_ContaNaoEncontradaException() { when(this.contaService.recuperar(anyLong())).thenThrow(ContaNaoEncontradaException.class); assertThrows(ContaNaoEncontradaException.class, ()-> this.contaController.buscar(1589L)); } @Test void Dado_contaFilter_Quando_lista_Entao_deve_retornar_um_Page_ContaModel() { ContaFilter contaFilter = new ContaFilter(); Pageable pageable = PageRequest.of(0, 10); Page<Conta> contasPage = new PageImpl<>(Arrays.asList(conta), pageable, 1); List<ContaModel> contaModelList = Arrays.asList(contaModel); when(this.contaRepository.filtrar(any(ContaFilter.class), any(org.springframework.data.domain.Pageable.class))).thenReturn(contasPage); when(this.contaModelMapper.toCollectiomModel(any(List.class))).thenReturn(contaModelList); Page<ContaModel> result = contaController.listar(contaFilter, pageable); assertEquals(1, result.getTotalElements()); assertEquals(1, result.getContent().size()); assertEquals(this.contaModel.getId(), result.getContent().get(0).getId()); assertEquals(this.contaModel.getDataVencimento(), result.getContent().get(0).getDataVencimento()); assertEquals(this.contaModel.getDataPagamento(), result.getContent().get(0).getDataPagamento()); assertEquals(this.contaModel.getValor(), result.getContent().get(0).getValor()); assertEquals(this.contaModel.getDescricao(), result.getContent().get(0).getDescricao()); assertEquals(this.contaModel.getSituacao(), result.getContent().get(0).getSituacao()); } @Test void Dado_uma_contaId_valida_Quando_atualizarSituacao_Entao_deve_atualizar_a_situacao_da_conta() { ContaSituacaoInput contaSituacaoInput = new ContaSituacaoInput(); contaSituacaoInput.setSituacao("Cancelada"); when(this.contaService.recuperar(anyLong())).thenReturn(this.conta); this.contaController.atualizarSituacao(1L, contaSituacaoInput); verify(this.contaService).recuperar(1L); verify(this.contaService).salvar(this.conta); assertEquals("Cancelada", this.conta.getSituacao()); } @Test void Dado_uma_contaId_invalido_Quando_atualizarSituacao_Entao_deve_retornar_ContaNaoEncontradaException() { ContaSituacaoInput contaSituacaoInput = new ContaSituacaoInput(); contaSituacaoInput.setSituacao("Cancelada"); when(this.contaService.recuperar(anyLong())).thenThrow(ContaNaoEncontradaException.class); assertThrows(ContaNaoEncontradaException.class, ()-> this.contaController.atualizarSituacao(1L, contaSituacaoInput)); } @Test void Dado_periodoInicial_e_periodoInicial_Quando_totalValorPago_Entao_deve_retornar_o_total_pago_no_periodo_informado() { BigDecimal totalPago = new BigDecimal("1500.00"); when(this.contaService.recuperarValorTotalPagoPorPeriodo(any(LocalDate.class), any(LocalDate.class))).thenReturn(totalPago); ContaValorTotalPagoModel result = this.contaController.totalValorPago(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31)); assertEquals(totalPago, result.getValorTotalPago()); verify(this.contaService).recuperarValorTotalPagoPorPeriodo(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31)); } }
欽定四庫全書     經部一   周易孔義集說     易類   提要   〈臣〉等謹案周易孔義集說二十卷   國朝沈起元撰起元字子大太倉人康熙辛丑進士官至光祿寺卿是書大㫖以十翼為夫子所手著又未經秦火其書獨完故學易者必當以孔傳為主因取明髙攀龍周易孔義之名別加纂集於古今說易諸書無所偏主惟合於孔傳者即取之其篇次則仍依今本以傳象傳繋於經文之下謂易之亡不亡不係於古本之復不復王氏以傳附經亦足以資觀玩惟大象傳徃徃別自起義文言則引伸觸𩔖以闡易藴皆無容附於本卦故別出之前列三圖一為八卦方位圖一為乾坤生六子圖一為因重圖皆據繫辭説卦之文至於河圖洛書先天後天方圓諸圖則謂此陳邵之易非夫子所本有概從刪薙頗能掃除紛紜轇轕之習其中亦多能推騐舊説引伸新義如乾彖傳大明終始王注程傳朱子皆未確解起元獨取侯行果大明日也之說而證以晉彖傳之順而麗乎大明禮所云日生於東於經義頗有根據觀六三九五上九之觀我生觀其生自孔疏以動出為生而後儒遂以動作施為解之俱不免於牽強起無獨取虞翻生謂坤生民也之說尤有合於九五象傳觀民之㫖其釋大象傳比𩔖求義於字句相似而義不同者推闡更為細宻在近來說易家中亦可雲有本之學矣乾隆四十六年九月恭校上   總纂官〈臣〉紀昀〈臣〉陸錫熊〈臣〉孫士毅   總 校 官 〈臣〉 陸 費 墀   周易孔義集説   傳易源流   班固曰孔子晚而好易讀之韋編三絶而為之傳傳即十翼也自魯商瞿子木受易於孔子以授魯橋庇子庸子庸授江東馯臂子弓子弓授燕周醜子家子家授東武孫虞子乗子乗授齊田何子莊及秦燔書易為卜筮之書獨不禁故傳授者不絶〈隋書雲秦焚書周易獨以卜筮得存惟失説卦三篇後河內女子得之〉漢興田何號杜田生授東武王同子中及洛陽周王孫梁人周寛齊服生皆著易傳漢初言易者本之田生同授緇川楊何寛授同郡碭田王孫王孫授施讐及孟喜梁丘賀由是有施孟梁丘之學焉施讐傳易授張禹及琅邪魯伯禹授淮陽彭宣及沛戴崇伯授太山毛莫如琅邪邴丹後漢劉昆受施氏易於沛人戴賔傳子軼孟喜從田王孫受易喜為易章句授同郡白光及沛翟牧後漢窪丹觟陽鴻任安皆傳孟氏易梁丘賀本從太中大夫京房受易後更事田王孫傳子臨臨傳五鹿充宗及琅邪王駿充宗授平陵士孫張及沛鄧彭祖齊衡咸後漢苑升傳梁丘易以授京兆楊政京房受易梁人焦延夀房為易章句説長於災異以授東海殷嘉及河東姚平河南乘𢎞皆為郎博士由是前漢多京氏學後漢戴馮孫期魏滿並傳之費直傳易授琅邪王璜為費氏學本以古字號古文易無章句徒以彖象繫辭文言解説上下經漢成帝時劉向典校書考易説以為諸易家説皆祖田何楊叔元丁將軍大義畧同唯京氏為異向又以中古文易經校施孟梁丘三家之易經或脫去無咎悔亡唯費氏經與古文同范氏後漢書雲京兆陳元扶風馬融河南鄭衆北海鄭康成潁川荀爽並傳費氏易沛人高相治易與費直同時其易亦無章句專説隂陽災異自言出丁將軍傳至相相授子康及蘭陵毋將永為高氏學漢初立易楊氏博士宣帝復立施孟梁丘之易元帝又立京氏易費高二家不得立民間傳之後漢費氏興而高氏遂微永嘉之亂施氏梁丘之易亡孟京費之易人無傳者唯鄭康成王輔嗣所注行於世而王氏為世所重其繫辭以下王不注相承以韓康伯注續之   總論   易象自八物外有卦畫竒耦之象內外上下之象有三才之象有中爻之象有變爻之象中爻為雜物撰徳四畫內又別為兩卦而象亦隨之變爻者用九用六易之占専視變爻故爻辭已有兼變卦而言者則象亦隨變而易此皆按之卦爻核之文周孔三聖之辭而確乎不可易者非傅㑹也惟漢晉先儒以應為象雲自某爻至某爻成某卦殊屬牽強蓋應以情應非此爻之彼爻也至半離半坎之說巧而彌拙均不可用其與說卦間有互異讀易者第據辭言象如乾不為虎而據履彖則乾為虎坤不為馬而據坤彖則坤為牝馬不必泥說卦而曲為之辭也   易言六位時成又言六位而成章無無位之說王輔嗣謂初上無位謬矣伊川謂乾上九貴而無位乃爵位之位非隂陽之位隂陽竒耦豈容無也李安溪以易初二無言位當不當者獨三四五三爻言當位則所謂位者亦藉以明分位之位謂德與位稱也愚謂當位者即正之謂也初上言正者多矣豈非當位乎亦不可泥矣   伏羲之卦畫彖爻之所取既無非象矣至中正亦有象則孔聖之所創也文周繫辭以斷吉凶而所以為吉凶者其道何由孔子定之以中正而後吉凶悔吝之故得然易象何以有中正孔子以一卦分二體而以二五為中之象以六爻分隂陽之位以所乗之隂陽當位為正之象此與伏羲以⚊⚋為隂陽皆從無象中開闢出來非開天之聖人不能夫中正二字典謨以來第言虛理至孔聖傳易而遂有實象可據於是推之而無不驗按之而不可易斯亦竒兵可見一部易書無一字不著實至實而至虛故曰潔淨精微易之時義孔子發之以一卦為一時一爻又各有一爻之時於是天下萬世鉅細精粗之道無不備此即所謂時中之道也   卦變之説惟程子之論為不易蓋變為易之要義孔子繫辭傳言之詳矣要不越於隂變陽陽變隂乾坤生六子變之權輿也六十四卦以因重而得一重則六位已定必不可謂自某卦來也來氏創為錯綜之説不過正對反對之別名亦與因重之義不符易道貴交天地不交則萬物不生君臣父子夫婦兄弟朋友不交則人道滅絶故易以隂交陽陽交隂為造化之樞杻孔子更從二體六爻內以應言乎逺交以比言乎近交而後交之道始備交有善不善而吉凶悔吝生焉則又於應比之內考其中不中正不正合時義違時義以定之此所謂神而明之者也易冒天下之道而其大要不外三綱君道也臣道也父道也子道也夫道也婦道也如是而已矣但辭寄於象苟不得於象必謬於其辭謬於其辭必害於其道聖人因象立言無隻字泛設孔子釋文周之辭至簡而至精所用虛字如而字以字之字皆有深意以顯繫辭之道學者一字玩忽差以毫𨤲謬以千里害不在辭義而在世道   言易者數千家即訓辭者亦人執一説其間有義可旁通者有必不可兼及者後學淺末何所適從熟玩文義可以定之聖人之言自典謨至今不獨道無有二即文理亦萬古不異虛心涵泳聖人之情有灼然著見不可移易者所謂文在茲者此也   易者聖人教人法天之學也聖人不以不可見之天敎人而以可見之天敎人則八物是已八物皆天也天地雷風水火山澤相錯而成六十四卦使人觀象而知萬事之理皆本於天行止進退事上與下宜剛宜柔象義胥備效之為事業成之為德行故大象傳必曰以豈俟蓍筮而始顯其用哉   易之興也其於中古乎孔子斯言想見伏羲畫卦以來易之道晦也久矣連山歸藏不特後世不傳其説而孔子亦僅雲吾得坤乾焉而未言其義周禮太卜掌三易之灋一曰連山二曰歸藏三曰周易其經卦皆八其別皆六十有四想見前此祗為卜筮之用然考左氏所載筮卦占驗之妙亦據繫辭以斷當周易未作以前有畫無文所為卜筮者亦不知其若何為用意即朱子所謂如今之環珓相似耳則伏羲當日畫卦以通神明之德以𩔖萬物之情順性命之理者終如長夜於是文周起而繫之以辭而易道始興是即卜筮之用亦自文周而始神不特闡幽微顯義理剖晰也宋道士陳圖南乃言羲畫不立文字使天下之人觀其象而已能如象焉則吉凶應違其道則吉凶反後世卦畫不明易道不傳聖人於是不得已而有辭學者為道止於是而不復知有畫矣此直以文周之辭轉有妨於易道欲廢辭而觀象其誣聖實甚而後儒猶有宗之者甚矣索隱行怪之惑人也   凡例   古周易文王卦辭周公爻辭為經上下二篇孔子十翼為傳十篇各為一書費長翁始以彖象繫辭之言解上下經鄭康成合彖傳大象傳小象傳於經加彖曰象曰字王輔嗣祖之謂孔子贊爻之辭本以釋經宜相附近又取乾坤二卦文言附入加文言曰三字於首於是好古者每歎古易之亡至宋呂汲公呂東萊訂正古易十二篇朱子本義初本亦據東萊本篇次至明初修大全復析本義従程傳之序則今之行本也愚謂易之亡不亡存乎其義耳篇次分合豈直筌蹄而已哉學易者不能舍卦爻辭以求易即不能舍孔傳以解辭伊川易傳序雲未有不得其辭而通其意者余所傳者辭也然則欲得文周之辭舍孔傳其曷由王氏以傳附經用資觀玩乃學易之定法不得雲變亂今仍之唯大象傳乃孔子以卦畫二體示人觀象學易之道往往別自起義補文周未發之㫖文言則引伸觸類以闡易藴皆無容附於本卦經文之後者不敢盡同王氏也   十翼之説各家不同胡安定以上彖下彖大象小象文言上繫下繫説卦序卦雜卦為十翼似為得之茲以彖傳小象傳分附各卦經文外餘上下繫辭傳大象傳文言傳説卦傳序卦傳雜卦傳仍自為篇次   高忠憲雲易註自夫子即註即經非夫子而烏知易之所語何語哉嘗歎以為至論後之説易者第當詳繹孔傳自得經㫖王輔嗣以來卦爻下先為註釋非勦襲即岐貳甚非宜也趙復齋於乾彖有雲元亨利貞形容乾體夫子贊之其㫖甚明後學玩辭自有所得更立語言去本愈逺噫豈獨乾彖雲爾哉苟非分經合傳則經文下直不容置一辭矣茲故於卦爻辭下即附孔傳後列諸儒之説以釋孔傳向以彖曰象曰字致後儒即以孔傳為彖象則鄭氏之貽誤也今易曰為傳以正之為隂文以誌之使初學者知經傳之別知卦爻辭之為彖象開卷瞭如   易理廣大悉備不可窮殫然孔子曰易有聖人之道四焉者舉其要矣説易者專門名家古今輩出縱有純駁要皆各有所得唯焦氏京氏主於災變占驗與孔傳言義理背馳此外豈無發明經義之處乃王輔嗣一掃馬鄭程朱一掃註疏程傳本義亦互有異同易義之糾紛視他經為甚夫羣言紛挐折衷聖人孔子為萬世立極之聖人又惟此十翼為所手著韋編三絶而後成非若詩書春秋之刪訂筆削猶有難求其説者又未經秦火其書獨完則學羲文周三聖之易者自當以孔傳為主愚不揣淺陋於漢晉唐宋元明以及   本朝説易諸書概無偏主惟以合於孔傳足以旁通曲暢者即為採入名曰孔義集説以明遵孔之意其諸儒則統以時代為先後焉   漢唐人釋經一字一義凡經前人所發者必稱某氏云云不欲襲為已説可見先儒之不苟此書單辭片語必載某氏存此志也其前儒所發後儒宗之既採前説後不復贅懼複疊也   説易者千餘家其可會通互參者兼取弗遺其衷之孔傳弗符者既不復錄宜無庸置辨然有數説同而一説異有千百年遵用而忽易一解者取舎之故不得不極其所以然以別其是非以定其指歸又間有先儒所未及愚以千慮一得偶有所見統附為案以俟明者採焉   繫辭傳雲居則觀其象而玩其辭動則觀其變而玩其占學易之道盡矣子又雲假年學易可以無大過是易者教人寡過之書也蓋天下萬事之理皆有天造地設不可移易者聖人舉目皆是百姓日用不知故以易象示之使知順之則吉逆之則凶所以前民用也伏羲之所以畫文周之所以繫辭孔子所以反覆贊之無非以天道明人事憂世濟民之深意至天之所以覆地之所以載日月之所以行四時之所以運自天主之原無藉於卦畫故此書於所為河圖洛書伏羲方圓圖先天卦位圖即不敢定其真偽要之無關人事非孔子之所言俱不復載惟據孔傳萬物出乎震節為八卦方位一圖據乾天也節為乾坤生六子一圖據因重節為六十四卦因重一圖以備觀玩   繫辭傳雲雜物撰德辨是與非則非其中爻不備中爻互卦也文王卦辭周公爻辭以互體立義者其象皎然故先儒多以互體説易不可忽也今於每卦之下標明中爻互卦為觀象之助   坤彖西南得朋東北喪朋 説卦傳萬物出乎震震東方也齊乎巽巽東南也齊也者言萬物之潔齊也離也者明也萬物皆相見南方之卦也聖人南面而聴天下嚮明而治蓋取諸此也坤也者地也萬物皆致養焉故曰致役乎坤兌正秋也萬物之所説也故曰説言乎兌戰乎乾乾西北之卦也言隂陽相薄也坎者水也正北方之卦也勞卦也萬物之所歸也故曰勞乎坎   艮東北之卦也萬物之所成終而成始也故曰成言乎艮   説卦傳雲乾天也故稱乎父坤地也故稱乎母震一索而得男故謂之長男巽一索而得女故謂之長女坎再索而得男故謂之中男離再索而得女故謂之中女艮三索而得男故謂之少男兌三索而得女故謂之少女   據此可想見伏羲當日自是先畫三竒三耦迨乾坤立而後有索以索之上中下而因有長中少故説卦傳自乾健也節後皆先乾坤後六子六子以長中少為序是八卦次第乃乾一坤二震三巽四坎五離六艮七兌八井井不易邵氏以一陽一隂各生一陽一隂層累而上至三畫既成而為乾一兌二離三震四巽五坎六艮七坤八之次第則是乾坤未成而六子並見六子先成而坤母後成矣與孔聖所云不符學者宜知所從矣 <經部,易類,周易孔義集說,圖>
import { cmsToFeetInch } from '../utils'; export const MIN_AGE = 18; export const MAX_AGE = 80; export const cardTextTruncateLength = 115; if (MAX_AGE - MIN_AGE < 0 || MAX_AGE - MIN_AGE > 100) { throw new Error(`illegal age range: ${MIN_AGE} - ${MAX_AGE}`); } function freezeObjArray<T>(array: T[]): readonly Readonly<T>[] { return Object.freeze(array.map(Object.freeze)) as any; } export const MIN_HEIGHT = 122; export const MAX_HEIGHT = 211; export const validImgExts = Object.freeze(['.png', '.jpg', '.jpeg', '.jfif', '.pjpeg', '.pjp']); export function isValidImg(filename: string): boolean { const ext = filename?.substring(filename.lastIndexOf('.'))?.toLowerCase(); return validImgExts.includes(ext); } export const ageRange = Object.freeze(Array.from({ length: MAX_AGE - MIN_AGE }, (_, n) => n + MIN_AGE)); export const religions = Object.freeze([ 'Hindu', 'Jain', 'Muslim', 'Christian', 'Budhdhist', 'Sikh', 'Parsi', 'Jewish', ]); export const languages = Object.freeze([ 'Gujrati', 'Hindi', 'Kannada', 'Malyalam', 'Marathi', 'Punjabi', 'Tamil', 'Telugu', 'Urdu', ]); export const castes = freezeObjArray([ { text: 'Agarwal', value: 'Agarwal', subcastes: [] }, { text: 'Gupta', value: 'Gupta', subcastes: [] }, { text: 'Arora', value: 'Arora', subcastes: [] }, { text: 'Bania', value: 'Bania', subcastes: [] }, { text: 'Brahmin', value: 'Brahmin', subcastes: ['Brahmin Kanyakubj'] }, { text: 'Jat', value: 'Jat', subcastes: [] }, { text: 'Kayastha', value: 'Kayastha', subcastes: [] }, { text: 'Khatri', value: 'Khatri', subcastes: [] }, { text: 'Rajpoot', value: 'Rajpoot', subcastes: [] }, { text: 'Shia', value: 'Shia', subcastes: [] }, { text: 'Sunni', value: 'Sunni', subcastes: [] }, ]); export const countries = Object.freeze(['India', 'USA', 'UK', 'Austrailia']); export const states = Object.freeze([ 'Delhi', 'Chandigarh', 'Gujarat', 'Haryana', 'Kolkata', 'Maharashtra', 'Rajasthan', 'Punjab', 'Uttar Pradesh', 'West Bengal', 'Telangana', 'Madhya Pradesh', 'Andhra Pradesh', 'Tamil Nadu', 'Kerala', ]); export const profileFilters = freezeObjArray([ { title: 'Religion', items: religions }, { title: 'Caste', items: castes.map(s => s.text), }, { title: 'State', items: states, }, { title: 'Language', items: languages, }, { title: 'Country', items: countries }, ]); export const shareOptions = freezeObjArray([ { path: '/TODO', icon: 'fa-rss', img: '/images/social1.png', }, { path: '/TODO', icon: ['fab', 'facebook-f'], fab: true, img: '/images/social3.png', }, { path: '/TODO', icon: ['fab', 'twitter'], fab: true, img: '/images/social2.png', }, { path: '/TODO', icon: ['fab', 'instagram'], img: '/images/social4.png', fab: true, }, { path: '/TODO', icon: ['fab', 'linkedin'], img: '/images/social5.png', fab: true, }, ]); export const steps = freezeObjArray([ { title: 'Signup', description: 'Register for free & put up your profile', img: '/images/signup.png', }, { title: 'Connect', description: 'Select and connect with matches you like', img: '/images/connect.png', }, { title: 'Interact', description: 'Become a premium member and start conversion', img: '/images/interect.png', }, ]); export const contactOptions = freezeObjArray([ { title: 'Send Personal Messages', description: 'Send Personal Messages to Members of your Choice Unlimited', icon: 'fa-comments', }, { title: 'View Contact', description: 'View contact numbers and call or text messages', icon: 'fa-mobile', }, { title: 'See Email', description: 'Talk via emails, share more pictures, biodata, kundli etc.', icon: 'fa-envelope', }, { title: 'Get Priority Display', description: 'Of your profile on all searches', icon: 'fa-desktop', }, { title: 'Chat', description: 'Talk via emails, Share more pictures. biodata, kundli etc.', icon: 'fa-comment', }, { title: 'Marriage Proposals', description: 'See all indian marriage proposals', icon: 'fa-camera-retro', }, ]); export const bodyTypes = Object.freeze(['Fit', 'Slim', 'Curvy', 'Overweight', 'Underweight']); export const hobbies = Object.freeze(['Painting', 'Drink', 'Reading', 'Dancing', 'Cricket', 'Smoking']); export const interests = Object.freeze(['Painting', 'Drink', 'Reading', 'Dancing', 'Cricket', 'Smoking']); export const complexion = Object.freeze(['Light', 'Fair', 'Wheatish', 'Medium Brown', 'Brown', 'Dark']); export const disabilities = Object.freeze([ 'Blindness', 'Person with low vision', 'Cerebral Palsy', 'Hearing impairment', 'Leprosy cured person', 'Locomotor disability', 'Mental illness', 'Learning Disabilities (Dyslexia)', 'No', ]); export const ethenicities = Object.freeze([ 'Assamese', 'Awadhi', 'Banjara', 'Bhojpuri', 'Bengali', 'Bhil', 'Chakma', 'Deccani', 'Dhivehi', 'Dogra', 'Garhwali', 'Gujarati', 'Haryanvi', 'Kamrupi', 'Kashmiri', 'Khas', 'Konkani', 'Kumaoni', 'Kutchi', 'Maithili', 'Maldivian', 'Marathi', 'Magahi', 'Nagpuri', 'North Indian', 'Odia', 'Pahari', 'Punjabi', 'Rajasthani', 'Marwaris', 'Rohingya', 'Sindhi', 'Memons', 'Saraiki', 'Saurashtra', 'Sinhalese', 'Sylheti', 'Tanchangya', 'Tharu', ]); export const educations = freezeObjArray([ { text: 'Doctorate (Phd)', value: 'phd', level: 10, values: ['Phd in Math', 'Phd in Physics'], }, { text: "Master's", value: 'masters', level: 9, values: ['MA', 'MBA', 'MSC'], }, { text: "Bachelor's", value: 'bachelors', level: 8, values: ['BA', 'BSC'], }, { text: 'secondary', value: 'secondary', level: 2, values: ['secondary'], }, { text: 'primary', value: 'primary', level: 1, values: ['primary'], }, ]); export const workingWith = Object.freeze(['Government Department', 'Freelancer', 'Business Owner', 'Not Working']); export const companyDepartment = Object.freeze([ 'Government Department', 'Freelancer', 'Business Owner', 'Not Working', ]); export const occupations = Object.freeze(['Government Department', 'Freelancer', 'Business Owner', 'Not Working']); export const annualIncomes = Object.freeze(['Under 1 Lakh', '1 Lakh to 2 Lakh']); export const locations = Object.freeze(['Sirsa', 'Patna', 'JabalPur', 'N/A']); export const fathersStatuses = Object.freeze(['Self Employed', 'Not Working']); export const mothersStatuses = Object.freeze(['Self Employed', 'House Wife', 'Not Working']); export const cities = Object.freeze([ 'Agra', 'Varanasi', 'Sarnath', 'Lucknow', 'Allahabad', 'Fatehpur Sikri', 'Mathura', 'Ayodhya', 'Aligarh', 'Baldeo', 'Balrampur', 'Bithoor', 'Noida', 'Chitrakoot', 'Faizabad', 'Gokul', 'Gorakhpur', 'Jaunpur', 'Jhansi', 'Kannauj', 'Kanpur', 'Kaushambi', 'Kushinagar', 'Mahaban', 'Meerut', 'Rae Bareily', 'Shravasti', 'Vrindavan', 'Kapilavastu', 'Sunauli', ]); export const nativePlaces = Object.freeze(['Sirsa', 'Moradabad']); export const familyValues = Object.freeze(['Traditional', 'Open Minded']); export const familyStatuses = Object.freeze(['Upper Class', 'Middle Class', 'Lower Class']); export const religiousBeliefs = Object.freeze(['Extreme', 'Open']); export const maritalStatuses = Object.freeze(['Single', 'Divorced', 'Never Married']);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 第三层函数只在内部调用,而不加return function hd() { let n = 1 return function show() { console.log(++n) let m = 10 function sum() { console.log(++m) } sum() } // show() } let a = hd() console.log(a) a() a() a() // 只有n会递增,m不会递增 // 说明每次调用a函数,n数据会保留,m会重开 </script> </body> </html>
import type { UmbCreatedPackageDefinition, UmbCreatedPackages } from '../../types.js'; import { UMB_PACKAGE_STORE_TOKEN } from './package.store.js'; import { UmbPackageServerDataSource } from './sources/package.server.data.js'; import type { UmbPackageStore } from './package.store.js'; import { isManifestBaseType } from '@umbraco-cms/backoffice/extension-api'; import { OpenAPI } from '@umbraco-cms/backoffice/external/backend-api'; import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api'; import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api'; import type { UmbApi, ManifestBase } from '@umbraco-cms/backoffice/extension-api'; /** * A repository for Packages which mimics a tree store. * @export */ export class UmbPackageRepository extends UmbControllerBase implements UmbApi { #init!: Promise<void>; #packageStore?: UmbPackageStore; #packageSource: UmbPackageServerDataSource; #apiBaseUrl = OpenAPI.BASE; constructor(host: UmbControllerHost) { super(host); this.#packageSource = new UmbPackageServerDataSource(this); this.#init = new Promise((resolve) => { this.consumeContext(UMB_PACKAGE_STORE_TOKEN, (instance) => { this.#packageStore = instance; this.requestConfiguration(instance); this.requestRootItems(instance); this.requestPackageMigrations(instance); resolve(); }); }); } async getCreatedPackage(unique: string | undefined): Promise<UmbCreatedPackageDefinition> { if (!unique) { return this.#getEmptyCreatedPackage(); } const { data } = await this.#packageSource.getCreatedPackage(unique); if (!data) { return this.#getEmptyCreatedPackage(); } const { id, ...model } = data; return { unique: id, ...model }; } async getCreatedPackages({ skip, take }: { skip: number; take: number }): Promise<UmbCreatedPackages | undefined> { const { data } = await this.#packageSource.getCreatedPackages({ skip, take }); if (!data) return undefined; return { items: data.items?.map((item) => ({ unique: item.id, name: item.name })), total: data.total, }; } async getCreatePackageDownload(unique: string): Promise<Blob | undefined> { const { data } = await this.#packageSource.getCreatePackageDownload(unique); return data; } #getEmptyCreatedPackage(): UmbCreatedPackageDefinition { return { unique: '', name: '', packagePath: '', contentNodeId: undefined, contentLoadChildNodes: false, mediaIds: [], mediaLoadChildNodes: false, documentTypes: [], mediaTypes: [], dataTypes: [], templates: [], partialViews: [], stylesheets: [], scripts: [], languages: [], dictionaryItems: [], }; } async deleteCreatedPackage(unique: string) { const { error } = await this.#packageSource.deleteCreatedPackage(unique); return !error; } async requestConfiguration(store: UmbPackageStore) { const { data } = await this.#packageSource.getPackageConfiguration(); if (data) { store.setConfiguration(data); } } /** * Request the root items from the Data Source * @memberOf UmbPackageRepository */ async requestRootItems(store: UmbPackageStore) { if (store.isPackagesLoaded) { return; } const { data: packages } = await this.#packageSource.getRootItems(); if (packages) { // Append packages to the store but only if they have a name store.appendItems(packages.filter((p) => p.name?.length)); const extensions: ManifestBase[] = []; packages.forEach((p) => { p.extensions?.forEach((e) => { // Crudely validate that the extension at least follows a basic manifest structure // Idea: Use `Zod` to validate the manifest if (isManifestBaseType(e)) { /** * Crude check to see if extension is of type "js" since it is safe to assume we do not * need to load any other types of extensions in the backoffice (we need a js file to load) */ // Add base url if the js path is relative if ('js' in e && typeof e.js === 'string' && !e.js.startsWith('http')) { e.js = `${this.#apiBaseUrl}${e.js}`; } // Add base url if the element path is relative if ('element' in e && typeof e.element === 'string' && !e.element.startsWith('http')) { e.element = `${this.#apiBaseUrl}${e.element}`; } // Add base url if the element path api relative if ('api' in e && typeof e.api === 'string' && !e.api.startsWith('http')) { e.api = `${this.#apiBaseUrl}${e.api}`; } extensions.push(e); } }); }); store.appendExtensions(extensions); } } /** * Request the package migrations from the Data Source * @memberOf UmbPackageRepository */ async requestPackageMigrations(store: UmbPackageStore) { const { data: migrations } = await this.#packageSource.getPackageMigrations(); if (migrations) { store.appendMigrations(migrations.items); } } async saveCreatedPackage(pkg: UmbCreatedPackageDefinition) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { unique: _, ...model } = pkg; const { data } = await this.#packageSource.saveCreatedPackage(model); return data; } async updateCreatedPackage(pkg: UmbCreatedPackageDefinition): Promise<boolean> { const { unique, ...model } = pkg; const { error } = await this.#packageSource.updateCreatedPackage(unique, model); return !error; } async configuration() { await this.#init; return this.#packageStore!.configuration; } /** * Observable of root items * @memberOf UmbPackageRepository */ async rootItems() { await this.#init; return this.#packageStore!.rootItems; } /** * Observable of extensions * @memberOf UmbPackageRepository */ async extensions() { await this.#init; return this.#packageStore!.extensions; } /** * Observable of migrations * @memberOf UmbPackageRepository */ async migrations() { await this.#init; return this.#packageStore!.migrations; } } export default UmbPackageRepository;
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/estilo.css" /> <title>PCWeb2022 - Atividade de Recuperação 1</title> <style> * { font-family: Roboto, Helvetica, sans-serif; } body { background-color: #ddd; } header, main { width: 900px; margin: 0 auto; background-color: #fff; box-shadow: 3px 5px 2px #ccc; padding: 20px 10px; } main { min-height: 80vh; } header { border-radius: 15px 15px 0px 0; } header img { width: 150px; height: 150px; float: left; margin-right: 25px; } header h1 { font-size: 1.2em; margin: 0; } header h3 { margin: 5px 0 10px; font-style: italic; font-weight: normal; font-size: 1em; } header h4 { margin: 5px 0; font-weight: normal; font-size: 0.75em; } main h4 { text-align: center; } main > p { font-size: 0.8em; margin-left: 15px; } main li { margin-bottom: 20px; margin-right: 15px; line-height: 1.2em; } article { background-color: #ddd; font-size: 0.8em; box-sizing: border-box; padding: 5px 10px; line-height: 1.2em; } .destaque { background-color: #ff0; padding: 2px; font-weight: bold; } label { font-size: 0.9em; font-weight: bold; } table, table td, table th { border: 1px solid #000; font-size: 0.85em; } table td, table th { padding: 1px 10px; } table tr:nth-child(2n) { background-color: #ddd; } </style> </head> <body> <header> <img src="img/logo.jpg" alt="Centro Federal de Educação Tecnológica do Rio de Janeiro Celso Suckow da Fonseca - CEFET/RJ" /> <h1> Centro Federal de Educação Tecnológica do Rio de Janeiro - Celso Suckow da Fonseca </h1> <h3>Campus Nova Friburgo</h3> <h4>Bacharelado em Sistemas de Informação</h4> <h4>Professor Rafael Escalfoni</h4> </header> <main> <h4>Fundamentos da Web</h4> <p> Leia os enunciados das questões com atenção. Responda à tarefa no MS Teams com este arquivo completo. </p> <p> Não altere o nome das variáveis no seu script. Seu script será testado nesta página, sem adaptações. </p> <p>Boa sorte!</p> <ol> <li> <h5>Computador de bordo</h5> <p> Um novo modelo de carro, super econômico foi lançado. Ele faz 20 km com 1 litro de combustível, considere cada litro de combustível custa R$ 7,00. </p> <p> Faça um programa que pergunte ao usuário quanto de dinheiro ele tem e em seguida diga quantos litros de combustível ele pode comprar e quantos quilômetros o carro consegue andar com este tanto de combustível. </p> <p>Seu script será usado no computador de bordo do carro.</p> <fieldset> <legend>Painel</legend> <label>Informe quantos R$ dispõe</label> <input id="q01-dinheiro" type="text" placeholder="999.99" /> <button id="q01-executar">Calcular</button> <ul id="q01-result"> <!-- <li>Você abastecerá 1l</li> <li>Sua autonomia é de 1km</li> --> </ul> </fieldset> </li> <li> <h5>Calculadora de IMC</h5> <p> O índice de massa corpórea (IMC) é o cálculo que demonstra se o indivíduo está ou não em seu peso ideal. Esse cálculo é importante para avaliar os riscos de obesidade e encontrar seu peso ideal. Segundo o modelo, pessoas com IMC </p> <table> <tbody> <tr> <th>Intervalos</th> <th>Interpretação</th> </tr> <tr> <td>abaixo de 18.5</td> <td>abaixo do peso</td> </tr> <tr> <td>entre 18.5 e 24.9</td> <td>com peso normal</td> </tr> <tr> <td>entre 25.0 e 29.9</td> <td>levemente acima do peso</td> </tr> <tr> <td>entre 30.0 e 34.9</td> <td>Obesidade grau I</td> </tr> <tr> <td>entre 35.0 e 39.9</td> <td>Obesidade grau II (severa)</td> </tr> <tr> <td>acima de 40</td> <td>Obesidade grau III (mórbida)</td> </tr> </tbody> </table> <p>Implemente a calculadora de IMC abaixo</p> <p>IMC = peso/(altura ^ 2)</p> <fieldset> <legend>Calculadora de IMC</legend> <label>Informe o peso (KG)</label> <input id="q02-peso" type="text" placeholder="999.99" /> <label>Informe a altura (m)</label> <input id="q02-altura" type="text" placeholder="9.99" /> <button id="q02-executar">Calcular</button> <ul id="q02-result"> <!-- <li>Seu IMC é zzz</li> <li>Você está na faixa: "abaixo do peso"</li> --> </ul> </fieldset> </li> <li> <h5>Cálculo de probabilidades</h5> <p> A probabilidade de dar um valor em um dado é 1/6 (uma em 6). Faça um script em JavaScript que simule 1 milhão de lançamentos de dados e mostre a frequência que deu para cada número. </p> <p> Ao apertar o botão "Simular", seu programa deverá realizar 1 milhão de lançamentos aleatórios e contabilizar a frequência para cada face do dado. </p> <fieldset> <legend>Simulador</legend> <button id="q03-executar">Simular</button> <p>Resposta:</p> <table> <tbody> <tr> <th>Face</th> <th>Ocorrências</th> <th>Frequência</th> </tr> <tr> <td>1</td> <td class="face-ocorr-1"> 160223<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-1"> 16.02%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> <tr> <td>2</td> <td class="face-ocorr-2"> 169021<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-2"> 16.90%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> <tr> <td>3</td> <td class="face-ocorr-3"> 171911<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-3"> 17.19%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> <tr> <td>4</td> <td class="face-ocorr-4"> 162888<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-4"> 16.29%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> <tr> <td>5</td> <td class="face-ocorr-5"> 165017<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-5"> 16.50%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> <tr> <td>6</td> <td class="face-ocorr-6"> 171940<!-- substitua o valor exemplo pela sua resposta aqui --> </td> <td class="face-freq-6"> 17.19%<!-- substitua o valor exemplo pela sua resposta aqui --> </td> </tr> </tbody> </table> </fieldset> </li> <li> <h5>Inversor de nomes</h5> <p> Faça um programa que peça ao usuário para digitar vários nomes. Ao mandar executar, seu programa deve exibir os nomes digitados invertidos (da última letra para a primeira). </p> <fieldset> <legend>Nomes</legend> <label>Insira um nome</label> <input id="q04-nome" type="text" placeholder="Digite um nome" /> <button id="q04-add">Adicionar nome</button> <h6>Lista de Nomes Digitados</h6> <ul id="q04-nomes"> <li>Ana</li> <li>Paulo</li> <!--<li>Insira os nomes digitados nessa lista</li> --> </ul> <button id="q04-executar">Inverter</button> <h6>Lista de Nomes Invertidos</h6> <ul id="q04-nomes-invertidos"> <!--<li>Insira os nomes invertidos nessa lista</li> --> </ul> </fieldset> </li> <li> <h5>Palíndromo</h5> <p> Faça um programa que verifique se uma palavra digitada é um palíndromo. </p> <p> <em >Um palíndromo é uma palavra que quando invertida tem a mesma escrita: ARARA, OVO, ANA...</em > </p> <fieldset> <legend>Palindromista</legend> <label>Digite uma palavra</label> <input id="q05-palavra" type="text" placeholder="Digite uma palavra" /> <button id="q05-executar">Testa Palíndromo</button> <p id="q05-result"></p> </fieldset> </li> </ol> </main> <script> const btn01 = document.querySelector("#q01-executar") const btn02 = document.querySelector("#q02-executar") const btn03 = document.querySelector("#q03-executar") const btn04 = document.querySelector("#q04-executar") const btn05 = document.querySelector("#q05-executar") /***************************************** * QUESTÃO 01 */ /** * Função que retorna a quantidade de dinheiro digitada pelo usuário */ const getDinheiro = () => parseFloat(document.querySelector("#q01-dinheiro").value) || 0 /** * Função que calcula a quantidade de combustivel comprada * @param dinheiro * @return litros * obs: cada litro custa 7 reais para o exemplo * o valor inicial é só para testes */ const calcLitrosCombustivel = dinheiro => { // programe aqui a compra de combustível let abastecimento = dinheiro/7 return abastecimento //mudar essa linha! } /** * função que retorna a quantidade de km que o carro conseguirá percorrer * @param litros - quantidade de litros comprados * @return km - de autonomia do carro */ const calcAutonomia = litros => { // programe a autonomia let autonomia = litros * 20 return autonomia //mude esse valor!!! } const respondeQuestao01 = (litros, autonomia) => { const listaResp = document.querySelector("#q01-result") const liResp = `<li>Você abastecerá ${litros}l</li> <li>Sua autonomia é de ${autonomia}km</li>` listaResp.innerHTML = liResp } btn01.addEventListener("click", () => { const dinheiro = getDinheiro() const litros = calcLitrosCombustivel(dinheiro).toFixed(2) const autonomia = calcAutonomia(litros).toFixed(2) respondeQuestao01(litros, autonomia) }) /***************************************** * QUESTÃO 02 */ /** * Função que retorna o PESO digitado pelo usuário */ const getPeso = () => parseFloat(document.querySelector("#q02-peso").value) || 0 /** * Função que retorna a ALTURA digitada pelo usuário */ const getAltura = () => parseFloat(document.querySelector("#q02-altura").value) || 0 const calcIMC = (peso, altura) => { let imc = peso/(altura*altura) return imc // programe aqui } const getFaixa = imc => { if (imc<18.5) return "Abaixo do peso" if (imc>=18.5 && imc<25) return "Peso normal" if (imc>=25 && imc<30) return "Levemente acima do peso" if (imc>=30 && imc<35) return "Obesidade grau I" if (imc>=35 && imc<40) return "Obesidade grau II (severa)" return "Obesidade grau III (mórbida)" } btn02.addEventListener("click", () => { const altura = getAltura() // programe aqui const peso = getPeso() //programe aqui const imc = calcIMC(peso,altura).toFixed(2)// calcule o imc document.querySelector("#q02-result").innerHTML = `<li>Seu IMC é ${imc}</li> <li>Você está na faixa: "${getFaixa(imc)}"</li>` console.log(getFaixa(imc)) //use getFaixa para imprimir a mensagem na tela }) /***************************************** * QUESTÃO 03 */ const lancadorDados = () => Math.ceil(Math.random()*6) btn03.addEventListener("click", () => { let lances = [0,0,0,0,0,0] //6 faces do dado for(let i=0; i<1000000; i++){ lancadorDados() lances[lancadorDados()-1]++; //lance o dado //contabilize os lances } console.log(lances) // a frequencia é total de #face/total de lancamentos document.querySelector(".face-ocorr-1").innerHTML = `${lances[0]}` document.querySelector(".face-ocorr-2").innerHTML = `${lances[1]}` document.querySelector(".face-ocorr-3").innerHTML = `${lances[2]}` document.querySelector(".face-ocorr-4").innerHTML = `${lances[3]}` document.querySelector(".face-ocorr-5").innerHTML = `${lances[4]}` document.querySelector(".face-ocorr-6").innerHTML = `${lances[5]}` document.querySelector(".face-freq-1").innerHTML = `${((lances[0]/1000000)*100).toFixed(2)+'%'}` document.querySelector(".face-freq-2").innerHTML = `${((lances[1]/1000000)*100).toFixed(2)+'%'}` document.querySelector(".face-freq-3").innerHTML = `${((lances[2]/1000000)*100).toFixed(2)+'%'}` document.querySelector(".face-freq-4").innerHTML = `${((lances[3]/1000000)*100).toFixed(2)+'%'}` document.querySelector(".face-freq-5").innerHTML = `${((lances[4]/1000000)*100).toFixed(2)+'%'}` document.querySelector(".face-freq-6").innerHTML = `${((lances[5]/1000000)*100).toFixed(2)+'%'}` //atualize a tabela com seus valores }) /***************************************** * QUESTÃO 04 */ const btnAddNome = document.querySelector("#q04-add") //funcao que retorna o nome digitado const getNome = () => document.querySelector("#q04-nome").value const insereNome = nome => { const listaNomes = document.querySelector("#q04-nomes") //inserir nomes em listaNomes } const inverteNome = nome => { //programe inverte nome aqui return nome.split("").reverse().join(""); } // insere nome digitado btnAddNome.addEventListener("click", () => { const listaNomes = document.querySelector("#q04-nomes") if(getNome()) {} { listaNomes.innerHTML += `<li>${getNome()}</li>` } document.querySelector("#q04-nome").value = '' }) btn04.addEventListener("click", ()=>{ const liNomesDigitados = document.querySelectorAll("#q04-nomes li") const listaInvertido = document.querySelector("#q04-nomes-invertidos") listaInvertido.innerHTML = `` //para cada li de liNomesDigitados, inverta e insira em listaInvertido for (let i=0; i<liNomesDigitados.length; i++) { const nome = liNomesDigitados[i].textContent const nomeInvertido = inverteNome(nome) listaInvertido.innerHTML += `<li>${nomeInvertido}</li>` } }) /***************************************** * QUESTÃO 05 */ //funcao que retorna o nome digitado const getPalavra = () => document.querySelector("#q05-palavra").value const verificaPalindromo = (palavra) => { if (palavra.toUpperCase() == (palavra.split("").reverse().join("")).toUpperCase()) { return true } else return false // programe aqui } btn05.addEventListener("click", () => { const palavra = getPalavra() const resp = document.querySelector("#q05-result") if(palavra) resp.innerHTML = `A palavra ${palavra} ${(verificaPalindromo(palavra))?"é":"não é"} um palíndromo` }) </script> </body> </html>
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { MatDialog, MAT_DIALOG_DATA, MatDialogRef, MatDialogConfig } from '@angular/material/dialog'; import { Route, Router } from '@angular/router'; import { ForgotPasswordComponent } from '../forgot-password/forgot-password.component'; import { LoginComponent } from '../login/login.component'; import { PdfService } from '../services/shared/pdf.service'; import { UserService } from '../services/user.service'; import { SignupComponent } from '../signup/signup.component'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { @ViewChild('content', { static: false }) el!: ElementRef displayedColumns: string[] = ['name', 'category', 'price', 'quantity', 'total'] dataSource = [ { "id": 1, "name": "Masala Tea", "category": "Tea", "quantity": "1", "price": 30, "total": 30 } ]; data = { "id": 2, "uuid": "b293855f-5ac4-476e-87b9-97e9b6634bbb", "name": "Ritesh", "email": "ritesh@gmail.com", "contactNumber": "8219481269", "paymentMethod": "Cash", "total": 30, "productDetails": "[{\"id\":1,\"name\":\"Masala Tea\",\"category\":\"Tea\",\"quantity\":\"1\",\"price\":30,\"total\":30}]", "createdBy": "ritesh@gmail.com" }; constructor( private dialog: MatDialog, private router: Router, private userService: UserService, private pdfService: PdfService ) { } ngOnInit(): void { if (localStorage.getItem('token')) { this.userService.checkToken().subscribe({ next: (resp) => { this.router.navigate(['/cafe/dashboard']) }, error: (err) => { console.log(err) } }) } } signupAction = () => { const dialogConfig = new MatDialogConfig(); dialogConfig.width = '550px' this.dialog.open(SignupComponent, dialogConfig) } forgotPasswordAction() { const dialogConfig = new MatDialogConfig(); dialogConfig.width = '550px' this.dialog.open(ForgotPasswordComponent, dialogConfig) } loginAction = () => { const dialogConfig = new MatDialogConfig(); dialogConfig.width = '550px' this.dialog.open(LoginComponent, dialogConfig) } }
import { Injectable, inject } from '@angular/core'; import { Message, MessageService } from 'primeng/api'; type OmittedKeys = 'severity' | 'detail' | 'closable'; type MessageOptions = Omit<Message, OmittedKeys>; @Injectable({ providedIn: 'root' }) export class ToastService { private messageService = inject(MessageService); clear(): void { this.messageService.clear(); } error(message: string, options?: MessageOptions): void { this.messageService.add({ severity: 'error', detail: message, closable: true, ...options, }); } warn(message: string, options?: MessageOptions): void { this.messageService.add({ severity: 'warn', detail: message, closable: true, ...options, }); } success(message: string, options?: MessageOptions): void { this.messageService.add({ severity: 'success', detail: message, closable: true, ...options, }); } info(message: string, options?: MessageOptions): void { this.messageService.add({ severity: 'info', detail: message, closable: true, ...options, }); } }
#!/usr/bin/env python # Generic driver for the Neato XV-11 Robot Vacuum # Copyright (c) 2010 University at Albany. All right reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the University at Albany nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL VANADIUM LABS 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. """ neato_driver.py is a generic driver for the Neato XV-11 Robotic Vacuum. ROS Bindings can be found in the neato_node package. """ __author__ = "ferguson@cs.albany.edu (Michael Ferguson)" import os import usb.core as uc import usb.util as uu import time # to find libusb-1.0.dll dirWithDll = os.path.abspath(os.path.dirname(__file__)) if dirWithDll not in os.environ['PATH']: print 'Going to search for libusb-1.0.dll in ' + dirWithDll os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.abspath(os.path.dirname(__file__)) BASE_WIDTH = 248 # millimeters MAX_SPEED = 300 # millimeters/second xv11_analog_sensors = [ "WallSensorInMM", "BatteryVoltageInmV", "LeftDropInMM", "RightDropInMM", "RightMagSensor", "LeftMagSensor", "XTemp0InC", "XTemp1InC", "VacuumCurrentInmA", "ChargeVoltInmV", "NotConnected1", "BatteryTemp1InC", "NotConnected2", "CurrentInmA", "NotConnected3", "BatteryTemp0InC" ] xv11_digital_sensors = [ "SNSR_DC_JACK_CONNECT", "SNSR_DUSTBIN_IS_IN", "SNSR_LEFT_WHEEL_EXTENDED", "SNSR_RIGHT_WHEEL_EXTENDED", "LSIDEBIT", "LFRONTBIT", "RSIDEBIT", "RFRONTBIT" ] xv11_motor_info = [ "Brush_MaxPWM", "Brush_PWM", "Brush_mVolts", "Brush_Encoder", "Brush_RPM", "Vacuum_MaxPWM", "Vacuum_PWM", "Vacuum_CurrentInMA", "Vacuum_Encoder", "Vacuum_RPM", "LeftWheel_MaxPWM", "LeftWheel_PWM", "LeftWheel_mVolts", "LeftWheel_Encoder", "LeftWheel_PositionInMM", "LeftWheel_RPM", "RightWheel_MaxPWM", "RightWheel_PWM", "RightWheel_mVolts", "RightWheel_Encoder", "RightWheel_PositionInMM", "RightWheel_RPM", "Laser_MaxPWM", "Laser_PWM", "Laser_mVolts", "Laser_Encoder", "Laser_RPM", "Charger_MaxPWM", "Charger_PWM", "Charger_mAH" ] xv11_charger_info = [ "FuelPercent", "BatteryOverTemp", "ChargingActive", "ChargingEnabled", "ConfidentOnFuel", "OnReservedFuel", "EmptyFuel", "BatteryFailure", "ExtPwrPresent", "ThermistorPresent[0]", "ThermistorPresent[1]", "BattTempCAvg[0]", "BattTempCAvg[1]", "VBattV", "VExtV", "Charger_mAH", "MaxPWM" ] NEATO_DEVICE = None INTERVAL = 0.05 def getAllUSBDevices(): return [i for i in uc.find(find_all=True)] def getNeatoDevice(): global NEATO_DEVICE if NEATO_DEVICE is None: idVendor=0x2108 idProduct=0x780b NEATO_DEVICE = uc.find(idVendor=idVendor, idProduct=idProduct) if NEATO_DEVICE is None: err = "could not find your device using vendor {} and product {}, please check that it is configured and installed correctly.".format(hex(idVendor), hex(idProduct)) print err raise Exception('no neato found: ' + err) else: print 'found neato, product/manufacturer:{}, {}'.format(NEATO_DEVICE.product, NEATO_DEVICE.manufacturer) return NEATO_DEVICE class NeatoUSB(): def __init__(self): self.device = getNeatoDevice() self.d = self.device self.d.set_configuration() def write(self, data): self.device.write(1, data) time.sleep(INTERVAL) def read(self, count=1): return ''.join([chr(x) for x in self.device.read(0x81, count)]) def readline(self): chars = [] chars.append(self.read(1)) while chars[-1] != '\n': chars.append(self.read(1)) return ''.join(chars) def flushInput(self): l = self.readline() while l: try: l = self.readline() except: return class xv11(): def __init__(self): self.port = NeatoUSB() # Storage for motor and sensor information self.state = {"LeftWheel_PositionInMM": 0, "RightWheel_PositionInMM": 0} self.stop_state = True # turn things on self.setTestMode("on") self.setLDS("on") # show off a bit distance = 25 self.setMotors(distance, -distance, 200) self.setMotors(-distance, distance, 200) # some alerts self.sound(3) self.sound(6) def exit(self): self.setLDS("off") self.setTestMode("off") def playSound(self, number): return self.command('playsound {}'.format(number)) def sound(self, number): return self.playSound(number) def setTestMode(self, value="on"): """ Turn test mode on/off. """ return self.command("testmode " + value) @property def LDS(self): return self.noLDS() def commands(self): return self.command('help') @LDS.setter def LDS(self, a): return self.setLDS("on" if a else "off") def noLDS(self): return self.setLDS("off") def setLDS(self, value="on"): return self.command("setldsrotation " + value) def requestScan(self): """ Ask neato for an array of scan reads. """ self.port.flushInput() return self.command("getldsscan") def getScanRanges(self): """ Read values of a scan -- call requestScan first! """ ranges = list() angle = 0 try: line = self.port.readline() except: return [] while line.split(",")[0] != "AngleInDegrees": try: line = self.port.readline() except: return [] while angle < 360: try: vals = self.port.readline() except: pass vals = vals.split(",") #print angle, vals try: a = int(vals[0]) r = int(vals[1]) ranges.append(r/1000.0) except: ranges.append(0) angle += 1 return ranges def turnRight(self, degrees, speed=200): ratio = 390.0 / 180 return self.setMotors(int(degrees*ratio), int(-degrees*ratio), speed) def turnLeft(self, degrees, speed=200): return self.turnRight(-degrees, speed) def turnAndBack(self, degrees, speed=200): a = self.turnRight(degrees, speed) time.sleep(3.0) b = self.turnLeft(degrees, speed) time.sleep(3.0) def setMotors(self, l, r, s): """ Set motors, distance left & right + speed """ #This is a work-around for a bug in the Neato API. The bug is that the #robot won't stop instantly if a 0-velocity command is sent - the robot #could continue moving for up to a second. To work around this bug, the #first time a 0-velocity is sent in, a velocity of 1,1,1 is sent. Then, #the zero is sent. This effectively causes the robot to stop instantly. if (int(l) == 0 and int(r) == 0 and int(s) == 0): if (not self.stop_state): self.stop_state = True l = 1 r = 1 s = 1 else: self.stop_state = False return self.command("setmotor "+str(int(l))+" "+str(int(r))+" "+str(int(s))) def getMotors(self): """ Update values for motors in the self.state dictionary. Returns current left, right encoder values. """ self.port.flushInput() return self.command("getmotors") line = self.port.readline() while line.split(",")[0] != "Parameter": try: line = self.port.readline() except: return [0,0] for i in range(len(xv11_motor_info)): try: values = self.port.readline().split(",") self.state[values[0]] = int(values[1]) except: pass return [self.state["LeftWheel_PositionInMM"],self.state["RightWheel_PositionInMM"]] def getAnalogSensors(self): """ Update values for analog sensors in the self.state dictionary. """ lines = self.command("getanalogsensors").splitlines() for index, line in enumerate(lines): if "SensorName" in line: break for line in lines[index+1:]: values = line.split(',') self.state[values[0]] = int(values[1]) def getDigitalSensors(self): """ Update values for digital sensors in the self.state dictionary. """ lines = self.command("getdigitalsensors").splitlines() for index, line in enumerate(lines): if "Digital Sensor Name" in line: break for line in lines[index+1:]: values = line.split(",") self.state[values[0]] = int(values[1]) def command(self, command): self.port.write(command + '\n') lines = [] l = self.port.readline() lines.append(l) while l: try: l = self.port.readline() lines.append(l) except: return ''.join(lines) return ''.join(lines) def howto(self, command): return self.command('help ' + command) def getCharger(self): """ Update values for charger/battery related info in self.state dictionary. """ return self.command("getcharger") line = self.port.readline() while line.split(",")[0] != "Label": line = self.port.readline() for i in range(len(xv11_charger_info)): values = self.port.readline().split(",") try: self.state[values[0]] = int(values[1]) except: pass def setBacklight(self, value=1): if value > 0: return self.command("setled backlighton") else: return self.command("setled backlightoff") def shell(self): command = raw_input('NEATO->>:').lower().encode('utf-8') print repr(command) while command not in ['q', 'quit']: print self.command(command) command = raw_input('NTO->>:').lower().encode('utf-8') #SetLED - Sets the specified LED to on,off,blink, or dim. (TestMode Only) #BacklightOn - LCD Backlight On (mutually exclusive of BacklightOff) #BacklightOff - LCD Backlight Off (mutually exclusive of BacklightOn) #ButtonAmber - Start Button Amber (mutually exclusive of other Button options) #ButtonGreen - Start Button Green (mutually exclusive of other Button options) #LEDRed - Start Red LED (mutually exclusive of other Button options) #LEDGreen - Start Green LED (mutually exclusive of other Button options) #ButtonAmberDim - Start Button Amber Dim (mutually exclusive of other Button options) #ButtonGreenDim - Start Button Green Dim (mutually exclusive of other Button options) #ButtonOff - Start Button Off
import Image from 'next/image'; import { client } from '../../../../lib/sanity.client'; import { groq } from 'next-sanity'; import urlFor from '../../../../lib/urlFor'; import { PortableText } from '@portabletext/react'; import { RichTextComponents } from '../../../../components/RichTextComponents'; import { getFormattedDate } from '@/utils'; import Link from 'next/link'; type Props = { params: { slug: string } }; export const revalidate = 60; // Revalidate this page every 60 seconds export async function generateStaticParams() { const query = groq` *[_type=='post'] { slug }`; const slugs: Post[] = await client.fetch(query); const slugRoutes = slugs.map((slug) => slug.slug.current); return slugRoutes.map((slug) => ({ slug: slug })); } async function Post({ params: { slug } }: Props) { const query = groq` *[_type=='post' && slug.current == $slug][0] { ..., body[]{ ..., markDefs[]{ ..., _type == "internalLink" => { "contentType": @.reference->_type, "slug": @.reference->slug } } }, author->, categories[]-> }`; const post: Post = await client.fetch(query, { slug }); const imageAltTags = post.imageAltText; const formattedDate = getFormattedDate(post._createdAt); return ( <article className="px-4 my-14 flex flex-col justify-start items-center"> <div className="flex justify-center items-center py-4"> {post.categories.map((category) => ( <div key={category._id} className="border rounded-md border-secondary text-secondary text-sm p-2 mx-2" > {category.title} </div> ))} </div> <div className="relative w-full h-96 md:h-[450px] cursor-pointer"> <Image className="object-contain object-center" src={urlFor(post.mainImage).url()} alt={imageAltTags} fill /> </div> <div className="text-secondary text-xl font-semibold m-0 uppercase pt-[30px] text-center"> {post.title} </div> <div className="text-neutral m-0 text-large pt-[30px] text-center "> {post.description} </div> <div className="text-secondary capitalize text-center mt-[30px]"> <p className="font-semibold text-center">{`By ${post.author.name}`}</p> <p className="font-extralight text-center">{formattedDate}</p> </div> <div className="text-neutral m-[30px] text-lg px-4 lg:px-36"> <PortableText value={post.body} components={RichTextComponents} /> </div> <div id="cta" className=" text-neutral text-xl p-2 md:px-24 text-center mx-2 my-4 uppercase" > If you liked reading this post, please share it with your fellow gym bros, and friends who you would like to see in the gym! Follow us on Instagram <Link href="https://www.instagram.com/gainssupply.mag/" className="text-accent" > {' '} @gainssupply.mag </Link> , to stay updated with the latest content! </div> <div id="disclaimer" className="border rounded-md border-secondary text-secondary text-sm p-2 mx-2 mt-8" > <p> All information posted on this website is for the purpose of sharing personal experiences and thoughts only. Do not take any of this as advice. Anything tried, would be at your own risk. The author and the website will not accept any responsibility for any liability/harm caused. </p> </div> </article> ); } export default Post;
# Created by asetti2002 at 2024/05/01 20:12 # leetgo: 1.4.3 # https://leetcode.com/problems/minimize-the-maximum-of-two-arrays/ from typing import * from leetgo_py import * # @lc code=begin class Solution: def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int: low = max(divisor1 + 1, divisor2 + 1) high = 10**9 while low < high: mid = (low + high) // 2 arr1 = set([mid - i for i in range(uniqueCnt1)]) arr2 = set([mid + i for i in range(uniqueCnt2)]) if any(num % divisor1 == 0 for num in arr1) or any(num % divisor2 == 0 for num in arr2) or len(arr1.intersection(arr2)) > 0: low = mid + 1 else: high = mid return low # @lc code=end if __name__ == "__main__": divisor1: int = deserialize("int", read_line()) divisor2: int = deserialize("int", read_line()) uniqueCnt1: int = deserialize("int", read_line()) uniqueCnt2: int = deserialize("int", read_line()) ans = Solution().minimizeSet(divisor1, divisor2, uniqueCnt1, uniqueCnt2) print("\noutput:", serialize(ans, "integer"))
package com.example.wastemanagement import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.firestore.FirebaseFirestore class BuyerHomeFragment : Fragment() { private lateinit var newRequestRecyclerView: RecyclerView private val firestore = FirebaseFirestore.getInstance() private val requestsCollection = firestore.collection("requests") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_buyer_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var auth = FirebaseAuth.getInstance() val userId = auth.currentUser loadUserName(userId,view) super.onViewCreated(view, savedInstanceState) newRequestRecyclerView = view.findViewById(R.id.newRequestRecyclerView) val newRequestAdapter = RequestAdapterBuyer() setupRecyclerView(newRequestRecyclerView, newRequestAdapter) loadRequests(newRequestAdapter) } private fun setupRecyclerView(recyclerView: RecyclerView, adapter: RequestAdapterBuyer) { recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.adapter = adapter } private fun loadUserName(userId: FirebaseUser?, view: View) { val db = FirebaseFirestore.getInstance() val userRef = db.collection("Buyers").document(userId?.uid ?: "") val textViewGreeting = view.findViewById<TextView>(R.id.textViewGreeting) userRef.get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { val userName = documentSnapshot.getString("Name") if (!userName.isNullOrEmpty()) { val greeting = "Hi $userName!" Log.d("BuyerHomeFragment", "Greeting: $greeting") // Update UI on the main thread activity?.runOnUiThread { textViewGreeting.text = greeting } } } } } private fun loadRequests( newRequestAdapter: RequestAdapterBuyer ) { val auth = FirebaseAuth.getInstance() val userId = auth.currentUser?.uid ?: return val newRequestsQuery = requestsCollection .whereEqualTo("buyerId", userId) .whereIn("status", listOf("pending")) newRequestsQuery.get().addOnCompleteListener { newRequestsTask -> if (newRequestsTask.isSuccessful) { val newRequests = newRequestsTask.result?.toObjects(Request::class.java) ?: emptyList() newRequestAdapter.submitList(newRequests) } } } }
import React from "react"; import { Link } from "react-router-dom"; import { useState } from "react"; const signUpRequest = (setIsHidden, setMessage) => (e) => { e.preventDefault(); let email = e.nativeEvent.srcElement[1].value let password = e.nativeEvent.srcElement[2].value let confirmPassword = e.nativeEvent.srcElement[3].value if (password !== confirmPassword){ const message = "Password must be identical with Confirm Password" setMessage(message) setIsHidden(false) } else{ fetch("http://localhost:4000/user/signup", { method:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( { email:email, password: password, userType: "restaurant" } ) }).then(async data => { const message = await data.text() if (data.status === 200){ setIsHidden(true) localStorage.setItem("jwtToken", message) window.location = "/RestaurantDataInitializer" } else{ setIsHidden(false) setMessage(message) } }) .catch(err => { console.error(err) setIsHidden(false) }) } } const RestaurantSignUp = () => { const [isHidden, setIsHidden] = useState(true); const [message, setMessage] = useState("") return( <main className="pa4 black-80 App"> <form className="measure center" onSubmit={signUpRequest(setIsHidden, setMessage)}> <fieldset id="sign_up" className="ba b--transparent ph0 mh0"> <legend className="f4 fw6 ph0 mh0">Sign Up</legend> <div className="mt3"> <label className="db fw6 lh-copy f6" htmlFor="email-address">Username</label> <input className="pa2 input-reset ba b--black bg-transparent hover-black w-100" type="text" name="email-address" id="email-address" /> </div> <div className="mt3"> <label className="db fw6 lh-copy f6" htmlFor="password">Password</label> <input className="b pa2 input-reset ba b--black bg-transparent hover-black w-100" type="password" name="password" id="password" /> </div> <div className="mt3"> <label className="db fw6 lh-copy f6" htmlFor="confirm-password">Confirm Password</label> <input className="b pa2 input-reset ba b--black bg-transparent hover-black w-100" type="password" name="confirm-password" /> <p className="dark-red" hidden = {isHidden}>{message}</p> </div> </fieldset> <div> <input className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib" type="submit" value="Sign Up" /> </div> <div className="lh-copy mt3"> <label className="db fw6 lh-copy f6">Do you already have an account?</label> <Link to={"/RestaurantSignIn"} className="f6 link dim black db"> Sign in </Link> </div> </form> </main> ); } export default RestaurantSignUp;
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:music/screens/albums/controller.dart'; class AlbumsScreen extends StatefulWidget { const AlbumsScreen({super.key}); @override State<AlbumsScreen> createState() => _AlbumsScreenState(); } class _AlbumsScreenState extends State<AlbumsScreen> { final controller = AlbumsController(); @override Widget build(BuildContext context) { return GridView.builder( padding: EdgeInsetsDirectional.only(top: 22.h, start: 20.w, end: 20.w), itemCount: controller.models.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( mainAxisExtent: 207.h, mainAxisSpacing: 20.h, crossAxisSpacing: 24.w, crossAxisCount: 2), itemBuilder: (context, index) => SizedBox( height: 207.h, width: 156.w, child: Column( children: [ Image.asset( controller.models[index].imgUrl, width: MediaQuery.of(context).size.width, height: 156.h, fit: BoxFit.fill, ), SizedBox( height: 12.h, ), Row( children: [ Text( controller.models[index].title, style: TextStyle( fontSize: 11.sp, fontWeight: FontWeight.w400, color: const Color(0xffEEEEEE)), ), const Spacer(), PopupMenuButton( color: const Color(0xff383B49), child: const Icon( Icons.more_vert, color: Colors.white, ), itemBuilder: (context) => List.generate( controller.popupItems.length, (index) => PopupMenuItem( child: Text( controller.popupItems[index], style: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.w400, color: const Color(0xffEEEEEE)), )))) ], ), Row( children: [ Text( controller.models[index].subTitle, style: TextStyle( fontSize: 11.sp, fontWeight: FontWeight.w400, color: const Color(0xffC1C0C0)), ), Padding( padding: EdgeInsetsDirectional.symmetric(horizontal: 10.w), child: CircleAvatar( radius: 1.5.r, backgroundColor: Colors.white.withOpacity(0.8), ), ), Expanded( child: Text( '${controller.models[index].numberOfSongs} songs', style: TextStyle( fontSize: 11.sp, fontWeight: FontWeight.w400, color: const Color(0xffC1C0C0), overflow: TextOverflow.ellipsis), ), ), ], ) ], ), ), ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GardenGlory.Context; using GardenGlory.EfClasses; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.ValueGeneration; namespace GardenGlory.EfCode.Configuration { public class RoleConfig: IEntityTypeConfiguration<Role> { public void Configure(EntityTypeBuilder<Role> builder) { builder.ToTable("Role"); // name of table builder.HasKey(c => c.RoleId); // primary key builder.Property(c => c.RoleId).HasValueGenerator(typeof(RoleKeyGenerator)); // generate values builder.HasOne(c => c.AccessRestrictionLink).WithMany(c => c.Roles).HasForeignKey(c => c.RestrictionId); } } public class RoleKeyGenerator : ValueGenerator { protected override object NextValue(EntityEntry entry) { var context = new GardenGloryContext(); var key = new StringBuilder(); var num = (context.Roles.Count() + 1).ToString(); key.Append("RL "); key.Append($"{num.PadLeft(4, '0')}"); return key.ToString(); } public override bool GeneratesTemporaryValues => false; } }
from django.http import HttpResponse from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.conf import settings from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination from djoser.views import UserViewSet from djoser.serializers import SetPasswordSerializer from users.models import CustomUser, Follow from recipes.models import (Tag, Ingredient, Recipe, Favorite, ShoppingList, IngredientsAmount) from api.serializers import (CustomUserSerializer, IngredientSearchSerializer, TagSerializer, RecipeSerializer, RecipeCreateSerializer, SubscriptionPageSerializer, ShortRecipeSerializer) from api.mixins import AddDeleteMixin from api.filters import RecipeFilter, IngredientFilter from api.permissions import AuthorOrReadOnly class BasePermissionViewSet(viewsets.ModelViewSet): def get_permissions(self): if self.action in ('list', 'retrieve'): return [AllowAny()] elif self.action in ('create', 'update', 'partial_update', 'destroy'): return [IsAdminUser()] return super().get_permissions() class CustomUserViewSet(UserViewSet, AddDeleteMixin): pagination_class = PageNumberPagination queryset = CustomUser.objects.all() def get_serializer_class(self): if self.action == 'set_password': return SetPasswordSerializer return CustomUserSerializer @action( detail=True, methods=('post', 'delete'), url_path='subscribe', permission_classes=(IsAuthenticated,), ) def subscribe_unsubscribe(self, request, id=None): author = get_object_or_404(CustomUser, id=id) return self.add_delete( request=request, model=Follow, serializer_class=SubscriptionPageSerializer, error_message={ 'post': 'Вы уже подписаны на автора.', 'delete': 'Вы не подписаны на автора.' }, success_message='Вы успешно отписались от автора.', item=author, field_name='author' ) @action( detail=False, methods=('get',), url_path='subscriptions', permission_classes=(IsAuthenticated,) ) def my_subscriptions(self, request): user = request.user subscriptions = CustomUser.objects.filter(following__user=user) paginated_subscriptions = self.paginate_queryset(subscriptions) serializer = ( SubscriptionPageSerializer( paginated_subscriptions, many=True, context={'request': request} ) ) return self.get_paginated_response(serializer.data) class IngredientViewSet(BasePermissionViewSet): queryset = Ingredient.objects.all() serializer_class = IngredientSearchSerializer filter_backends = (DjangoFilterBackend,) filterset_class = IngredientFilter pagination_class = None class TagViewSet(BasePermissionViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer pagination_class = None class RecipeViewSet(viewsets.ModelViewSet, AddDeleteMixin): queryset = Recipe.objects.all() pagination_class = PageNumberPagination permission_classes = (AuthorOrReadOnly,) filter_backends = (DjangoFilterBackend,) filterset_class = RecipeFilter def get_serializer_class(self): if self.action in ('list', 'retrieve'): return RecipeSerializer return RecipeCreateSerializer @action( detail=True, methods=('post', 'delete'), url_path='favorite', permission_classes=(IsAuthenticated,) ) def favorite(self, request, pk=None): recipe = get_object_or_404(Recipe, id=pk) return self.add_delete( request=request, model=Favorite, serializer_class=ShortRecipeSerializer, error_message={ 'post': 'Рецепт уже в избранном.', 'delete': 'Рецепт не в избранном.' }, success_message='Рецепт успешно удален из избранного.', item=recipe, field_name='recipe' ) @action( detail=True, methods=('post', 'delete'), url_path='shopping_cart', permission_classes=(IsAuthenticated,) ) def shopping_list(self, request, pk=None): recipe = get_object_or_404(Recipe, id=pk) return self.add_delete( request=request, model=ShoppingList, serializer_class=ShortRecipeSerializer, error_message={ 'post': 'Рецепт уже в списке покупок.', 'delete': 'Рецепт не в списке покупок.' }, success_message='Рецепт успешно удален из списка покупок.', item=recipe, field_name='recipe' ) @action( methods=('get',), detail=False, url_path='download_shopping_cart', permission_classes=(IsAuthenticated,) ) def download_shopping_cart_list(self, request): user = request.user if not user.shopping_list.exists(): return Response(status=status.HTTP_400_BAD_REQUEST) shopping_list = ( ShoppingList.objects .filter(user=user) .values_list('recipe__pk', flat=True) ) ingredients = ( IngredientsAmount.objects .filter(recipe__in=shopping_list) .values( 'ingredient_name__name', 'ingredient_name__measurement_unit' ) .annotate(sum_amount=Sum('amount')) ) ingredient_totals = { ingredient['ingredient_name__name']: { 'amount': ingredient['sum_amount'], 'unit': ingredient['ingredient_name__measurement_unit'] } for ingredient in ingredients } # Создаем динамический файл TXT response = HttpResponse(content_type=settings.CONTENT_TYPE) response['Content-Disposition'] = ( f'attachment; filename={settings.SHOPPING_LIST_FILENAME}' ) response.write('Ингредиент, Количество, Единица измерения:\n') for ingredient, data in ingredient_totals.items(): line = f'- {ingredient}, {data["amount"]}, {data["unit"]}\n' response.write(line) return response
<?php /* For licensing terms, see /license.txt */ require_once __DIR__.'/../../../../vendor/autoload.php'; /** * Test example to user API v2.php. * * Using Guzzle' HTTP client to call the API endpoint and make requests. * Change URL on the first lines of createUser() below to suit your needs. */ use GuzzleHttp\Client as Client; // set your URL, username and password here to use it for all webservices in this test file. $webserviceURL = 'https://YOURCHAMILO/main/webservices/api/'; $webserviceUsername = 'USERNAME'; $webservicePassword = 'PASSWORD'; /** * Make a request to get the API key for admin user. * * @throws Exception * * @return string */ function authenticate() { global $webserviceURL; global $webserviceUsername; global $webservicePassword; $client = new Client([ 'base_uri' => $webserviceURL, ]); $response = $client->post('v2.php', [ 'form_params' => [ 'action' => 'authenticate', 'username' => $webserviceUsername, 'password' => $webservicePassword, ], ]); if ($response->getStatusCode() !== 200) { throw new Exception('Entry denied with code : '.$response->getStatusCode()); } $jsonResponse = json_decode($response->getBody()->getContents()); if ($jsonResponse->error) { throw new Exception('Authentication failed because : '.$jsonResponse->message); } return $jsonResponse->data->apiKey; } $apiKey = authenticate(); echo 'user API Key: '.$apiKey;
import TP2Objetos.* describe "TEST" { const enviosRapidos = new Sector(costoDe = 20) const enviosEstandares = new Sector(costoDe = 15) const enviosVIP = new Sector(costoDe = 30) const unParanoico = new MensajerxEstandar(sector = enviosRapidos, tipoMensajero = paranoico) const unAlegre = new MensajerxEstandar(sector = enviosEstandares, tipoMensajero = new Alegre(gradoAlegria= 12)) const unSerio = new MensajerxEstandar(sector = enviosVIP, tipoMensajero = new Serio()) const unMensajeCifrado = new MensajeCifrado(mensaje=" mensaje no me la container") const unMensajeElocuente = new MensajeElocuente(mensaje="oye como va") const otroMensajeElocuente = new MensajeElocuente(mensaje = "mi ritmo bueno pa gozar") const mensajeElocuente = new MensajeElocuente(mensaje = "todo piola") const mensajeCantado1 = new MensajeCantado(mensaje = "holaaaa") const mensajeNormal1 = new Mensaje(mensaje = "menos de 30 caracteres") const mensajeCantado2 = new MensajeCantado(mensaje = "queridos brian, valeria, espero que les guste nuestro tp") const mensajeNormal2 = new Mensaje(mensaje = "maaas de treintaaa caractereees") // 1-TESTS PICHCA INTEGRANTE 1 test "pichca: condiciones de envío" { assert.notThat(pichca.puedeEnviar("buenasss")) assert.that(pichca.puedeEnviar("que onda loco todo bien?")) } test "pichca: costo" { assert.that(pichca.costoDe("buenasss")%3==0 || pichca.costoDe("buenasss")%4==0 || pichca.costoDe("buenasss")%5==0 || pichca.costoDe("buenasss")%6==0 || pichca.costoDe("buenasss")%7==0 ) } // 2-TEST MENSAJERO ESTANDAR test "mensajero estandar: puede enviar mensaje"{ assert.that(unParanoico.puedeEnviar("hola como estas? Yo todo bien y vos")) } test "mensajero estandar puede enviar mensaje 2"{ assert.that(unParanoico.puedeEnviar("hola como estas? tas ok?")) } test "mensajero estandar no puede enviar mensaje"{ assert.that(unParanoico.puedeEnviar("hola").negate()) } test "costo de mensajero que pertenece al sector de envios rapidos"{ assert.equals(unParanoico.costoDe("hola como andas"), 60) } test "costo de mensajero que pertenece al sector de envios estandares"{ assert.equals(unAlegre.costoDe("hola como andas"), 45) } test "costo de mensajero que pertenece al sector de envios VIP"{ assert.equals(unSerio.costoDe("hola como andas"), 90) } // 3- RECIBIR/ENVIAR MENSAJE test "no enviar un mensaje vacio" { assert.throwsExceptionWithMessage("La operacion no se puede realizar: mensaje vacio", { agenciaDeMensajeria.enviarMensaje("")}) } test "nadie puede enviar el mensaje" { assert.throwsExceptionWithMessage("La operacion no se puede realizar: nadie puede enviarlo", { agenciaDeMensajeria.enviarMensaje("cortito")}) } test "enviar un mensaje 1" { const cantidadMensajes = agenciaDeMensajeria.historial().size() agenciaDeMensajeria.enviarMensaje("mensaje apto para alguien") assert.equals(agenciaDeMensajeria.historial().size(), cantidadMensajes + 1) } test "enviar un mensaje 2" { agenciaDeMensajeria.enviarMensaje("mensaje apto para alguien") assert.notThat(agenciaDeMensajeria.historial().isEmpty()) } // 4 - GANANCIA NETA DEL MES test "ganancia neta" { //ROMPE porque el mensaje como string no sabe su ganancia neta. hay que cambiar TODO lo de agenciaDeMensajeria //agenciaDeMensajeria.enviarMensaje(unMensajeElocuente) agenciaDeMensajeria.enviarMensaje("soy un mensaje mayor a treinta caracteres") agenciaDeMensajeria.enviarMensaje("soy un mensaje menor a 20") assert.equals(agenciaDeMensajeria.gananciaNeta(),1280) //rompe porque dice que no hay ningun elemento en el historial en los ultimos 30 dias?? y es mentira //CUANDO FUNCIONE HAY QUE CORREGIR EL 50 } //5 - CHASQUI QUILLA test "chasqui quilla" { agenciaDeMensajeria.enviarMensaje("primer mensaje de prueba") agenciaDeMensajeria.enviarMensaje("segundo mensaje de prueba") agenciaDeMensajeria.enviarMensaje("tercer mensaje de prueba") assert.equals(agenciaDeMensajeria.chasquiQuilla(),messich) //rompe porque dice que no hay ningun elemento en el historial en los ultimos 30 dias?? y es mentira //CUANDO FUNCIONE HAY QUE CORREGIR EL messich } //7- MENSAJE CANTADO test "mensaje cantado"{ assert.equals(mensajeCantado1.gananciaMensaje(), mensajeNormal1.gananciaMensaje()) assert.equals(mensajeCantado2.gananciaMensaje(), mensajeNormal2.gananciaMensaje()) } //8- MENSAJE ELOCUENTE test "grado de elocuencia de mensaje elocuente 1"{ assert.equals(unMensajeElocuente.gradoElocuencia(), 2) } test "grado de elocuencia de mensaje elocuente 2"{ assert.equals(otroMensajeElocuente.gradoElocuencia(), 3) } test "grado de elocuencia de mensaje elocuente 3"{ assert.equals(mensajeElocuente.gradoElocuencia(), 1) } test "ganancia de mensaje elocuente"{ assert.equals(otroMensajeElocuente.ganancia(), 1500) } test "costo de mensaje elocuente"{ assert.equals(otroMensajeElocuente.costoDe(), 56) } //9- MENSAJE CIFRADO test "mensaje cifrado" { assert.equals(unMensajeCifrado.entregar(),"reniatnoc al em on ejasnem ") assert.equals(unMensajeCifrado.costoDe(),79) } //10 - CREANDO UN MENSAJE test "paranoico entrega un mensaje cifrado" { assert.equals(unParanoico.tipoMensajero().definirMensaje("hola que tal").entregar(),"lat euq aloh") } test "alegre entrega un mensaje cantado" { assert.equals(unAlegre.tipoMensajero().definirMensaje("un mensaje").duracion(),72) } test "serio entrega un mensaje cifrado" { unSerio.tipoMensajero().definirMensaje("primer mensaje") unSerio.tipoMensajero().definirMensaje("segundo mensaje") unSerio.tipoMensajero().definirMensaje("tercer mensaje") assert.equals(unSerio.tipoMensajero().definirMensaje("hola que tal").entregar(),"lat euq aloh") } }
package main import ( "fmt" "time" "curso.com/m/html" ) func oMaisRapido(url1, url2, url3 string) string { c1 := html.Titulo(url1) c2 := html.Titulo(url2) c3 := html.Titulo(url3) // Estrutura de controle específica para concorrência select { case t1 := <-c1: return t1 case t2 := <-c2: return t2 case t3 := <-c3: return t3 // o time funcionar como um validador de tempo case <-time.After((1000 * time.Millisecond)): return "Todos perderam!" // o valor default é executado quando nenhum dos casos é executado // o default é sempre executado cuidado com o uso, // return "Sem resposta!" } } func main() { campeao := oMaisRapido( "https://www.cod3r.com.br", "https://www.google.com", "https://www.youtube.com", ) fmt.Println(campeao) }
import { BadRequestException, Injectable, InternalServerErrorException, NotFoundException, Param } from '@nestjs/common'; import { MarketAbi } from './nftMarket.abi'; import { ethers } from 'ethers' import axios from 'axios'; const pinataSDK = require('@pinata/sdk'); import * as FormData from 'form-data'; import { generateNftMetadata } from './nft.utils'; import { Readable } from 'stream'; import { InjectModel } from '@nestjs/mongoose'; import { Nft } from './schema/nft.schema'; import * as moongoose from 'mongoose' import { NFTList, NFTListDocument } from './schema/nft-list.schema'; import { NftABI } from './nft.abi'; import { contractAddress } from 'env'; @Injectable() export class NftService { private provider = new ethers.JsonRpcProvider('https://sepolia.infura.io/v3/2275c01a51534148952b843d1ef1f366'); private abi = MarketAbi private nftABI = NftABI nftContractAddres = contractAddress.nftContractAddress //"0x7bf1eEA2c602300b44Ff8Dac69F06639F5DBa135" private nftContract = new ethers.Contract(this.nftContractAddres, this.nftABI, this.provider) private marketContractAddress = contractAddress.nftMarketContractAddress //"0x2D8D144b5A158d620DD180bEb230f92E9bB32e25" private contract = new ethers.Contract(this.marketContractAddress, this.abi, this.provider); imageUrl: any metadataUrl: any constructor(@InjectModel(Nft.name) private nftModel: moongoose.Model<Nft>, @InjectModel(NFTList.name) private nftListModel: moongoose.Model<NFTList>) { } async uploadToPinata(file: Express.Multer.File, name: string, description: string): Promise<any> { const pinataApiKey = '470191ed2ab4ab1686df'; const pinataSecretApiKey = 'b09041c7376a3d91909cc6db0fab7db9f9b4be5724fa92f6e44ca02a80ae1927'; const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`; // Upload image to IPFS const imageFormData = new FormData(); imageFormData.append('file', Readable.from(file.buffer), { filename: String(file.originalname), }); const imageResponse = await axios.post(url, imageFormData, { maxContentLength: Infinity, headers: { ...imageFormData.getHeaders(), pinata_api_key: pinataApiKey, pinata_secret_api_key: pinataSecretApiKey, }, }); this.imageUrl = `https://azure-past-guan-217.mypinata.cloud/ipfs/${imageResponse.data.IpfsHash}`; // Generate and upload metadata to IPFS const metadata = generateNftMetadata(name, description, this.imageUrl); // Generate metadata const metadataFormData = new FormData(); metadataFormData.append('file', Buffer.from(JSON.stringify(metadata)), { filename: 'metadata.json', }); const metadataResponse = await axios.post(url, metadataFormData, { maxContentLength: Infinity, headers: { ...metadataFormData.getHeaders(), pinata_api_key: pinataApiKey, pinata_secret_api_key: pinataSecretApiKey, }, }); this.metadataUrl = `https://azure-past-guan-217.mypinata.cloud/ipfs/${metadataResponse.data.IpfsHash}`; const imageUrl = this.imageUrl const metadataUrl = this.metadataUrl await this.nftEvent(); return { imageUrl, metadataUrl } } async nftEvent(): Promise<any> { await this.nftContract.on('NFTMinted', async (nft: string, nftOwner: string, nftId: string) => { const imageUrl = this.imageUrl const metadataUrl = this.metadataUrl const nftData = new this.nftModel({ _id: new moongoose.Types.ObjectId(), imageUrl, metadataUrl, nftOwner, nftId }) return await nftData.save();; }) } async findAllNfts(): Promise<Nft[]> { return this.nftModel.find() } async updateNftOwner(nftId: any, nftOwner: string): Promise<Nft> { const query = { nftId: nftId } const updatedNft = await this.nftModel.findOneAndUpdate( query, { nftOwner }, { new: true }, ); if (!updatedNft) { throw new NotFoundException('NFT not found'); } return updatedNft; } async getNftByUserAddress(nftOwner: string): Promise<any> { const nfts = await this.nftModel.find({ nftOwner }).exec(); return nfts.map(nft => nft); } async listEvent() { await this.contract.on('ListNFT', async (nftAddress: string, nftId: string, owner: string, nftPrice: string, expiryTime: string, status: string, listingType: string) => { try { const existingData = await this.nftListModel.findOne({ nftId }); if (existingData) { // If existing data found, delete it from the database await this.nftListModel.deleteOne({ nftId }); } const nft = await this.nftModel.findOne({ nftId }) const imageUrl = await nft.imageUrl const price = await ethers.formatEther(nftPrice) const data = await new this.nftListModel({ nftAddress, nftId, imageUrl, owner, price, expiryTime, status, listingType }) if (data.status == "NFT Listed") { await data.save() } else { alert("") } return ({ nftAddress, nftId, owner, }) } catch (error) { console.error(error.message); } }) } async auctionEvent() { await this.contract.on('AuctionNFT', async (nftAddress: string, nftId: string, seller: string, winner: string, intialPrice: string, lastBidPrice: string, currentBidPrice: string, expiryTime: string, compeleted: boolean) => {}) } async findListedNft(nftAddress: string) { return await this.nftListModel.find({ nftAddress}); } async findNftById(_id: string) { return await this.nftModel.find({ _id }) } findAndDelete(nftId: string) { const deleteListedItem = this.nftListModel.deleteOne({ nftId }) return deleteListedItem } }
import { message } from 'antd' import { useRouter } from 'next/router' import shareDocApi from '../../../../common/api/shareDocApi' import userApi from '../../../../common/api/userApi' import { useAppDispatch, useAppSelector } from '../../../../common/hooks/hooks-redux' import { RootState } from '../../../../common/hooks/store-redux' import { SET_USER_LIST, SET_IS_LOADING, ADD_USER, DELETE_USER, EDIT_USER } from './store' export function UseUserController() { const state = useAppSelector((state: RootState) => state.user) const dispatch = useAppDispatch() const router = useRouter() const getAllUser = async () => { try { dispatch(SET_IS_LOADING(true)) const userList = await userApi.getAll() dispatch(SET_USER_LIST(userList.data)) if (userList.status === 403) await router.push('/error/403') dispatch(SET_IS_LOADING(false)) } catch (error) { console.log('ERROR : ', error) await router.push('/error/404') } } const getUserNotShared = async (id: any) => { try { const listNotShare = await shareDocApi.getUserNotShared(id) dispatch(SET_USER_LIST(listNotShare.data)) } catch (error) { console.log('ERROR : ', error) } } const shareDocUser = async (idDoc: any, dataUser: any[]) => { try { const dataIdUser = dataUser.map((item) => item.id) const dataPost = { users: dataIdUser, } await shareDocApi.addUser(idDoc, dataPost) message.success(`Chia sẻ văn bản thành công !`) } catch (error) { console.log('ERROR : ', error) message.error(`Chia sẻ văn bản thất bại !`) } } const getUserNotDepartId = async () => { try { dispatch(SET_IS_LOADING(true)) const userListNotDepartId = await userApi.getUser() dispatch(SET_USER_LIST(userListNotDepartId.data)) dispatch(SET_IS_LOADING(false)) } catch (error) { console.log('ERROR : ', error) } } const addUser = async (data: any) => { try { const user = await userApi.create(data) dispatch(ADD_USER(user.data)) message.success(`Thêm người dùng thành công !`) } catch (error) { console.log('ERROR : ', error) message.error(`Thêm người dùng thất bại !`) } } const editUser = async (data: any, id: any) => { try { const response = await userApi.update(id, data) console.log('res: ', response) if (response.status === 200) dispatch(EDIT_USER({ data, id })) message.success(`Cập nhật người dùng thành công !`) } catch (error) { console.log('ERROR : ', error.message) message.error(`Cập nhật người dùng thất bại !`) } } const deleteUser = async (id: any) => { try { await userApi.delete(id) dispatch(DELETE_USER(id)) message.success(`Xóa người dùng thành công !`) } catch (error) { console.log('ERROR : ', error) message.error(`Xóa người dùng thất bại !`) } } return { state, getAllUser, getUserNotDepartId, getUserNotShared, addUser, deleteUser, editUser, shareDocUser, } }
<?php namespace app\model; use support\Model; /** * xs_user * @property integer $uid (主键) * @property string $username 用户名 * @property string $nickname 昵称 * @property string $phone 手机号码 * @property string $email 邮箱地址 * @property string $qq QQ * @property string $wx_credit 微信号 * @property string $wb_credit 微博号 * @property string $salt 密码盐 * @property string $password 密码 * @property string $access_token 微信权限token * @property string $auth_key 微信权限key * @property string $avatar_url 头像 * @property string $ip IP * @property string $addr 最后登录地址 * @property integer $vip_level VIP等级 * @property integer $rid 角色 * @property integer $puid 上级邀请人 * @property integer $gpuid 上上级邀请人 * @property integer $level 等级 * @property integer $credit 经验值 * @property string $gold 金币 * @property string $rmb 余额 * @property string $pay_password 支付密码 * @property string $pay_password_salt 支付密码盐 * @property string $last_login_time * @property integer $status 状态 0 正常 1 禁用 * @property string $created_at * @property string $updated_at * @property string $deleted_at * @property string $vip_expired_at 会员过期时间 * @property integer $sex 性别 1 男 2 女 * @property integer $follow_num 关注人数 * @property integer $followed_num 被多少人关注 */ class User extends Model { /** * The connection name for the model. * * @var string|null */ protected $connection = 'mysql'; /** * The table associated with the model. * * @var string */ protected $table = 'user'; /** * The primary key associated with the table. * * @var string */ protected $primaryKey = 'uid'; public const STATUS = [ '正常', //正常状态 '禁止登录' //禁止登录 ]; /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false; protected $fillable = [ 'access_token',//微信权限token 'addr',//最后登录地址 'auth_key',//微信权限key 'avatar_url',//头像 'created_at',// 'credit',//经验值 'deleted_at',// 'email',//邮箱地址 'follow_num',//关注人数 'followed_num',//被多少人关注 'gold',//金币 'gpuid',//上上级邀请人 'ip',//IP 'last_login_time',// 'level',//等级 'nickname',//昵称 'password',//密码 'pay_password',//支付密码 'pay_password_salt',//支付密码盐 'phone',//手机号码 'puid',//上级邀请人 'qq',//QQ 'rid',//角色 'rmb',//余额 'salt',//密码盐 'sex',//性别 1 男 2 女 'status',//状态 0 正常 1 禁用 'updated_at',// 'username',//用户名 'vip_expired_at',//会员过期时间 'vip_level',//VIP等级 'wb_credit',//微博号 'wx_credit',//微信号 ]; public function select() { return [ 'access_token',//微信权限token 'addr',//最后登录地址 'auth_key',//微信权限key 'avatar_url',//头像 'created_at',// 'credit',//经验值 'deleted_at',// 'email',//邮箱地址 'follow_num',//关注人数 'followed_num',//被多少人关注 'gold',//金币 'gpuid',//上上级邀请人 'ip',//IP 'last_login_time',// 'level',//等级 'nickname',//昵称 'phone',//手机号码 'puid',//上级邀请人 'qq',//QQ 'rid',//角色 'rmb',//余额 'sex',//性别 1 男 2 女 'status',//状态 0 正常 1 禁用 'updated_at',// 'username',//用户名 'vip_expired_at',//会员过期时间 'vip_level',//VIP等级 'wb_credit',//微博号 'wx_credit',//微信号 ]; } public function getRedisKey($param) { if(is_array($param)) { return $this->model->getTable().'_'.implode('_',$param); }else{ $this->model->getTable().'_'.$this->model->getKeyName().'_'.$param; } } }
<?php /** * Template part for displaying page content in page.php * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/ * * @package HybridMag */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php // Before content hook do_action( 'hybridmag_before_content' ); /** * Before entry header hook. * * @since 1.0.0 */ do_action( 'hybridmag_before_entry_header' ); ?> <header class="entry-header"> <?php // Before page title hook. do_action( 'hybridmag_before_page_title' ); the_title( '<h1 class="entry-title">', '</h1>' ); // After page title hook. do_action( 'hybridmag_after_page_title' ); ?> </header><!-- .entry-header --> <?php // After page header hook. do_action( 'hybridmag_after_page_header' ); if ( get_theme_mod( 'hybridmag_show_page_thumbnail', true ) ) { hybridmag_post_thumbnail(); } ?> <div class="entry-content"> <?php the_content(); wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'hybridmag' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <?php if ( get_edit_post_link() ) : ?> <footer class="entry-footer"> <?php edit_post_link( sprintf( wp_kses( /* translators: %s: Name of current post. Only visible to screen readers */ __( 'Edit <span class="screen-reader-text">%s</span>', 'hybridmag' ), array( 'span' => array( 'class' => array(), ), ) ), wp_kses_post( get_the_title() ) ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> <?php endif; ?> <?php // After content hook do_action( 'hybridmag_after_content' ); ?> </article><!-- #post-<?php the_ID(); ?> -->
// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ #pragma once #include <array> #include <optional> #include <api/model/api_model_fwd.h> #include <api/model/recording_stats_reply.h> #include <common/common_globals.h> #include <core/resource/resource_fwd.h> #include <nx/vms/api/data/id_data.h> #include <nx/vms/api/data/storage_scan_info.h> #include <nx/vms/api/types/event_rule_types.h> #include <nx/vms/client/core/common/utils/common_module_aware.h> #include <nx/vms/client/core/network/remote_connection_aware.h> #include <nx/vms/client/desktop/system_context_aware.h> #include <server/server_storage_manager_fwd.h> struct QnStorageStatusReply; /** * Client-side class to monitor server-related storages state: storages structure, space, roles and * rebuild process. */ class QnServerStorageManager: public QObject, public nx::vms::client::desktop::SystemContextAware { Q_OBJECT using base_type = QObject; public: explicit QnServerStorageManager( nx::vms::client::desktop::SystemContext* systemContext, QObject* parent = nullptr); virtual ~QnServerStorageManager() override; /** * Temporary method to access storage manager from the current system context. */ static QnServerStorageManager* instance(); QSet<QString> protocols(const QnMediaServerResourcePtr& server) const; nx::vms::api::StorageScanInfo rebuildStatus( const QnMediaServerResourcePtr& server, QnServerStoragesPool pool) const; bool rebuildServerStorages(const QnMediaServerResourcePtr& server, QnServerStoragesPool pool); bool cancelServerStoragesRebuild( const QnMediaServerResourcePtr& server, QnServerStoragesPool pool); // TODO: #vbreus Method name doesn't reflect actual action, should be fixed. /** * This method updates active metadata storage and sends storages archive rebuild progress * requests for given server. */ void checkStoragesStatus(const QnMediaServerResourcePtr& server); void saveStorages(const QnStorageResourceList& storages); void deleteStorages(const nx::vms::api::IdDataList& ids); QnStorageResourcePtr activeMetadataStorage(const QnMediaServerResourcePtr& server) const; /** * Requests storage space from mediaserver. * Response data can be retrieved from signal `storageSpaceRecieved` * @returns request handle. It is zero if something goes wrong. */ int requestStorageSpace(const QnMediaServerResourcePtr& server); int requestStorageStatus( const QnMediaServerResourcePtr& server, const QString& storageUrl, std::function<void(const QnStorageStatusReply&)> callback); int requestRecordingStatistics(const QnMediaServerResourcePtr& server, qint64 bitrateAnalyzePeriodMs, std::function<void (bool, int, const QnRecordingStatsReply&)> callback); signals: void serverProtocolsChanged( const QnMediaServerResourcePtr& server, const QSet<QString>& protocols); void serverRebuildStatusChanged(const QnMediaServerResourcePtr& server, QnServerStoragesPool pool, const nx::vms::api::StorageScanInfo& status); void serverRebuildArchiveFinished( const QnMediaServerResourcePtr& server, QnServerStoragesPool pool); void storageAdded(const QnStorageResourcePtr& storage); void storageChanged(const QnStorageResourcePtr& storage); void storageRemoved(const QnStorageResourcePtr& storage); // For convenience this signal is also sent when the server goes online or offline or is removed. void activeMetadataStorageChanged(const QnMediaServerResourcePtr& server); void storageSpaceRecieved(QnMediaServerResourcePtr server, bool success, int handle, const QnStorageSpaceReply& reply); private: void invalidateRequests(); bool isServerValid(const QnMediaServerResourcePtr& server) const; bool sendArchiveRebuildRequest(const QnMediaServerResourcePtr& server, QnServerStoragesPool pool, Qn::RebuildAction action = Qn::RebuildAction_ShowProgress); void checkStoragesStatusInternal(const QnResourcePtr& resource); void handleResourceAdded(const QnResourcePtr& resource); void handleResourceRemoved(const QnResourcePtr& resource); QnStorageResourcePtr calculateActiveMetadataStorage( const QnMediaServerResourcePtr& server) const; void setActiveMetadataStorage(const QnMediaServerResourcePtr& server, const QnStorageResourcePtr& storage, bool suppressNotificationSignal); void updateActiveMetadataStorage(const QnMediaServerResourcePtr& server, bool suppressNotificationSignal = false); private: void at_archiveRebuildReply(bool success, int handle, const nx::vms::api::StorageScanInfoFull& reply); void at_storageSpaceReply(bool success, int handle, const QnStorageSpaceReply& reply); private: struct ServerInfo; struct RequestKey { QnMediaServerResourcePtr server; QnServerStoragesPool pool = QnServerStoragesPool::Main; RequestKey() = default; RequestKey(const QnMediaServerResourcePtr& server, QnServerStoragesPool pool); }; QHash<QnMediaServerResourcePtr, ServerInfo> m_serverInfo; QHash<int, RequestKey> m_requests; QHash<QnMediaServerResourcePtr, QnStorageResourcePtr> m_activeMetadataStorages; }; #define qnServerStorageManager QnServerStorageManager::instance()
<div align="center"> <p> Transaction Detail (Add) </p> </div> <div *ngIf="transactionForm" align="center"> <form [formGroup]="transactionForm" novalidate> <div class="show_window"> <div class="row margin-top-20"> <div class="col-sm-3 align-left"> <label for="transactionDate">Transaction Date:</label> </div> <div class="col-sm-9 align-left"> <input type="date" class="form-control" id="transactionDate" name="transactionDate" formControlName="transactionDate" useValueAsDate> <control-messages [control]="transactionForm.controls.transactionDate"></control-messages> </div> </div> <div class="row margin-top-20"> <div class="col-sm-3 align-left"> <label for="requestor">Requestor:</label> </div> <div class="col-sm-9 align-left"> <select class="form-control" id="requestor" name="requestor" formControlName="requestor"> <option value="Organization One">Organization One</option> <option value="Organization Two">Organization Two</option> <option value="Organization Three">Organization Three</option> <option value="Organization Four">Organization Four</option> <option value="Organization Five">Organization Five</option> <option value="Organization Six">Organization Six</option> <option value="Organization Seven">Organization Seven</option> <option value="Organization Eight">Organization Eight</option> <option value="Organization Nine">Organization Nine</option> <option value="Organization Ten">Organization Ten</option> </select> <control-messages [control]="transactionForm.controls.requestor"></control-messages> </div> </div> <div *ngIf="getRequestorLogo()" class="row margin-top-20"> <div class="col-sm-3 align-left"> <label>Requestor Logo:</label> </div> <div class="col-sm-9 align-left"> <img [src]="getRequestorLogo()"> </div> </div> <div class="row margin-top-20"> <div class="col-sm-3 align-left"> <label for="location">Location:</label> </div> <div class="col-sm-9 align-left"> <input type="text" class="form-control" id="location" placeholder="Location" name="location" formControlName="location" > <control-messages [control]="transactionForm.controls.location"></control-messages> </div> </div> <div class="row margin-top-20"> <div class="col-sm-3 align-left"> <label for="status">Status:</label> </div> <div class="col-sm-9 align-left"> <select class="form-control" id="status" name="status" formControlName="status"> <option value="Open">Open</option> <option value="Completed">Completed</option> <option value="Rejected">Rejected</option> <option value="Pending">Pendiing</option> </select> <control-messages [control]="transactionForm.controls.status"></control-messages> </div> </div> <div class="row margin-top-20"> <div class="col-sm-3 align-left"> <label for="transactionCode">TransactionCode:</label> </div> <div class="col-sm-9 align-left"> <input type="text" class="form-control" id="transactionCode" placeholder="Transaction Code" name="transactionCode" formControlName="transactionCode" > <control-messages [control]="transactionForm.controls.transactionCode"></control-messages> </div> </div> <div class="row margin-top-20 margin-bottom-20"> <div class="col-sm-3 align-left"> <label for="description">Description:</label> </div> <div class="col-sm-9 align-left"> <input type="text" class="form-control" id="description" placeholder="description" name="Description" formControlName="description" > <control-messages [control]="transactionForm.controls.description"></control-messages> </div> </div> </div> <div class="align_bottom"> <button [disabled]="transactionForm.pristine || transactionForm.invalid || submitted" class="button_ctl" (click)="onSubmit()">Submit</button> <button class="button_ctl" (click)="onCancel()">Cancel</button> </div> </form> </div>
import type { AppContext } from "@webstudio-is/trpc-interface/index.server"; import env from "~/env/env.server"; import { authenticator } from "~/services/auth.server"; import { trpcClient } from "~/services/trpc.server"; import { entryApi } from "./entri/entri-api.server"; import { getTokenPlanFeatures, getUserPlanFeatures, } from "./db/user-plan-features.server"; const createAuthorizationContext = async ( request: Request ): Promise<AppContext["authorization"]> => { const url = new URL(request.url); const authToken = url.searchParams.get("authToken") ?? url.hostname; const user = await authenticator.isAuthenticated(request); const isServiceCall = request.headers.has("Authorization") && request.headers.get("Authorization") === env.TRPC_SERVER_API_TOKEN; const context: AppContext["authorization"] = { userId: user?.id, authToken, isServiceCall, projectTemplates: env.PROJECT_TEMPLATES, authorizeTrpc: trpcClient.authorize, }; return context; }; const createDomainContext = (request: Request) => { const context: AppContext["domain"] = { domainTrpc: trpcClient.domain, }; return context; }; const createDeploymentContext = (request: Request) => { const url = new URL(request.url); const context: AppContext["deployment"] = { deploymentTrpc: trpcClient.deployment, env: { BUILDER_ORIGIN: url.origin, BRANCH_NAME: env.BRANCH_NAME ?? "main", }, }; return context; }; const createEntriContext = () => { return { entryApi, }; }; const createUserPlanContext = async ( request: Request, authorization: AppContext["authorization"] ) => { const url = new URL(request.url); const authToken = url.searchParams.get("authToken"); // When a shared link is accessed, identified by the presence of an authToken, // the system retrieves the plan features associated with the project owner's account. if (authToken !== null) { const planFeatures = await getTokenPlanFeatures(authToken); return planFeatures; } const user = await authenticator.isAuthenticated(request); const planFeatures = user?.id ? getUserPlanFeatures(user.id) : undefined; return planFeatures; }; /** * argument buildEnv==="prod" only if we are loading project with production build */ export const createContext = async (request: Request): Promise<AppContext> => { const authorization = await createAuthorizationContext(request); const domain = createDomainContext(request); const deployment = createDeploymentContext(request); const entri = createEntriContext(); const userPlanFeatures = await createUserPlanContext(request, authorization); return { authorization, domain, deployment, entri, userPlanFeatures, }; };
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { PostModel } from '../shared/post-model'; import { PostService } from '../shared/post.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { searchText : string = ""; posts : Array<PostModel> = []; constructor(private postService : PostService){ } /** * Display all Post */ ngOnInit(): void { this.postService.getAllPost().subscribe((post : any) =>{ this.posts = post; }); } /** * Initialize searchPosts() method to search for posts * User to search Post by postName */ searchPosts(searchvaluepost : string){ this.searchText = searchvaluepost; this.posts = this.posts.filter(post => post.postName.includes(this.searchText)); console.log(this.searchText); } }
--- title: "Course Project" author: "Group D7" output:html_document --- Reading and Displaying Data ```{r} df<-read.csv("C:/Users/cheta/Desktop/cleaned_reviews.csv") head(df) ``` FINDING ROWS WITH NULL VALUES ```{r} rows_with_null<-df[apply(is.na(df),1,any),] ``` FINDING COLUMNS WITH ANY NULL VALUES ```{r} cols_with_null<- df[apply(is.na(df),2,any)] ``` PRINTING THE ROWS AND COLUMN WITH NULL VALUES ```{r} print(rows_with_null) ``` ```{r} print(cols_with_null) ``` Displaying Data Dimensions:- ```{r} dim(df) ``` Displaying Data Structure:-It provides information about the data types of columns and other data-related details. ```{r} str(df) ``` Summary of Data:-It includes statistics and information about the data in each column. ```{r} summary(df) ``` Installing the "dplyr" Package:-It is commonly used for data manipulation and transformation. ```{r} install.packages("dplyr") ``` Loading the "dplyr" Package ```{r} library(dplyr) ``` Loading the "ggplot2" Package ```{r} library(ggplot2) ``` Creating a Box Plot Creating a box plot that visualizes the distribution of review scores by sentiment. ```{r} boxplot_plot <- ggplot(df, aes(x =sentiments, y =review_score)) + geom_boxplot() + labs(title = "Boxplot") print(boxplot_plot) ``` Creating a Scatter Plot Creating the Scatter plot to visualize the relationship between review scores and sentiments. ```{r} library(ggplot2) ggplot(data=df,mapping=aes(x=sentiments,y=review_score))+geom_point() ``` Creating a Grouped Box Plot creates a grouped box plot using "ggplot2" to visualize the distribution of review scores by sentiment. ```{r} library(ggplot2) ggplot(data=df,mapping=aes(x=sentiments,y=review_score,fill=sentiments))+geom_boxplot() ``` Creating a Scatter Plot for Review Length and Sentiments Creates a scatter plot to visualize the relationship between sentiments and the length of cleaned reviews. ```{r} library(ggplot2) ggplot(data=df,mapping=aes(x=sentiments,y=cleaned_review_length))+geom_point() ``` Calculating Percentage of Review Scores Calculate the percentage of each unique value in the review_score column ```{r} rating_counts <- table(df$review_score) rating_pct <- (rating_counts / nrow(df)) * 100 print(rating_pct) ``` Analyzing Text Data These code chunks focus on analyzing text data, including checking data types, converting text data to character type, checking for missing values, and creating a histogram to visualize word count distribution in the "cleaned_review" column. ```{r} barplot(rating_pct, main = "Rating Percentages", xlab = "Rating", ylab = "Percentage", col = "blue") ``` To calculate words per review check the datatype of the cleaned_review column ```{r} class(df$cleaned_review) ``` convert the text column to character ```{r} df$Text <- as.character(df$cleaned_review) ``` check the missing value ```{r} sum(is.na(df$Text)) ``` ```{r} library(ggplot2) WordsPerReview <- sapply(strsplit(df$Text, ' '), length) #create the histogram ggplot(data = data.frame(WordsPerReview = WordsPerReview), aes(x = WordsPerReview)) + geom_histogram(bins = 100, fill = "blue", color = "black") + xlab("cleaned_review") + theme_minimal() ``` Creating a New Dataframe ```{r} new_df <- df[, c('cleaned_review', 'review_score')] ``` Renaming Column Names ```{r} colnames(new_df) <- c('Rating', 'Review') ``` Creating Sentiment Mapping Function ```{r} apply_sentiment <- function(Rating) { if (Rating <= 2) { return(0) } else { return(1) } } rating <- 3 sentiment <- apply_sentiment(rating) print(sentiment) ``` Setting Warning Conflicts to FALSE ```{r} options(warn.conflicts = FALSE) ``` Creating Review Score Visualizations ```{r} library(ggplot2) library(gridExtra) # Calculate value counts for review scores review_counts <- table(df$review_score) # Create a count plot count_plot <- ggplot(data = df, aes(x = review_score)) + geom_bar() + labs(title = "Review Score Count Plot") print(count_plot) ``` Creating Review Score Visualizations ```{r} # Load the necessary libraries library(ggplot2) # Sample data for review counts review_counts <- data.frame( review_score = c("Excellent", "Very Good", "Good", "Fair", "Poor"), n = c(20, 30, 15, 10, 5) ) # Create a pie chart pie_chart <- ggplot(data = review_counts, aes(x = "", y = n, fill = review_score)) + geom_bar(stat = "identity") + coord_polar(theta = "y") + theme_void() + labs(title = "Review Score Distribution") # Print the pie chart print(pie_chart) ``` Text Mining and Sentiment Analysis ```{r} install.packages("tm") ``` ```{r} install.packages("syuzhet") ``` ```{r} library(tm) library(syuzhet) ``` Sample text data ```{r} text_data <- c( "Its very nice product, i just loved it", "The customer service was terrible.", "The movie was just okay, nothing special.", "I hate this product.", "It was good but not that good", "This is the most excellent product I have used till", "The product is okay, does what it's supposed to do.", "I'm disappointed with this product; it failed to meet my expectations.", "This is the best product I've ever used!", "The product is middle-of-the-road, quite what you'd expect.", "I'm overjoyed with the results; this is a premium quality product!", "Customer service was fine, nothing special but not bad either.", "The quality is subpar, not what I was hoping for at all.", "I'm incredibly pleased with the customer service; they're fantastic!", "It's a standard service, meets expectations but doesn't exceed them.", "I regret this purchase; the product is not worth the money.", "Absolutely love how this performs, it's perfect for my needs.", "This service has been a game-changer, so grateful I found it!", "I'm thrilled with the results, it's just what I was looking for!", "It's an average item, not bad for the price.", "The quality of this item is outstanding, exceeded my expectations!", "I'm delighted with my purchase, would buy it again in a heartbeat!", "Service was competent, though it lacked that extra touch.", "This has to be the greatest invention, it makes life so much easier!", "The product works as intended but doesn't stand out in any way.", "Customer service was unhelpful and frustrating to deal with.", "This item is fairly ordinary, neither good nor bad.", "It's an adequate product, though there's room for improvement.", "This item is poorly made and started falling apart quickly.", "I'm not satisfied with the service; it was a waste of time.", "The product is far below the quality advertised.", "It's a standard service, meets expectations but doesn't exceed them.", "I had a bad experience with this service; I wouldn't recommend it.", "This has been a letdown; the item does not perform as promised.", "I'm unhappy with the purchase; it's not up to the standard.", "The item is acceptable, but I might try something different next time.", "I love this product", "This is terrible", "It's okay" ) ``` Create a data frame with the text data ```{r} df <- data.frame(Text = text_data) ``` Preprocess the text data using the tm package (same as in the previous example) Perform sentiment analysis using the syuzhet package. ```{r} sentiments <- get_sentiment(df$Text, method = "afinn") ``` Combine the results with the original data frame ```{r} df <- cbind(df, Sentiment = sentiments) ``` Print the results ```{r} print(df) ``` ```{r} df_sorted_ascending <- df[order(df$Sentiment), ] df_sorted_ascending ```
--- title: "iPhone Development: to Objective-C or not to Objective-C ?" author: "Humberto C Marchezi" date: "2011-02-27" categories: [software-engineering] --- When I think of Objective-C, what comes to my mind is a niche programming language for the MacOS and Apple related products. Thus as far as I know this is the only officially supported language to develop products for iPhones, iPods, iPads and so on .... On the other hand I really what to develop apps that will work in Windows, Linux and MacOS, and for this purpose I see two options: **1) Develop in C/C++ and try to find tools that translate this code to Objective-C and/or MacOS** **2) Use Objective-C to develop any kind of application (at least desktop and mobile apps)** Developing portable iPhone apps outside Objective-C --------------------------------------------------- ### Swig For the first option, there is swig ( http://www.swig.org/ ) which is a wrapper for C++ to export its classes and/or functions to several languages (Objective-C is a work in progress). However it doesn´t really solve the problem because there are libraries. ### Mono Touch The Mono Touch ( http://monotouch.net/ ) is probably one of the most interesting project to develop apps for the iPhone without Objective-C. It makes it possible to develop apps with C\#.NET. The same Mono project also make it possible to develop apps for Linux. As a consequence, C\#.NET could be seriously considered to develop apps for a wide range of platforms. However unlike Mono one must pay to start using it which may not be a problem if you are familiarized with C\#.NET. ### PhoneGap Another options is PhoneGap ( http://www.phonegap.com ) which is an open-source framework whose objective is to let developers to write apps with HTML5+CSS+JavaScript and execute it to the different mobile platforms including iOS. Objective-C as a portable programming language ---------------------------------------------- I recently read about he mechanics and philosophy of Objective-C language and I got quite impressed by its features. It is not just C with classes as I heard before, it is actually a powerful dynamic language. Everything is an object including the classes itself what reminds me of Smalltalk, LISP and Python. There are also some options to use Objective-C outside of the Apple ecosystem: ### GNU Step As stated in their website ( http://www.gnustep.org/ ) the objective is to create an open version of Cocoa (former NextStep) for several platforms including Linux and Windows. Besides porting the API this project also comes with several developer tools such as an IDE named **ProjectCenter** and a GUI code generator called **Gorm**.
--- minutes: 20 --- # Exercise: Logger Trait Let's design a simple logging utility, using a trait `Logger` with a `log` method. Code which might log its progress can then take an `&impl Logger`. In testing, this might put messages in the test logfile, while in a production build it would send messages to a log server. However, the `StderrLogger` given below logs all messages, regardless of verbosity. Your task is to write a `VerbosityFilter` type that will ignore messages above a maximum verbosity. This is a common pattern: a struct wrapping a trait implementation and implementing that same trait, adding behavior in the process. What other kinds of wrappers might be useful in a logging utility? ```rust,compile_fail {{#include exercise.rs:setup}} // TODO: Define and implement `VerbosityFilter`. {{#include exercise.rs:main}} ```
#' Helper function to run a linear mixed model #' #' @importFrom lmerTest lmer #' @importFrom lme4 lmerControl .single_lmer <- function(data, formula_string, REML = TRUE, ...) { out_model <- tryCatch( lmerTest::lmer( stats::as.formula(formula_string), data = data, REML = REML, control = lme4::lmerControl(check.conv.singular = "ignore"), ... ), warning = function(w) { return(lmerTest::lmer( stats::as.formula(formula_string), data = data, REML = REML, control = lme4::lmerControl(optimizer = "Nelder_Mead", check.conv.singular = "ignore"), ... )) } ) if (is(out_model, "lmerModLmerTest")) { return(out_model) } else { stop("Convergence issue not caught by single_lmer") } } #' Helper function to run a linear model .run_linear_model <- function(X, pheno, formula, method="lm", type="II", ...) { pheno$component <- X formula <- stats::as.formula(paste0("component", formula)) if (method == "lmer") { linear_model <- .single_lmer(pheno, formula, ...) anova_res <- data.frame(stats::anova(linear_model, type=type)) summary_res <- data.frame(summary(linear_model)$coefficients) } else if (method == "lm") { linear_model <- stats::lm(formula, pheno) anova_res <- data.frame(car::Anova(linear_model, type=type)) summary_res <- data.frame(summary(linear_model)$coefficients) } anova_res$term <- rownames(anova_res) summary_res$term <- rownames(summary_res) return(list("model"=linear_model, "anova"=anova_res, "summary"=summary_res)) } #' Runs linear models for components and sample-level data #' #' Runs either standard linear or linear mixed models between reduced #' components (e.g., factors or modules) and sample-level information. #' #' @param re An object inheriting from #' \link[ReducedExperiment]{ReducedExperiment}. #' #' @param formula The model formula to apply. Only the right hand side of the #' model need be specified (e.g., "~ x + y"). The left hand side represents the #' components themselves. The variables in this formula should be present in the #' `colData` of `re`. #' #' @param method If "lm", then the \link[stats]{lm} function is used to run #' linear models (in tandem with \link[car]{Anova} for running anovas on the #' model terms). If "lmer", then linear mixed models are run through #' \link[lmerTest]{lmer}. #' #' @param scale_reduced If TRUE, the reduced data are scaled (to have a standard #' deviation of 1) before modelling. #' #' @param center_reduced If TRUE, the reduced data are centered (to have a mean #' of 0) before modelling. #' #' @param type The type of anova to be applied to the terms of the linear model. #' #' @param adj_method The method for adjusting for multiple testing. Passed to #' the \link[stats]{p.adjust} `method` parameter. #' #' @param ... Additional arguments passed to \link[lmerTest]{lmer}, given that #' `method` is set to "lmer". #' #' @returns Returns a list with the entry "models" including a list of the #' model objects, "anovas" containing the output of anova-based testing, #' and "summaries" containing the results of running `summary` on the models. #' #' @export associate_components <- function(re, formula, method="lm", scale_reduced=TRUE, center_reduced=TRUE, type="II", adj_method="BH", ...) { models <- list() summaries <- anovas <- data.frame() red <- reduced(re, scale_reduced=scale_reduced, center_reduced=center_reduced) for (comp in componentNames(re)) { linear_model <- .run_linear_model( X=red[, comp], pheno=data.frame(colData(re)), formula=formula, method=method, type=type, ... ) linear_model$anova$component <- linear_model$summary$component <- comp models[[comp]] <- linear_model$model anovas <- rbind(anovas, linear_model$anova) summaries <- rbind(summaries, linear_model$summary) } colnames(anovas) <- .rename_results_table(colnames(anovas)) colnames(summaries) <- .rename_results_table(colnames(summaries)) rownames(anovas) <- paste(anovas$component, anovas$term, sep="_") rownames(summaries) <- paste(summaries$component, summaries$term, sep="_") anovas$adj_pvalue <- .adjust_by_term(anovas, method=adj_method) summaries$adj_pvalue <- .adjust_by_term(summaries, method=adj_method) return(list("models"=models, "anovas"=anovas, "summaries"=summaries)) } #' Adjusts the p-values of model results for multiple testing on a per-term basis .adjust_by_term <- function(res, method="BH") { res$adj_pvalue <- NA for (term in unique(res$term)) { res$adj_pvalue[which(res$term == term)] <- stats::p.adjust(res$pvalue[which(res$term == term)], method=method) } return(res$adj_pvalue) } #' Renames linear model result table column names .rename_results_table <- function(cnames) { cname_conversions <- list( "Sum.Sq" = "sum_sq", "Mean.Sq" = "mean_sq", "NumDF" = "num_df", "DenDF" = "den_df", "F.value" = "fvalue", "Pr..F." = "pvalue", "Estimate" = "estimate", "Std..Error" = "stderr", "t.value" = "tvalue", "Pr...t.." = "pvalue" ) for (i in seq_along(cnames)) if (cnames[i] %in% names(cname_conversions)) cnames[i] <- cname_conversions[[cnames[i]]] return(cnames) }
import { createEnv } from "@t3-oss/env-nextjs" import { z } from "zod" export const env = createEnv({ /** * Specify your server-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. */ server: { NODE_ENV: z.enum(["development", "test", "production"]), DATABASE_URL: z.string().url(), CLERK_SECRET_KEY: z.string().min(1), STRIPE_SECRET_KEY: z.string().min(1), STRIPE_WEBHOOK_SECRET: z.string().min(1), STRIPE_DEV_WEBHOOK_SECRET: z.string().min(1), }, /** * Specify your client-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. To expose them to the client, prefix them with * `NEXT_PUBLIC_`. */ client: { // NEXT_PUBLIC_CLIENTVAR: z.string().min(1), NEXT_PUBLIC_TMDB_API: z.string().min(1), NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.string().min(1), NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: z.string().min(1), }, /** * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. * middlewares) or client-side so we need to destruct manually. */ runtimeEnv: { NODE_ENV: process.env.NODE_ENV, // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_TMDB_API: process.env.NEXT_PUBLIC_TMDB_API, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY, NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY, STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET, STRIPE_DEV_WEBHOOK_SECRET: process.env.STRIPE_DEV_WEBHOOK_SECRET, }, /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. * This is especially useful for Docker builds. */ skipValidation: !!process.env.SKIP_ENV_VALIDATION, })
using MediatR; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WhatBug.Application.Common.Interfaces; using WhatBug.Application.Common.MediatR; using WhatBug.Application.Common.Security; using WhatBug.Domain.Data; namespace WhatBug.Application.Home { [Authorize] public record GetHomeQuery : IQuery<Response<GetHomeQueryResult>> { } public class GetHomeQueryHandler : IRequestHandler<GetHomeQuery, Response<GetHomeQueryResult>> { private readonly IWhatBugDbContext _context; private readonly ICurrentUserService _currentUserService; public GetHomeQueryHandler(IWhatBugDbContext context, ICurrentUserService currentUserService) { _context = context; _currentUserService = currentUserService; } public async Task<Response<GetHomeQueryResult>> Handle(GetHomeQuery request, CancellationToken cancellationToken) { var myProjectIds = await _context.ProjectRoleUsers .Where(u => u.UserId == _currentUserService.Id) .Select(p => p.ProjectId) .Distinct() .ToListAsync(); var myProjects = await _context.Projects .Include(p => p.Issues).ThenInclude(i => i.IssueStatus) .Where(p => myProjectIds.Contains(p.Id)) .ToListAsync(); var creators = await _context.Users.Where(u => myProjects.Select(p => p.CreatedBy).Contains(u.Id)).ToListAsync(); var dto = new GetHomeQueryResult { Projects = new List<ProjectDto>() }; foreach (var project in myProjects) { var totalIssueCount = project.Issues.Count(); var completedIssueCount = project.Issues.Where(i => i.IssueStatus.Id == IssueStatuses.Done.Id).Count(); var creator = creators.First(u => u.Id == project.CreatedBy); dto.Projects.Add(new ProjectDto { Id = project.Id, Key = project.Key, Name = project.Name, Description = project.Description, Created = project.Created, CreatorId = creator.Id, CreatorEmail = creator.Email, CreatorName = $"{creator.FirstName} {creator.Surname}", ProgressPercent = (int)Math.Round((double)completedIssueCount / totalIssueCount * 100) }); } var toDoIssues = await _context.Issues .Where(i => i.AssigneeId == _currentUserService.Id) .Where(i => i.IssueStatus.Id == IssueStatuses.ToDo.Id) .Select(i => new IssueDTO { Id = i.Id, ProjectId = i.ProjectId, Summary = i.Summary, Priority = i.Priority.Name, Icon = i.Priority.Icon.WebName, IconColor = i.Priority.Color.Name, }) .ToListAsync(); var inProgressIssues = await _context.Issues .Where(i => i.AssigneeId == _currentUserService.Id) .Where(i => i.IssueStatus.Id == IssueStatuses.InProgress.Id) .Select(i => new IssueDTO { Id = i.Id, ProjectId = i.ProjectId, Summary = i.Summary, Priority = i.Priority.Name, Icon = i.Priority.Icon.WebName, IconColor = i.Priority.Color.Name, }) .ToListAsync(); dto.ToDoIssues = toDoIssues; dto.InProgressIssues = inProgressIssues; return Response<GetHomeQueryResult>.Success(dto); } } }
/// MIT License /// /// Copyright (c) 2023 Mac Gallagher /// /// 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 Combine import UIKit enum DemoTextFieldCellTransformer { static func makeCellRegistration(viewModel: DemoViewModel, delegate: DemoCellDelegate?) -> DemoCellRegistration { DemoCellRegistration { [weak delegate] cell, indexPath, item in var configuration = DemoTextFieldContentConfiguration() configuration.title = makeTitle(for: item) configuration.placeholder = makePlaceholder(for: item) configuration.text = makeText( for: item, duration: viewModel.duration, hourInterval: viewModel.hourInterval, minuteInterval: viewModel.minuteInterval, secondInterval: viewModel.secondInterval, minimumDuration: viewModel.minimumDuration, maximumDuration: viewModel.maximumDuration) configuration.textUpdateHandler = { text in delegate?.textFieldCell( textDidChangeForItem: item, text: text) } cell.contentConfiguration = configuration } } // MARK: - Private private static func makeTitle(for item: DemoDataSource.Item) -> String? { switch item { case .durationPickerHourInterval: return "Hour Interval" case .durationPickerMaximumDuration: return "Maximum Duration" case .durationPickerMinimumDuration: return "Minimum Duration" case .durationPickerMinuteInterval: return "Minute Interval" case .durationPickerSecondInterval: return "Second Interval" case .durationPickerValue: return "Selected Duration" default: return nil } } private static func makePlaceholder(for item: DemoDataSource.Item) -> String? { switch item { case .durationPickerHourInterval: return "Hours" case .durationPickerMaximumDuration, .durationPickerMinimumDuration, .durationPickerSecondInterval, .durationPickerValue: return "Seconds" case .durationPickerMinuteInterval: return "Minutes" default: return nil } } private static func makeText(for item: DemoDataSource.Item, duration: TimeInterval, hourInterval: Int, minuteInterval: Int, secondInterval: Int, minimumDuration: TimeInterval?, maximumDuration: TimeInterval?) -> String? { switch item { case .durationPickerHourInterval: return String(hourInterval) case .durationPickerMinuteInterval: return String(minuteInterval) case .durationPickerMaximumDuration: if let maximumDuration { return String(maximumDuration) } return nil case .durationPickerMinimumDuration: if let minimumDuration { return String(minimumDuration) } return nil case .durationPickerSecondInterval: return String(secondInterval) case .durationPickerValue: return String(duration) default: return nil } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Computed Properties</title> <link rel="stylesheet" href="../assets/styles.css" /> <script src="../vue@3.2.37.js"></script> <!-- <script src="https://unpkg.com/vue@3"></script> --> </head> <body> <div id="app"> <div class="nav-bar"></div> <div class="cart">Cart({{cart}})</div> <div class="product-display"> <div class="product-container"> <div class="product-image"> <img :src="image" /> </div> <div class="product-info"> <h1>{{title}}</h1> <p v-if="inStock>10">有存货</p> <p v-else>缺货</p> <ul> <li v-for="detail in details">{{detail}}</li> </ul> <div v-for="(variant,i) in variants" :key="variant.id" @mouseover="updateVariant(i)" class="color-circle" :style="{backgroundColor:variant.color}" ></div> <button @click="addToCart" class="button" :disabled="inStock" :class="{disabledButton:inStock}" > 添加到购物车 </button> </div> </div> </div> </div> <script src="./main.js"></script> <script> // 可在控制台给vm.product赋值看到页面数据立马变化 const vm = app.mount("#app") </script> </body> </html>
import { useEffect, useState } from "react"; import axios from "axios"; import { Movie } from "./types"; import { motion, AnimatePresence } from "framer-motion"; function Filter({ movies, setFilterd, active, setActive, }: { movies: Movie[]; setFilterd: React.Dispatch<React.SetStateAction<Movie[]>>; active: number; setActive: (n: number) => void; }) { useEffect(() => { if (active === 0) { setFilterd(movies); return; } const filtered = movies.filter((m) => m.genre_ids.includes(active)); setFilterd(filtered); }, [active, movies, setFilterd]); console.log(active); return ( <div className="filter__container"> <button className={active === 0 ? "active" : ""} onClick={() => setActive(0)}> All </button> <button className={active === 35 ? "active" : ""} onClick={() => setActive(35)}> Comedy </button> <button className={active === 28 ? "active" : ""} onClick={() => setActive(28)}> Action </button> </div> ); } function App() { const API_KEY = "fa709d2ae4fdd55460fa7a306a8d152c"; const [movies, setMovies] = useState<Movie[]>([]); const [filterd, setFilterd] = useState<Movie[]>([]); const [active, setActive] = useState(0); useEffect(() => { const fetchData = async () => { const { data } = await axios.get( `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}&language=en-US&page=1` ); setMovies(data.results as Movie[]); setFilterd(data.results as Movie[]); }; fetchData(); }, []); return ( <div className=""> <Filter movies={movies} setFilterd={setFilterd} active={active} setActive={setActive} /> <motion.div layout className="popular__movies"> <AnimatePresence> {filterd.map((movie) => ( <motion.div animate={{ opacity: 1 }} initial={{ opacity: 0 }} exit={{ opacity: 0 }} key={movie.id} layout className="movie__item"> <h2>{movie.title}</h2> <img src={"https://image.tmdb.org/t/p/w500" + movie.backdrop_path} alt="" /> </motion.div> ))} </AnimatePresence> </motion.div> </div> ); } export default App;
import React, { useState, useEffect } from "react"; import HighScore, { loadHighScores } from "../Highscore"; import { Card, Typography } from "@material-ui/core"; import Spacer from "./Spacer"; interface Props { selectedGame?: HighScore; } export default ({ selectedGame }: Props) => { const [list, setList] = useState<HighScore[]>([]); useEffect(() => { const list = loadHighScores(); setList(list); setTimeout(() => scrollCurrentGameIntoView(list), 400); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const scrollCurrentGameIntoView = (listToUse: HighScore[]) => { if (selectedGame) { const currentGame = listToUse.findIndex( h => h.uniqueness === selectedGame!.uniqueness ); if (currentGame !== -1) { const target = document.querySelector(`#A${currentGame}`); if (target) { target.scrollIntoView({ behavior: "smooth" }); } } } }; const formatTime = (input: Date) => { let timeInSeconds = Math.floor(input.getTime() / 1000); let timeInMinutes = 0; while (timeInSeconds > 60) { timeInSeconds -= 60; timeInMinutes++; } return { min: timeInMinutes.toString().padStart(2, "0"), sec: timeInSeconds.toString().padStart(2, "0"), }; }; return ( <div style={{ maxHeight: "100%", height: "100%", overflow: "scroll", minWidth: "80vw", }} > {list.length === 0 && ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", }} > <Typography variant="h2"> Ingen scores endnu, du må hellere komme igang med at spille! </Typography> </div> )} {list.map((score, index) => { const { name, time, word, wrongLettersGuessed, calcScore, uniqueness, } = score; const { min, sec } = formatTime(time); return ( <Card key={index} id={"A" + index} className={ uniqueness === selectedGame?.uniqueness ? "newScore" : "" } style={{ margin: 15, display: "flex", alignItems: "center", padding: 15, }} > <Typography variant="h2">{index + 1}.</Typography> <Typography>{name}</Typography> <Spacer /> <Typography>{word}</Typography> <Spacer /> <div style={{ textAlign: "right" }}> <Typography>{calcScore()} point</Typography> <Typography> {wrongLettersGuessed} forkerte </Typography> <Typography> {min}:{sec} </Typography> </div> </Card> ); })} </div> ); };
How to Install the WeBWorK Problem Library Version 2.5 --- -- ------- --- ------- ------- ------- ------- --- Installing the problem library can be done in 5 steps. 1. Download and unpack files ---------------------------- The files can be obtained from cd /opt/webwork/libraries http://github.com/openwebwork/webwork-open-problem-library You can download the library as a zipfile, or using git software. Once you have downloaded the library, you will have a directory webwork-open-problem-library containing the following files and directories: INSTALL OPL_LICENSE OpenProblemLibrary/ README.md In the following instructions, the directory OpenProblemLibrary is refered to as the "problem library" 2. Tell WeBWorK where on your disk you put the problem library -------------------------------------------------------------- In the file $WEBWORK_ROOT/conf/localOverrides.conf, set the following values. The first one is where you put the problem library files in step 1. $problemLibrary{root} = "/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary"; $problemLibrary{version} = "2.5"; 3. Run the installation script ------------------------------ Run the command OPL-update which is in the directory $WEBWORK_ROOT/bin. If $WEBWORK_ROOT/bin is not in your path, you may need to specify the full path, which might look something like /opt/webwork/webwork2/bin/OPL-update The script will print diagnostic information as it goes. When it finishes, you are ready to go. 4. Adjust existing courses. --------------------------- If you have courses which had been accessing version 1 of the problem library, your courses will have a symbolic link in their templates directories called Library. Delete this link (rm Library). WeBWorK will make the correct new link for you the next time you use the library browser. 5. Using the Rochester problem library from OPL ----------------------------------------------- For many years, the canonical set of problems people would start with for their WeBWorK installation was the Rochester collection. All of those problems are now part of the OPL. Since development/refinement of OPL problems will continue, it is a good idea to use the OPL problems instead. If you have existing problem sets, or you simply want to be able to browse the Rochester problems as you always have, you can still use the OPL problems for this purpose. The trickiest part of the instructions for doing this is that different systems may have put files in different places. Here we assume: OPL is located at /opt/libary/webwork-open-problem-library/ProblemLibrary Rochester problems were a symbolic link in each course templates directory called "rochester_problib" (you may have to substitute your own value in the commands below). Then, move to the templates directory of a course: cd /opt/courses/MyCourseName/templates Then execute the commands: rm rochester_problib ln -s Library/Rochester rochester_problib Then repeat this for each existing course. In the future, if new courses are made by copying the templates directories from existing courses, the changes will be carried over automatically. Test and enjoy. Upgrading --------- First update the problems in the problem library. "cd" to the location of the problem library, which might be cd /opt/library/webwork-open-problem-library/OpenProblemLibrary depending on where you installed it initially. From that location, give the command git pull This will update any problems you have already, and download new problems if the problem library has grown. To register those new problems with the webwork library browser run webwork2/bin/OPL-update Send questions, problems, and other feedback to jj (at) asu.edu. Credit ------ This problem library was compiled in large part by support from the National Science Foundation.
package com.example.vision; import android.annotation.SuppressLint; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.TextView; public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; TextView view; public GPSTracker(Context context, TextView view) { this.mContext = context; this.view = view; getLocation(); } @SuppressLint("MissingPermission") public Location getLocation() { if (LightUtils.permissionsGranted(mContext)) { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled rip } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } else { view.setText("111"); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } }
// routes.h handles the server's routes // Importing Rhys Weatherly's cryptography library to use SHA256 encryption #include <Crypto.h> #include <SHA256.h> // Import the hash calculation function #include "auth_utils.h" // Import the publicIp variable #include "wifi_utils.h" // Import the html files #include "../views/wol_html.h" #include "../views/login_html.h" #include "../views/status_html.h" #include "../views/copyIp_html.h" // Sets the path handlers for the server variable inputed void setServerRoutes(SecureServer &secureServer) { // Home path handler secureServer.server.on("/", HTTP_GET, [&]() { if (secureServer.handleAuthentication("", secureServer.getAuthCookie())) { secureServer.redirectTo("/wol"); } else { secureServer.redirectTo("/login"); } }); // WOL path handler secureServer.server.on("/wol", HTTP_GET, [&]() { if (secureServer.handleAuthentication("", secureServer.getAuthCookie())) { secureServer.server.send(200, "text/html", wol_html); } else { secureServer.redirectTo("/login"); } }); // Success path handler secureServer.server.on("/success", HTTP_GET, [&]() { secureServer.server.send(200, "text/html", status_html); }); // Error path handler secureServer.server.on("/error", HTTP_GET, [&]() { secureServer.server.send(200, "text/html", status_html); }); // Copy ip page path handlers secureServer.server.on("/publicIp", HTTP_GET, [&]() { secureServer.redirectTo("/copyIp?ip=" + publicIp); }); secureServer.server.on("/copyIp", HTTP_GET, [&]() { secureServer.server.send(200, "text/html", copyIp_html); }); // Login path handler secureServer.server.on("/login", HTTP_GET, [&]() { if (secureServer.handleAuthentication("", secureServer.getAuthCookie())) { secureServer.redirectTo("/wol"); } else { secureServer.server.send(200, "text/html", login_html); } }); // Login submission handler secureServer.server.on("/login", HTTP_POST, [&]() { String username = secureServer.server.arg("username").substring(0, 16); String password = secureServer.server.arg("password").substring(0, 16); // Use a mix of the username and the password to create the credentials String credentials = calculateSHA256Hash(username + ":" + password); if (secureServer.handleAuthentication(credentials, secureServer.getAuthCookie())) { secureServer.redirectTo("/wol"); } else { secureServer.server.send(200, "text/html", login_html); } }); // WOL submission handler secureServer.server.on("/wol", HTTP_POST, [&]() { String macAddress = secureServer.server.arg("macAddress").substring(0, 17); String secureOn = secureServer.server.arg("secureOn").substring(0, 17); String broadcastAddress = secureServer.server.arg("broadcastAddress").substring(0, 17); String pin = secureServer.server.arg("pin").substring(0, 6); // Check if authenticated and TOTP PIN match using current time (time(nullptr)) if (secureServer.handleAuthentication("", secureServer.getAuthCookie()) && secureServer.isPinValid(pin)) { // Send magic packet to the equipment if (secureOn != "") { Serial.println("Sent SecureOn"); secureServer.WOL.sendSecureMagicPacket(macAddress.c_str(), secureOn.c_str()); // Convert String to const char * } else { Serial.println("Sent MAC only"); secureServer.WOL.sendMagicPacket(macAddress.c_str()); // Convert String to const char * } // Return success page and logout secureServer.redirectTo("success?message=Magic%20Packet%20sent%20to%20equipment."); secureServer.logout(secureServer.server.client().remoteIP()); } else { secureServer.logout(secureServer.server.client().remoteIP()); secureServer.redirectTo("error?message=Not%20Allowed"); } }); }
<template> <ul class="buttons-list"> <li class="buttons__item" v-for="index of floorsCount" :key="index"> <button class="buttons__button" type="button" @click="callElevator(index)" > {{ index }} </button> </li> </ul> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { props: { floorsCount: { type: Number, required: true, }, }, computed: { ...mapGetters(['getCurrentFloor']), isCurrentFloor: { get() { return this.getCurrentFloor === this.floor; }, set(value) { if (value) { this.addFloorToCallQueue(this.floor); this.$nextTick(() => { const stageHeight = 100; const elevator = document.querySelector('.elevator'); elevator.style.bottom = `${stageHeight * this.floor}px`; }); } }, }, }, methods: { ...mapActions(['addFloorToCallQueue', 'callElevator']), }, }; </script> <style> .buttons-list { display: flex; flex-direction: column-reverse; justify-content: space-around; margin: 0; padding: 0; list-style: none; } .buttons__button { width: 30px; height: 30px; font-weight: 600; background-color: transparent; border-color: aqua; cursor: pointer; transition: background-color 0.3s; } .buttons__button:hover { background-color: aqua; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="styles/styles.css" /> <link rel="stylesheet" href="styles/menu.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" /> <script src="script/menu.js" defer></script> <title>Intro section with dropdown navigation</title> </head> <body> <main class="content"> <!-- Navbar Start --> <header class="header"> <nav class="menu navbar"> <li><img class="logo_one" src="images/logo.svg" alt="logo" /></li> <ul class="nav-menu"> <div class="nav-opac"></div> <div class="nav-wrapper"> <li><img class="logo" src="images/logo.svg" alt="logo" /></li> <li class="item has-submenu"> <a id="item-one" class="main-item" tabindex="0" >Features<i class="fas fa-chevron-down"></i ></a> <ul class="submenu"> <li class="subitem"> <img class="icons" src="images/icon-todo.svg" alt="to-do-icon" srcset="" /><a href="#">Todo List</a> </li> <li class="subitem"> <img class="icons one" src="images/icon-calendar.svg" alt="calendar-icon" srcset="" /> <a href="#">Calendar</a> </li> <li class="subitem"> <img class="icons two" src="images/icon-reminders.svg" alt="reminders-icon" srcset="" /> <a href="#">Reminders</a> </li> <li class="subitem"> <img class="icons three" src="images/icon-planning.svg" alt="planning-icon" srcset="" /> <a href="#">planning</a> </li> </ul> </li> <li class="item has-submenu"> <a id="item-two" class="main-item" tabindex="0" >Company<i class="ftwo fas fa-chevron-down"></i ></a> <ul class="submenu"> <li class="subitem"><a href="#">History</a></li> <li class="subitem"><a href="#">Our Team</a></li> <li class="subitem"><a href="#">Blog</a></li> </ul> </li> <span class="space"></span> <!-- Line seperator --> <li class="nav-item"> <button class="btn careers">Careers</button> </li> <li class="nav-item"><button class="btn about">About</button></li> <li class="main-item nav-item login">Login</li> <li class="nav-item"> <button class="buttons">Register</button> </li> </div> </ul> <li class="toggle"></li> <div class="hamburger"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> </nav> </header> <!-- Navbar End --> <div class="wrapper"> <div class="container"> <div class="col_one"> <img class="hero-img" src="images/image-hero-desktop.png" alt="hero-image" /> </div> <div class="col_two"> <div class="desc"> <h1>Make remote work</h1> <p> Get your team in sync, no matter your location. Streamline processes, create team rituals, and watch productivity soar </p> <button class="buttons-l">Learn More</button> <div class="flex-icons"> <img class="icon-img" src="images/client-databiz.svg" alt="databiz-icon" /> <img class="icon-img" src="images/client-audiophile.svg" alt="audiophile-icon" /> <img class="icon-img" src="images/client-meet.svg" alt="meet-icon" /> <img class="icon-img" src="/images/client-maker.svg" alt="maker-icon" /> </div> </div> </div> </div> </div> </main> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Job Shifts Board</title> <link rel="stylesheet" href="../css/main.css"> <style> </style> </head> <body> <button id="showCalendarByWeek">Week</button> <button id="showCalendarByMonth">Month</button> <section class="records-container"> <div class="calendar-side-container"> <div class="calender-top">Clients</div> </div> <div class="calendars-container"> <!-- Calendars will be populated dynamically using JavaScript --> </div> </section> <script> // Array of job titles let jobTitles = ["Kitchen Potter", "Care Assistat", "Nurse", "Chef", "Warehouse Assistant"]; let totalJobs = jobTitles.length; const calendarsContainer = document.querySelector(".calendars-container"); const calenderDiv = document.createElement('div'); calenderDiv.classList.add('calendar'); // Create days container for each month const daysContainer = document.createElement('div'); daysContainer.classList.add('days'); //monthContainer.appendChild(daysContainer); calenderDiv.appendChild(daysContainer); calendarsContainer.appendChild(calenderDiv); // Define the from and to dates const fromDate = new Date('2023-12-28'); // Assuming format: YYYY-MM-DD const toDate = new Date('2024-01-12'); // Assuming format: YYYY-MM-DD // JavaScript code // Function to get the number of days in a specific month function getDaysInMonth(month, year) { return new Date(year, month, 0).getDate(); } // Function to populate days in the calendar function populateCalendars() { const screenWidth = window.innerWidth; const containerWidth = calendarsContainer.getBoundingClientRect().width; // Get the width of the container const dayWidth7 = Math.floor(containerWidth / 7) - 2; // Calculate the width of each day dynamically // Function to get the week of the year const getWeek = (date) => { const onejan = new Date(date.getFullYear(), 0, 1); return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7); } const formatDate = (date) => { const options = { day: 'numeric', weekday: 'short', month: 'short', year: 'numeric' }; const formattedDate = new Intl.DateTimeFormat('en-GB', options).format(date); const week = getWeek(date); // Extract individual parts of the formatted date const [dayMonth, month, year, weekday] = formattedDate.split(' '); return { dayMonth: dayMonth.replace(',', ''), // Remove comma after day of the month month, year, weekday, week: `Week ${week}` // Add week number }; }; // Loop through each date from 'fromDate' to 'toDate' const currentDate = new Date(fromDate); while (currentDate <= toDate) { const formatted = formatDate(currentDate); const date = new Date(currentDate); // Extract individual date components const dayOfWeek = date.getDay(); // Get the day of the week (0-6, where 0 represents Sunday) const dayOfMonth = date.getDate(); // Get the day of the month (1-31) const month = date.getMonth(); // Get the month (0-11) const year = date.getFullYear(); // Get the full year (e.g., 2023) // Calculate ISO week of the year const isoWeek = getISOWeek(date); // Custom function to get ISO week of the year // Define an array to map day of the week index to its name const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // Create an array containing the extracted date components const dateInfo = [daysOfWeek[dayOfWeek], dayOfMonth, month, year, isoWeek]; const dayElement = document.createElement('div'); dayElement.classList.add('calendar-day'); dayElement.innerHTML = ` <div class="calender-top"> <span class="day">${dayOfMonth}</span><br> ${daysOfWeek[dayOfWeek]} <span class="shift-hours">0 Hrs</span> </div> `; // Add 5 divs with different classes for (let i = 1; i <= totalJobs; i++) { const innerDiv = document.createElement('div'); innerDiv.classList.add('calendar-box'); dayElement.appendChild(innerDiv); } dayElement.style.width = dayWidth7 + 'px'; daysContainer.appendChild(dayElement); console.log(formatted); currentDate.setDate(currentDate.getDate() + 1); // Increment the date by 1 day } for(i=1;i<=0;i++){ const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const currentDate = new Date(); const currentMonth = currentDate.getMonth() + 1; const currentDay = currentDate.getDate(); const screenWidth = window.innerWidth; // Calculate the width of each day dynamically const dayWidth = Math.floor(screenWidth / 7) - 2; // Subtracting 2px for borders // Loop through each month from January to December for (let month = 1; month <= 12; month++) { const daysInMonth = getDaysInMonth(month, 2024); // Create container for each month const monthContainer = document.createElement('div'); monthContainer.classList.add('month'); // Give the first calendar a unique ID if (month === 1) { monthContainer.id = 'uniqueCalendar'; } // Create header for each month const monthHeader = document.createElement('div'); monthHeader.classList.add('header'); monthHeader.textContent = new Date(2024, month - 1, 1).toLocaleString('default', { month: 'long' }); //monthContainer.appendChild(monthHeader); // Create days container for each month const daysContainer = document.createElement('div'); daysContainer.classList.add('days'); // Create day elements for each month for (let day = 1; day <= daysInMonth; day++) { const dayElement = document.createElement('div'); dayElement.classList.add('calendar-day'); dayElement.innerHTML = ` <div class="calender-top"> <span class="day">${day}</span><br> ${daysOfWeek[new Date(2024, month - 1, day).getDay()]} <span class="shift-hours">0 Hrs</span> </div>`; // Add 5 divs with different classes for (let i = 1; i <= totalJobs; i++) { const innerDiv = document.createElement('div'); innerDiv.classList.add('calendar-box'); dayElement.appendChild(innerDiv); } dayElement.style.width = dayWidth + 'px'; daysContainer.appendChild(dayElement); // If it's the current day, add a class to style it differently if (month === currentMonth && day === currentDay) { dayElement.classList.add('current-day'); } } monthContainer.appendChild(daysContainer); calenderDiv.appendChild(monthContainer) calendarsContainer.appendChild(calenderDiv); // If it's the current month, scroll to the current day if (month === currentMonth) { const currentDayElement = monthContainer.querySelector('.current-day'); if (currentDayElement) { const scrollOffset = currentDayElement.offsetLeft - (calendarsContainer.offsetWidth / 2); calendarsContainer.scrollLeft = scrollOffset; } } } } } // Function to populate side with job titles function populateSide() { const calendarSide = document.querySelector(".calendar-side-container"); let i = 0; // Initialize loop counter // Loop through each job title and add to inner divs while (i < totalJobs) { const innerDiv = document.createElement('div'); innerDiv.classList.add('calendar-box'); // Add class based on current loop number innerDiv.textContent = jobTitles[i]; // Set inner text to current job title calendarSide.appendChild(innerDiv); i++; // Increment loop counter } } // Call the functions when the page loads window.addEventListener('load', function() { populateCalendars(); populateSide(); }); function getISOWeek(date) { const dayOfWeek = date.getDay() || 7; // Adjust for JavaScript's 0-indexed day of the week where Sunday is 0 const startOfYear = new Date(date.getFullYear(), 0, 1); const startOfWeek = new Date(startOfYear); startOfWeek.setDate(startOfWeek.getDate() + (1 - startOfWeek.getDay())); // Find the start of the week containing the first Thursday of the year const weekNumber = Math.ceil(((date - startOfWeek) / 86400000 + 1) / 7); // Calculate the week number return weekNumber; } // Function to show all days when the button is clicked function showCalendarByMonth() { const calendarsContainer = document.querySelector('.calendars-container'); const containerWidth = calendarsContainer.getBoundingClientRect().width; // Get the width of the container const dayWidth30 = Math.floor(containerWidth / 30) - 2; // Calculate the width of each day dynamically const dayElements = document.querySelectorAll('.calendar-day'); dayElements.forEach(dayElement => { dayElement.style.width = dayWidth30 + 'px'; }); } // Function to show all days when the button is clicked function showCalendarByWeek() { const calendarsContainer = document.querySelector('.calendars-container'); const containerWidth = calendarsContainer.getBoundingClientRect().width; // Get the width of the container const dayWidth7 = Math.floor(containerWidth / 7) - 2; // Calculate the width of each day dynamically const dayElements = document.querySelectorAll('.calendar-day'); dayElements.forEach(dayElement => { dayElement.style.width = dayWidth7 + 'px'; }); } // Add event listener to the button document.getElementById('showCalendarByMonth').addEventListener('click', showCalendarByMonth); document.getElementById('showCalendarByWeek').addEventListener('click', showCalendarByWeek); </script> </body> </html>
"""api URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.urls import path, include urlpatterns = [ path("submit/", include("cuckoo.web.api.submit.urls")), path("import/", include("cuckoo.web.api.importing.urls")), path("analysis/", include("cuckoo.web.api.analysis.urls")), path("analyses/", include("cuckoo.web.api.analyses.urls")), path("targets/", include("cuckoo.web.api.targets.urls")) ]
import { performance } from 'perf_hooks'; /** Number of decimal places to keep in timers */ const TruncateTimers = 4; /** * Utility to record some metrics about the execution of the function * * TODO this should be replaced by open telemetry */ export class Metrics { /** * Start time of all timers */ timers: Map<string, { start: number; duration?: number }> = new Map(); getTime(): number { return performance.now(); } /** * Start a timer at the current time * @param timeName name of timer to start */ public start(timeName: string): void { const existing = this.timers.get(timeName); if (existing != null && existing.duration == null) { throw new Error(`Duplicate startTime for "${timeName}"`); } this.timers.set(timeName, { start: this.getTime() }); } /** * End the timer, returning the duration in milliseconds * @param timeName timer to end */ public end(timeName: string): number { const timer = this.timers.get(timeName); if (timer == null) throw new Error(`Missing startTime information for "${timeName}"`); const duration = this.getTime() - timer.start; timer.duration = Number(duration.toFixed(TruncateTimers)); return duration; } /** Get list of all timers that have run */ public get metrics(): Record<string, number> | undefined { if (this.timers.size === 0) return undefined; const output: Record<string, number> = {}; for (const [key, timer] of this.timers.entries()) { if (timer.duration != null) output[key] = timer.duration; } return output; } /** Get a list of timers that never finished */ public get unfinished(): string[] | undefined { const st: string[] = []; for (const [key, timer] of this.timers.entries()) { if (timer.duration == null) st.push(key); } if (st.length === 0) return undefined; return st; } }
# Neo4j EC2 Instance Installation Assuming the EC2 instance is a Debian based distribution, ssh into it and run the following commands: ```shell sudo add-apt-repository -y ppa:openjdk-r/ppa sudo apt-get update wget -O - https://debian.neo4j.com/neotechnology.gpg.key | sudo apt-key add - echo 'deb https://debian.neo4j.com stable latest' | sudo tee -a /etc/apt/sources.list.d/neo4j.list sudo apt-get update sudo apt-get install neo4j=1:5.5.0 ``` Then `cd` to `etc/neo4j` and run `sudo vi neo4j.conf`, edit the following lines to what is shown below: ```shell server.bolt.listen_address=0.0.0.0:7687 server.http.listen_address=0.0.0.0:7474 server.https.listen_address=0.0.0.0:7474 ``` Commands for neo4j control: ```shell sudo service neo4j start sudo service neo4j stop sudo service neo4j restart ``` After saving the `conf` file, restart and go to EC2 security group to add inbound rules for the ports above (or all traffic if you just want to test). You can then access access the browser view of the database by navigating to `http://<IP-of-EC2>:7474/browser` and then follow the prompts to connect to the server.
🔔목차🔔 - [외래 키(Foreign Key)](#외래-키foreign-key) - [참조 무결성](#참조-무결성) - [관계](#관계) - [RDB에서의 관계](#rdb에서의-관계) - [Comment(댓글)](#comment댓글) - [Django Relationship fields](#django-relationship-fields) - [Comment 모델 정의](#comment-모델-정의) - [Django 관계 필드에서 외래 키의 필수 인자](#django-관계-필드에서-외래-키의-필수-인자) - [\(참고) 데이터 무결성](#참고-데이터-무결성) - [역참조](#역참조) - [댓글 기능 구현하기](#댓글-기능-구현하기) - [댓글 개수 출력하기](#댓글-개수-출력하기) - [댓글이 없을 때 대체 콘텐츠 출력하기](#댓글이-없을-때-대체-콘텐츠-출력하기) # 외래 키(Foreign Key) - 관계형 데이터베이스에서 한 테이블의 필드 중 다른 테이블의 행을 식별할 수 있는 키 - 참조되는 테이블의 기본 키를 가리킴 - 각 행에서 서로 다른 테이블 간의 관계를 만드는 데 사용 - 참조하는 테이블 행 1개의 값은 참조되는 측 테이블의 행 값에 대응 - 참조하는 테이블 행 여러개가 참조되는 테이블의 동일한 행 참조 가능 ## 참조 무결성 - 데이터베이스 관계 모델에서 관련된 2개의 테이블 간 일관성 - 외래 키가 선언된 테이블의 외래 키 속성(열)의 값은 그 테이블의 부모가 되는 테이블의 기본 키 값으로 존재해야 함 - 없는 값을 외래 키로 사용할 수 없음 # 관계 - 테이블 간 상호작용을 기반으로 설정되는 여러 테이블 간 논리적 연결 ## RDB에서의 관계 - 1:1 : 한 테이블의 단일 레코드가 다른 테이블의 레코드 한 개와 관련된 경우 - N:1 : 한 테이블의 0개 이상의 레코드가 다른 테이블의 레코드 한 개와 관련된 경우 - N:N : 한 테이블의 0개 이상 레코드가 다른 테이블의 0개 이상 레코드와 관련된 경우, 양쪽 모두에서 N:1 관계를 가짐 # Comment(댓글) - Comment 모델과 Article 모델 간 관계 설정 - 0개 이상의 댓글은 1개의 게시글에 작성될 수 있음 # Django Relationship fields ## Comment 모델 정의 ```python class Comment(models.Model): article = models.Foreignkey(Article, on_delete=models.CASCADE) # Article : 댓글을 달 게시물 모델 content = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): # 조회 시 content의 내용 표시 return self.content ``` ## Django 관계 필드에서 외래 키의 필수 인자 1. 참조하는 model class 2. on_delete 옵션 : 외래 키 참조 객체가 사라졌을 때 외래 키를 보유한 객체를 어떻게 처리할지 결정 - CASCADE : 부모 객체(게시글)이 삭제되었을 때 이를 참조하는 객체(댓글)도 삭제 - PROTECT, SET_NULL, SET_DEFAULT 등도 사용 가능 ### \(참고) 데이터 무결성 - 데이터의 정확성과 일관성을 유지하고 보증하는 것 - 무결성 제한의 유형(원칙) 1. 참조 무결성 : 참조하려는 객체가 존재해야 함 2. 개체 무결성 : 참조하려는 개체는 고유해야 함 3. 범위 무결성 : 참조 범위는 유효해야 함 ## 역참조 - 나를 참조하는 테이블(나를 외래 키로 지정한 테이블)을 참조(접근)하는 것 - N:1 관계에서 외래 키를 보유하지 않은 1이 N을 참조하는 경우 # 댓글 기능 구현하기 ## 댓글 개수 출력하기 1. length 사용 ``` {{ article.comment_set.all|length }} ``` 2. count() 사용 ``` {{ article.comment_set.count }} ``` ## 댓글이 없을 때 대체 콘텐츠 출력하기 {% if comments%} 이후의 {% for ~ %}와 {% endfor %} 사이에 {% empty %} 삽입 - 불러온 댓글 정보가 없는 경우 {% empty %}와 {% endfor %} 사이의 정보 출력
from django.core.exceptions import ValidationError from habits.models import Habit def validate_frequency(value): """ Проверяет частоту привычки. """ if value < 7: raise ValidationError("Частота привычки не может быть меньше 7 дней.") def validate_time_required(value): """ Проверяет необходимое время для привычки. """ if value > 120: raise ValidationError("Необходимое время не должно превышать 120 секунд.") class LinkedHabitValidator: def __init__(self, field): self.field = field def __call__(self, value): linked_habit = dict(value).get(self.field) if linked_habit is not None: habit = Habit.objects.get(pk=linked_habit.pk) if not habit.is_pleasant: raise ValidationError("Связанная привычка может быть только приятной.") class PleasantHabitValidator: def __init__(self, field): self.field = field def __call__(self, value): is_pleasant = dict(value).get("is_pleasant") tmp_val = dict(value).get(self.field) if is_pleasant and tmp_val is not None: raise ValidationError( "Приятная привычка не может иметь награду или связанную привычку." ) class LinkedHabitOrRewardValidator: """Проверка, что одновременно не назначено вознаграждение и связанная привычка""" def __init__(self, field): self.field = field def __call__(self, value): linked_habit = dict(value).get("linked_habit") reward = dict(value).get(self.field) if linked_habit is not None and reward is not None: raise ValidationError( "Нельзя одновременно выбрать вознаграждение и связанную привычку" )
<!-- BREADCRUMB --> <div id="breadcrumb" class="section"> <!-- container --> <div class="container"> <!-- row --> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb-tree"> <li><a href="#">Home</a></li> <li><a href="#">{{product.category}}</a></li> <li class="active">{{product.name}}</li> </ul> </div> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /BREADCRUMB --> <!-- SECTION --> <div class="section"> <!-- container --> <div class="container"> <!-- row --> <div class="row"> <!-- Product main img --> <div class="col-md-5 col-md-push-2"> <div id="product-main-img"> <ng-template [ngIf]="thumbImages.length === 0"> <div class="product-preview"> <img [src]="product.image" alt="{{ product.name }}" /> </div> </ng-template> <ng-template [ngIf]="thumbImages.length > 0"> <div class="product-preview" *ngFor="let t of thumbImages"> <img [src]="t" alt="{{ product.name }}" /> </div> </ng-template> </div> </div> <!-- /Product main img --> <!-- Product thumb imgs --> <div class="col-md-2 col-md-pull-5"> <ng-template [ngIf]="thumbImages.length > 0"> <div id="product-imgs"> <div class="product-preview" *ngFor="let t of thumbImages"> <img [src]="t" alt="{{ product.name }}" /> </div> </div> </ng-template> <ng-template [ngIf]="thumbImages.length === 0"> <div id="product-imgs"> <div class="product-preview" *ngFor="let t of thumbImages"> <img [src]="product.image" alt="{{ product.name }}" /> </div> </div> </ng-template> </div> <!-- /Product thumb imgs --> <!-- Product details --> <div class="col-md-5"> <div class="product-details"> <h2 class="product-name">{{ product.name }}</h2> <div> <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o"></i> </div> <a class="review-link" href="#">10 Review(s) | Add your review</a> </div> <div> <h3 class="product-price"> {{product.price | currency:'ARS'}} </h3> <span class="product-available">{{product.quantity>0 ? 'En Stock' : 'Fuera de Stock' }}</span> </div> <p> {{product.description}} </p> <div class="product-options"> <label> Size <select class="input-select"> <option value="0">X</option> </select> </label> <label> Color <select class="input-select"> <option value="0">Red</option> </select> </label> </div> <div class="add-to-cart"> <div class="qty-label"> Qty <div class="input-number"> <input type="number" [max]="product?.quantity >= 1 ? product?.quantity : 0" readonly #quantity min="1" value="{{product?.quantity >= 1 ? 1 : 0}}" /> <span class="qty-up" (click)="Increase()">+</span> <span class="qty-down" (click)="Decrease()">-</span> </div> </div> <button class="add-to-cart-btn" (click)="addToCart(product?.id)"> <i class="fa fa-shopping-cart"></i> Agregar Al Carrito </button> </div> <ul class="product-btns"> <li> <a href="#"><i class="fa fa-heart-o"></i> add to wishlist</a> </li> <li> <a href="#"><i class="fa fa-exchange"></i> add to compare</a> </li> </ul> <ul class="product-links"> <li>Category:</li> <li><a href="#">Headphones</a></li> <li><a href="#">Accessories</a></li> </ul> <ul class="product-links"> <li>Share:</li> <li> <a href="#"><i class="fa fa-facebook"></i></a> </li> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> <li> <a href="#"><i class="fa fa-google-plus"></i></a> </li> <li> <a href="#"><i class="fa fa-envelope"></i></a> </li> </ul> </div> </div> <!-- /Product details --> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /SECTION --> <!-- Section --> <div class="section"> <!-- container --> <div class="container"> <!-- row --> <div class="row"> <div class="col-md-12"> <div class="section-title text-center"> <h3 class="title">Related Products</h3> </div> </div> <!-- product --> <div class="col-md-3 col-xs-6"> <div class="product"> <div class="product-img"> <img src="./img/product01.png" alt="" /> <div class="product-label"> <span class="sale">-30%</span> </div> </div> <div class="product-body"> <p class="product-category">Category</p> <h3 class="product-name"><a href="#">product name goes here</a></h3> <h4 class="product-price"> $980.00 <del class="product-old-price">$990.00</del> </h4> <div class="product-rating"></div> <div class="product-btns"> <button class="add-to-wishlist"> <i class="fa fa-heart-o"></i ><span class="tooltipp">add to wishlist</span> </button> <button class="add-to-compare"> <i class="fa fa-exchange"></i ><span class="tooltipp">add to compare</span> </button> <button class="quick-view"> <i class="fa fa-eye"></i ><span class="tooltipp">quick view</span> </button> </div> </div> <div class="add-to-cart"> <button class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </div> </div> </div> <!-- /product --> <!-- product --> <div class="col-md-3 col-xs-6"> <div class="product"> <div class="product-img"> <img src="./img/product02.png" alt="" /> <div class="product-label"> <span class="new">NEW</span> </div> </div> <div class="product-body"> <p class="product-category">Category</p> <h3 class="product-name"><a href="#">product name goes here</a></h3> <h4 class="product-price"> $980.00 <del class="product-old-price">$990.00</del> </h4> <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> </div> <div class="product-btns"> <button class="add-to-wishlist"> <i class="fa fa-heart-o"></i ><span class="tooltipp">add to wishlist</span> </button> <button class="add-to-compare"> <i class="fa fa-exchange"></i ><span class="tooltipp">add to compare</span> </button> <button class="quick-view"> <i class="fa fa-eye"></i ><span class="tooltipp">quick view</span> </button> </div> </div> <div class="add-to-cart"> <button class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </div> </div> </div> <!-- /product --> <div class="clearfix visible-sm visible-xs"></div> <!-- product --> <div class="col-md-3 col-xs-6"> <div class="product"> <div class="product-img"> <img src="./img/product03.png" alt="" /> </div> <div class="product-body"> <p class="product-category">Category</p> <h3 class="product-name"><a href="#">product name goes here</a></h3> <h4 class="product-price"> $980.00 <del class="product-old-price">$990.00</del> </h4> <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o"></i> </div> <div class="product-btns"> <button class="add-to-wishlist"> <i class="fa fa-heart-o"></i ><span class="tooltipp">add to wishlist</span> </button> <button class="add-to-compare"> <i class="fa fa-exchange"></i ><span class="tooltipp">add to compare</span> </button> <button class="quick-view"> <i class="fa fa-eye"></i ><span class="tooltipp">quick view</span> </button> </div> </div> <div class="add-to-cart"> <button class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </div> </div> </div> <!-- /product --> <!-- product --> <div class="col-md-3 col-xs-6"> <div class="product"> <div class="product-img"> <img src="./img/product04.png" alt="" /> </div> <div class="product-body"> <p class="product-category">Category</p> <h3 class="product-name"><a href="#">product name goes here</a></h3> <h4 class="product-price"> $980.00 <del class="product-old-price">$990.00</del> </h4> <div class="product-rating"></div> <div class="product-btns"> <button class="add-to-wishlist"> <i class="fa fa-heart-o"></i ><span class="tooltipp">add to wishlist</span> </button> <button class="add-to-compare"> <i class="fa fa-exchange"></i ><span class="tooltipp">add to compare</span> </button> <button class="quick-view"> <i class="fa fa-eye"></i ><span class="tooltipp">quick view</span> </button> </div> </div> <div class="add-to-cart"> <button class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </div> </div> </div> <!-- /product --> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /Section -->
%% EBOT, an erlang web crawler. %% Copyright (C) 2010 ~ matteo DOT redaelli AT libero DOT it %% http://www.redaelli.org/matteo/ %% %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %% %%%------------------------------------------------------------------- %%% File : ebot_url_util.erl %%% Author : matteo <<matteo.redaelli@@libero.it> %%% Description : %%% %%% Created : 4 Oct 2009 by matteo <matteo@redaelli.org> %%%------------------------------------------------------------------- -module(ebot_url_util). -author("matteo.redaelli@@libero.it"). %% API -export([ convert_to_absolute_url/2, filter_external_links/2, is_external_link/2, is_same_domain/2, is_same_main_domain/2, is_subdomain/2, is_valid_image/1, is_valid_link/1, is_valid_url/1, normalize_url/2, parse_url/1, url_context/1, url_depth/1, url_domain/1, url_main_domain/1 ]). %%-------------------------------------------------------------------- %% Function: convert_to_absolute_url %% Input: an url and its referral/parent url %% Description: converts relative urls to absolute %%-------------------------------------------------------------------- convert_to_absolute_url( Url, ParentUrl) -> %% does the string start with http:// or https:// ? %% remember that in RE s? matches "s" or "" case re:run(Url, "^https?://") of {match, _L} -> Url; nomatch -> {Domain,Folder,_File,_Query} = parse_url(ParentUrl), case re:run(Url, "^/") of {match, _L} -> Domain ++ Url; nomatch -> Domain ++ normalize_path(Folder ++ Url) end end. filter_external_links(Url, Links) -> lists:filter( fun(L) -> is_external_link(Url, L) end, Links). is_same_domain(Url1, Url2) -> url_domain(Url1) == url_domain(Url2). is_same_main_domain(Url1, Url2) -> %% error_logger:info_report({?MODULE, ?LINE, {is_same_main_domain, Url1, Url2}}), url_main_domain(Url1) == url_main_domain(Url2). is_subdomain(Url1, Url2) -> is_same_main_domain(Url1, Url2) andalso url_domain(Url1) =/= url_domain(Url2). is_external_link(Url1, Url2) -> not is_same_domain(Url1, Url2). is_valid_image(Url) when is_binary(Url) -> is_valid_image(binary_to_list(Url)); is_valid_image(Url) -> {ok, Options} = ebot_util:get_env(is_valid_image), is_valid(Url, Options). is_valid_link(Url) when is_binary(Url) -> is_valid_link(binary_to_list(Url)); is_valid_link(Url) -> {ok, Options} = ebot_util:get_env(is_valid_link), is_valid(Url, Options). is_valid_url(Url) when is_binary(Url) -> is_valid_url(binary_to_list(Url)); is_valid_url(Url) -> {ok, Options} = ebot_util:get_env(is_valid_url), is_valid(Url, Options). %%-------------------------------------------------------------------- %% Function: normalize_url/2 %% Input: an url and its options (see config files) %% Description: converts relative urls to absolute %%-------------------------------------------------------------------- normalize_url(Url, Options) when is_binary(Url) -> NewUrl = normalize_url(binary_to_list(Url), Options), list_to_binary(NewUrl); normalize_url(Url, [{plugin, Module, Function}|Options]) -> NewUrl = Module:Function(Url), normalize_url(NewUrl, Options); normalize_url(Url, [{replace_string, RElist}|Options]) -> NewUrl = ebot_util:string_replacements_using_regexps(Url, RElist), normalize_url(NewUrl, Options); normalize_url(Url, [add_final_slash|Options]) -> NewUrl = url_add_final_slash(Url), normalize_url(NewUrl, Options); normalize_url(Url, [{max_depth,MaxDepth}|Options]) -> NewUrl = url_using_max_depth(Url, MaxDepth), normalize_url(NewUrl, Options); normalize_url(Url, [strip|Options]) -> NewUrl = string:strip(Url, both, $ ), normalize_url(NewUrl, Options); normalize_url(Url, [without_internal_links|Options]) -> NewUrl = url_without_internal_links(Url), normalize_url(NewUrl, Options); normalize_url(Url, [without_queries|Options]) -> NewUrl = url_without_queries(Url), normalize_url(NewUrl, Options); normalize_url(Url, [Opt|Options]) -> error_logger:error_report({?MODULE, ?LINE, {normalize_url, Url, unknown_option, Opt}}), normalize_url(Url, Options); normalize_url(Url, []) -> Url. parse_path(Path) -> Sep = string:rstr(Path,"/"), {string:sub_string(Path,1, Sep), string:sub_string(Path, Sep + 1)}. parse_url(Url) when is_binary(Url) -> parse_url( binary_to_list(Url)); parse_url(Url) -> case http_uri:parse(Url) of {error, Result} -> {error, Result}; {Protocol,_,Root,Port,Path,Query} -> %% TODO: should check protocol/port and not only port case Port of 80 -> P = ""; 443 -> P = ""; _Else -> P = ":" ++ integer_to_list(Port) end, Domain = atom_to_list(Protocol) ++ "://" ++ Root ++ P, {Folder, File} = parse_path(Path), {Domain,Folder,File,Query} end. url_context(Url) -> {Domain,Folder,_File,_Query} = parse_url(Url), Domain ++ Folder. url_depth(Url) -> {_Domain,Folder,_File,_Query} = parse_url(Url), length(string:tokens(Folder, "/")). url_domain(Url) -> {Domain,_,_,_} = ebot_url_util:parse_url(Url), Domain. url_main_domain(Url) -> %% error_logger:info_report({?MODULE, ?LINE, {url_main_domain, Url, start}}), {Domain,_,_,_} = ebot_url_util:parse_url(Url), [Protocol, Host] = re:split(Domain, "//", [{return,list}]), List = re:split(Host, "[.]", [{return,list}]), case lists:reverse(List) of [Dom1, Dom2|_] -> Protocol ++ "//" ++ Dom2 ++ "." ++ Dom1; Else -> error_logger:error_report({?MODULE, ?LINE, {url_main_domain, Url, too_short_url, Else}}), {error, too_short_url} end. %% EBOT_Url specific Internal functions is_valid(Url, [{validate_any_mime_regexps, RElist}|Options]) -> Mime = mochiweb_util:guess_mime(Url), ebot_util:is_valid_using_any_regexps(Mime, RElist) andalso is_valid(Url, Options); is_valid(Url, [{validate_all_url_regexps, RElist}|Options]) -> ebot_util:is_valid_using_all_regexps(Url, RElist) andalso is_valid(Url, Options); is_valid(Url, [{validate_any_url_regexps, RElist}|Options]) -> ebot_util:is_valid_using_any_regexps(Url, RElist) andalso is_valid(Url, Options); is_valid(Url, [{plugin, Module, Function}|Options]) -> Module:Function(Url) andalso is_valid(Url, Options); is_valid(_Url, []) -> true. normalize_path(Path) -> Tokens = lists:reverse(string:tokens(Path,"/")), case normalize_path( Tokens, {0,[]}) of {ok, ""} -> "/"; {ok, NewTokens} -> "/" ++ string:join(NewTokens,"/"); {error, _} -> "/" end. normalize_path([".."|L], {Cont,NewList}) -> normalize_path(L, {Cont + 1,NewList}); normalize_path([_|L], {Cont,NewList}) when Cont > 0 -> normalize_path(L, {Cont - 1,NewList}); % skipping unuseful ./ normalize_path(["."|L], {Cont,NewList}) when Cont == 0 -> normalize_path(L, {Cont,NewList}); normalize_path([E|L], {Cont,NewList}) when Cont == 0 -> normalize_path(L, {Cont,[E|NewList]}); normalize_path([], {0,NewList}) -> {ok,NewList}; normalize_path([], {_,_}) -> error_logger:info_report({?MODULE, ?LINE, {normalize_path, too_many_backs}}), {error, too_many_backs}. url_add_final_slash(Url) -> case re:run(Url, "^http://.+/") of {match, _} -> Url; nomatch -> error_logger:info_report({?MODULE, ?LINE, {added_final_slash_to, Url}}), Url ++ "/" end. url_unparse({Domain,Folder,File,Query}) -> Domain ++ Folder ++ File ++ Query. url_using_max_depth(Url, MaxDepth) -> Depth = url_depth(Url), url_using_max_depth(Url, MaxDepth, Depth). url_using_max_depth(Url, MaxDepth, Depth) when Depth =< MaxDepth-> Url; url_using_max_depth(Url, MaxDepth, _Depth) -> {Domain,Folder,_File,_Query} = parse_url(Url), Tokens = string:tokens(Folder, "/"), NewTokens = lists:sublist(Tokens, MaxDepth), NewFolder = "/" ++ string:join(NewTokens,"/") ++ "/", NewUrl = url_unparse({Domain,NewFolder,"",""}), error_logger:info_report({?MODULE, ?LINE, {renamed_url, Url, NewUrl}}), NewUrl. url_without_internal_links(Url) -> {Scheme, Netloc, Path, Query, _Fragment} = mochiweb_util:urlsplit(Url), mochiweb_util:urlunsplit({Scheme, Netloc, Path, Query,[]}). url_without_queries(Url) -> {Scheme, Netloc, Path, _Query, _Fragment} = mochiweb_util:urlsplit(Url), mochiweb_util:urlunsplit({Scheme, Netloc, Path, [],[]}). %% EUNIT TESTS -include_lib("eunit/include/eunit.hrl"). -ifdef(TEST). ebot_url_test() -> Domain = "http://www.redaelli.org", Home = "http://www.redaelli.org/", Utest = "http://www.redaelli.org/matteo/ebot_test/", Udir1 = "http://www.redaelli.org/matteo/ebot_test/dir1/", Udir11 = "http://www.redaelli.org/matteo/ebot_test/dir1/dir11/", Utyre1 = "http://www.tyres-pneus-online.co.uk/car-tyres-FORTUNA/F1000/155,65,R13,73,T.html", [ ?assertEqual(Home, url_add_final_slash(Domain)), ?assertEqual(Home, convert_to_absolute_url("../../", Utest)), ?assertEqual(0, ebot_url_util:url_depth(Domain)), ?assertEqual(0, ebot_url_util:url_depth(Home)), ?assertEqual(0, ebot_url_util:url_depth(Home ++ "index.html")), ?assertEqual(1, ebot_url_util:url_depth(Home ++ "matteo/index.html")), ?assertEqual(2, ebot_url_util:url_depth(Utest)), ?assertEqual(3, ebot_url_util:url_depth(Udir1)), ?assertEqual(4, ebot_url_util:url_depth(Udir11)), ?assertEqual(2, ebot_url_util:url_depth(Utyre1)), ?assertEqual(Domain, url_domain(Home)), ?assertEqual(Domain, url_domain(Utest)), ?assertEqual(Domain, url_domain(Udir1)), ?assertEqual(Utest, url_using_max_depth(Udir1, 2)), ?assertEqual(Utest, url_using_max_depth(Udir11, 2)), ?assertEqual(Udir1, url_using_max_depth(Udir1, 3)), ?assertEqual(Udir11, url_using_max_depth(Udir11, 4)), ?assertEqual(Utyre1, url_using_max_depth(Utyre1, 4)), ?assertEqual(Utyre1, url_using_max_depth(Utyre1, 4)), ?assertEqual(Utyre1, url_using_max_depth(Utyre1, 2)), ?assertEqual("http://www.tyres-pneus-online.co.uk/car-tyres-FORTUNA/", url_using_max_depth(Utyre1, 1)), ?assertEqual(true, is_external_link( <<"http://github.com/matteoredaelli/ebot">>, <<"http://www.redaelli.org/">>)), ?assertEqual(false, is_external_link( <<"http://www.redaelli.org/matteo/">>, <<"http://www.redaelli.org/">>)), ?assertEqual(false, is_same_domain( <<"http://github.com/matteoredaelli/ebot">>, <<"http://www.redaelli.org/">>)), ?assertEqual(true, is_same_domain( <<"http://www.redaelli.org/matteo/">>, <<"http://www.redaelli.org/">>)), ?assertEqual( "http://redaelli.org", url_main_domain(<<"http://www.redaelli.org/aa/">>)), ?assertEqual( "http://redaelli.org", url_main_domain(<<"http://www.matteo.redaelli.org/aa/a">>)), ?assertEqual( "http://redaelli.org", url_main_domain(<<"http://redaelli.org/aa/a">>)), ?assertEqual(true, is_same_main_domain(<<"http://www.redaelli.org/matteo/">>, <<"http://matteo.redaelli.org/">>)), ?assertEqual(true, is_same_main_domain(<<"http://redaelli.org/matteo/">>, <<"http://matteo.redaelli.org/">>)), ?assertEqual(true, is_same_main_domain(<<"http://redaelli.org/matteo/">>, <<"http://www.matteo.redaelli.org/">>)), ?assertEqual(false, is_same_main_domain(<<"http://redaelli.org/matteo/">>, <<"http://matteoredaelli.wordpress.com/">>)), ?assertEqual(true, is_subdomain(<<"http://redaelli.org/matteo/">>, <<"http://www.matteo.redaelli.org/">>)), ?assertEqual(true, is_subdomain(<<"http://aaa.redaelli.org/matteo/">>, <<"http://www.matteo.redaelli.org/">>)), ?assertEqual(false, is_subdomain(<<"http://www.redaelli.org/matteo/blog/">>, <<"http://www.redaelli.org/">>)), ?assertEqual(false, is_subdomain(<<"http://www.redaelli.org/matteo/">>, <<"http://matteoredaelli.wordpress.com/">>)) ]. -endif.
package com.example.contactsapp import android.annotation.SuppressLint import android.app.Activity import android.app.Instrumentation.ActivityResult import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.provider.ContactsContract import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { private val REQUEST_PHONE_NUMBER = 111 lateinit var contactUri: Uri override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val selectContacts = findViewById<Button>(R.id.selectContacts) selectContacts.setOnClickListener { val intent = Intent(Intent.ACTION_PICK) intent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE; startActivityForResult(intent, REQUEST_PHONE_NUMBER) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_PHONE_NUMBER && resultCode == Activity.RESULT_OK) { contactUri = data!!.data!! getPhoneNumber() } } @SuppressLint("Range") private fun getPhoneNumber() { val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER) val cursor = contentResolver.query(contactUri, projection, null, null, null); cursor?.use { if (it.moveToFirst()) { val name = it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); val phoneNumber = it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); val nameText = findViewById<TextView>(R.id.name) val phoneText = findViewById<TextView>(R.id.phoneNumber) nameText.text = name phoneText.text = phoneNumber } } } }
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; use App\Mail\EmailVerification; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Password; class AuthController extends Controller { /** * Register a new user. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\JsonResponse */ public function register(Request $request) { try { $validatedData = $request->validate([ 'name' => 'required|string', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|confirmed', ]); $user = User::create([ 'name' => $validatedData['name'], 'email' => $validatedData['email'], 'password' => Hash::make($validatedData['password']), 'email_verified_at' => null, ]); $this->sendEmailVerificationNotification($user); return response()->json(['message' => 'User registered successfully. Please verify your email address.']); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 400); } } /** * Send email verification notification to the user. * * @param \App\Models\User $user * @return void */ protected function sendEmailVerificationNotification($user) { Mail::to($user->email)->send(new EmailVerification($user)); } /** * Authenticate the user and issue a token. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\JsonResponse */ public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required|string', ]); if (Auth::attempt($request->only('email', 'password'))) { $user = Auth::user(); $token = $user->createToken('AuthToken')->accessToken; return response()->json(['token' => $token]); } return response()->json(['error' => 'Unauthorized'], 401); } /** * Get the authenticated user details. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\JsonResponse */ public function getUser(Request $request) { if (Auth::check()) { $user = Auth::user(); return response()->json($user); } else { return response()->json(['error' => 'Unauthorized'], 401); } } /** * Reset the user's password. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\JsonResponse */ public function resetPassword(Request $request) { $request->validate([ 'email' => 'required|email', 'token' => 'required|string', 'password' => 'required|string|confirmed|min:8', ]); $status = Password::reset( $request->only('email', 'token', 'password', 'password_confirmation'), function ($user, $password) { $user->forceFill([ 'password' => bcrypt($password), ])->save(); } ); if ($status === Password::PASSWORD_RESET) { return response()->json(['message' => 'Password reset successfully'], 200); } else { return response()->json(['error' => 'Unable to reset password'], 400); } } /** * Send a reset link to the given user. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\JsonResponse */ public function sendResetLinkEmail(Request $request) { $request->validate([ 'email' => 'required|email', ]); $status = Password::sendResetLink($request->only('email')); if ($status === Password::RESET_LINK_SENT) { return response()->json(['message' => 'Password reset link sent to your email'], 200); } else { return response()->json(['error' => 'Unable to send reset link'], 400); } } public function index() { $users = User::all(); return response()->json(['users' => $users], 200); } public function showAuthenticatedUser(Request $request) { $user = Auth::user(); if (!$user) { return response()->json(['error' => 'User not authenticated'], 401); } return response()->json(['user' => $user], 200); } }
use strict; use warnings; # Copyright (C) 2015 Christian Garbs <mitch@cgarbs.de> # Licensed under GNU GPL v2 or later. package Net::Fritz; # ABSTRACT: AVM Fritz!Box interaction via TR-064 =head1 SYNOPSIS use Net::Fritz::Box; my $fritz = Net::Fritz::Box->new(); if ($fritz->error) { die $fritz->error; } my $device = $fritz->discover(); $device->errorcheck; my $service = $device->find_service('DeviceInfo:1'); $service->errorcheck; my $response = $service->call('GetSecurityPort'); $response->errorcheck; printf "SSL communication port is %d\n", $response->data->{NewSecurityPort}; # dump all available devices and services print Net::Fritz::Box->new()->discover()->dump(); You also need to enable TR-064 on your Fritz!Box, see L</"CONFIGURATION AND ENVIRONMENT">. =head1 DESCRIPTION L<Net::Fritz> is a set of modules to communicate with an AVM Fritz!Box (and possibly other routers as well) via the TR-064 protocol. I wanted to initiate calls via commandline, but I only found GUI tools to do that or libraries in other languages than Perl, so I have built this library. Luckily, the TR-064 protocol announces all available services via XML. So this module does some HTTP or HTTPS requests to find the router, query it's services and then calls them via SOAP. Parameter names and counts are verified against the service specification, but L<Net::Fritz> itself knows nothing about the available services or what they do. =head1 INTERFACE L<Net::Fritz::Box> is the main entry point and initializes a basic object with some configuration information (URL of the Fritz!Box, authentication data etc.). Use the C<discover()> method to get a L<Net::Fritz::Device> which represents your router. A device may contain further L<Net::Fritz::Device> subdevices, eg. a LAN or WAN interface. But most importantly, a device should contain at least one L<Net::Fritz::Service> on which different methods can be C<call()>ed to set or read parameters or do various things. A method call will return L<Net::Fritz::Data> which is a simple wrapper about the data returned (normally a hash containing all return values from the called service). L<Net::Fritz::Error> is returned instead of the other objects whenever something goes wrong. Finally, there is L<Net::Fritz::IsNoError>, which is just a role to provide all valid (non-error) objects with C<error> and C<errorcheck()> so that you can query every C<Net::Fritz::> object for its error state. =head1 CONFIGURATION AND ENVIRONMENT To set up your Fritz!Box, you have to enable the remote administration via TR-064 in the web administration interface. Nearly all services except C<GetSecurityPort> from the example above need authentication. The best way to achieve this is to add an extra user with its own password (again via the web administration interface). The user needs the permission to change and edit the Fritz!Box configuration. If you want to call the VoIP services, it needs that permission as well. Then use the I<username> and I<password> parameters of C<Net::Fritz::Box->new()>. =head1 BUGS AND LIMITATIONS To report a bug, please use the github issue tracker: L<https://github.com/mmitch/fritz/issues> =head2 event subscriptions Apart from exposing the L<eventSubURL|Net::Fritz::Service/eventSubURL> of a L<Net::Fritz::Service> there is currently no support for event subscriptions. =head2 TR-064 protocol L<Net::Fritz> implements parts of the TR-064 protocol, which could be separated in to a C<Net::Protocol::TR064> distribution or something like that. I have not yet done this because I don't know much about the TR-064 protocol, I just implemented everything I needed to get the Fritz!Box communication running. If anybody comes along and identifies the code parts that belong to TR-064, I'm happy to move them out to another package. Apart from the authentication scheme it should be pretty straight-forward to split the modules. There might also be some parts in here that look vaguely like UPnP... =head1 AVAILABILITY =over =item github repository L<git://github.com/mmitch/fritz.git> =item github browser L<https://github.com/mmitch/fritz> =item github issue tracker L<https://github.com/mmitch/fritz/issues> =back =begin html =head1 BUILD STATUS <p><a href="https://travis-ci.org/mmitch/fritz"><img src="https://travis-ci.org/mmitch/fritz.svg?branch=master" alt="Build Status"></a></p> =end html =begin html =head1 TEST COVERAGE <p><a href="https://codecov.io/github/mmitch/fritz?branch=master"><img src="https://codecov.io/github/mmitch/fritz/coverage.svg?branch=master" alt="Coverage Status"></a></p> =end html =head1 SEE ALSO =over =item * L<WebService::FritzBox> for communicating with a Fritz!Box without the TR-064 protocol (eg. to list current bandwidth) =item * L<AVM interface documentation|http://avm.de/service/schnittstellen/> =back =cut 1;
import { AccountIcon, PasswordIcon, RoleIcon } from "@/components/icons"; import { Button, Card, Form, Input, Select } from "antd"; import "./index.less"; import { useStore } from "@/stores"; import { useNavigate } from "react-router-dom"; import { observer } from "mobx-react-lite"; const Login = () => { const { loginStore } = useStore(); let navigate = useNavigate(); type FieldType = { role?: string; account?: string; password?: string; }; const handleLoginBtnClick = (values: any) => { const res = loginStore.login(values); if (res) { navigate("/first-hop", { replace: true }); } }; return ( <div className="flex justify-center"> <video className="w-full -z-10 fixed" autoPlay loop muted> <source src="/images/background.mp4" type="video/mp4" /> Your browser does not support the video tag. </video> <Card className="login-panel"> <div className="text-xl m-b-2"> <b>管理平台</b> </div> <Form onFinish={handleLoginBtnClick} requiredMark={false}> <Form.Item<FieldType> name="role" rules={[{ required: true, message: "请选择您的角色!" }]} > <Select className="input-basic" size="large" placeholder={ <div className="flex items-center"> <RoleIcon /> <div className="m-l-1">请选择角色,默认选择管理员</div> </div> } options={[ { value: "user", label: "用户" }, { value: "admin", label: "管理员" }, ]} /> </Form.Item> <Form.Item<FieldType> name="account" rules={[{ required: true, message: "请输入您的账号!" }]} > <Input className="input-basic" size="large" prefix={<AccountIcon />} placeholder="请输入账号,默认账号admin" /> </Form.Item> <Form.Item<FieldType> name="password" rules={[{ required: true, message: "请输入您的密码!" }]} > <Input.Password className="input-basic" size="large" prefix={<PasswordIcon />} placeholder="请输入密码,默认密码123456" /> </Form.Item> <Form.Item className="flex justify-center"> <Button className="login-btn" htmlType="submit"> 登录 </Button> </Form.Item> </Form> </Card> </div> ); }; export default observer(Login);
grammar Desc; options { language = C; output = AST; } @header { #include <vector> #include <string> #include "DataTypeManager.h" using std::vector; using std::string; #ifndef TXT #define TXT(x) ((const char*)(x->getText(x))->chars) #endif #ifndef TXTN #define TXTN(x) ((NormalizeQuotes((const char*)(x->getText(x))->chars)).c_str()) #endif #ifndef TXTS #define TXTS(x) ((StripQuotes((const char*)(x->getText(x))->chars)).c_str()) #endif #ifndef STR #define STR(X) ( string(TXT(X)) ) #endif #ifndef STRN #define STRN(X) ( string(TXTN(X)) ) #endif #ifndef STRS #define STRS(X) ( string(TXTS(X)) ) #endif } @members { static DataTypeManager & dTM = DataTypeManager::GetDataTypeManager(); extern string StripQuotes(string str); extern string NormalizeQuotes(string str); } /* Keywords */ FUNCTION : 'function' | 'Function' | 'FUNCTION'; OPKEYWORD : 'operator' | 'Operator' | 'OPERATOR'; DATATYPE : 'datatype' | 'Datatype' | 'DATATYPE'; SYNONYM : 'synonym' | 'Synonym' | 'SYNONYM'; TEMPLATE : 'template' | 'Template' | 'TEMPLATE'; GLA : 'gla' | 'Gla' | 'GLA'; GF : 'gf' | 'Gf' | 'GF'; GTRAN : 'gt' | 'Gt' | 'GT'; GIST : 'gist' | 'Gist' | 'GIST'; DEFINE : 'define' | 'Define' | 'DEFINE'; FROM : 'from' | 'From' | 'FROM'; AS : 'as' | 'As' | 'AS'; REQUIRES : 'requires' | 'Requires' | 'REQUIRES'; /* Base stuff */ INT : '0'..'9'+ 'L'? ; COMMENT : '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;} | '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;} ; WS : ( ' ' | '\t' | '\r' | '\n' ) {$channel=HIDDEN;} ; ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; STRING : '\'' ( ESC_SEQ | ~('\''|'\\') )* '\'' | '"' ( ESC_SEQ | ~('\\'|'"') )* '"' ; SEMICOLON : ';' ; COMMA : ',' ; COLON : ':' ; LPAREN : '(' ; RPAREN : ')' ; LSQ : '['; RSQ : ']'; ARROW : '->'; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment ESC_SEQ : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\') | UNICODE_ESC | OCTAL_ESC ; fragment OCTAL_ESC : '\\' ('0'..'3') ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ; fragment UNICODE_ESC : '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ; // Actual parser stuff parse : statements ; statements : (statement SEMICOLON!)+ ; statement : DEFINE defineStatement -> defineStatement ; defineStatement : DATATYPE n=ID FROM f=STRING { dTM.AddBaseType(STR($n), STRS($f)); } | SYNONYM syn=ID FROM base=ID { dTM.AddSynonymType(STR($syn), STR($base)); } | FUNCTION n=ID LPAREN params=typeList RPAREN ARROW ret=ID FROM f=STRING { dTM.AddFunctions(STR($n), $params.vect, STR($ret), STRS($f), true ); } | OPKEYWORD op=STRING LPAREN params=typeList RPAREN ARROW ret=ID FROM f=STRING { dTM.AddFunctions(STRS($op), $params.vect, STR($ret), STRS($f), true ); } | GLA n=ID states=reqStateList LPAREN params=typeList RPAREN ARROW LPAREN retList=typeList RPAREN FROM f=STRING { dTM.AddGLA( STR($n), $params.vect, $retList.vect, STRS($f), $states.vect ); } | GTRAN n=ID states=reqStateList LPAREN params=typeList RPAREN ARROW LPAREN retList=typeList RPAREN FROM f=STRING { dTM.AddGT( STR($n), $params.vect, $retList.vect, STRS($f), $states.vect ); } | GF n=ID states=reqStateList LPAREN params=typeList RPAREN FROM f=STRING { dTM.AddGF( STR($n), $params.vect, STRS($f), $states.vect ); } | GIST n=ID states=reqStateList ARROW LPAREN (retList=typeList) RPAREN FROM f=STRING { dTM.AddGIST( STR($n), $states.vect, $retList.vect, STRS($f) ); } | n=ID AS ty=ID { dTM.AddSynonymType(STR($syn), STR($ty)); } ; typeList returns [vector<string> vect] : /* nothing */ | a=ID {$vect.push_back(STR($a));} (COMMA b=ID {$vect.push_back(STR($b));})* ; reqStateList returns [vector<string> vect] : LSQ states=typeList {$vect = $states.vect; } RSQ | /* nothing */ ;
<template> <div class="app-container"> <!-- 搜索工作栏 --> <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"> <el-form-item label="状态" prop="status"> <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 240px"> <el-option v-for="dict in userStatusDict" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)"/> </el-select> </el-form-item> <el-form-item label="公司名称" prop="companyName"> <el-input v-model="queryParams.companyName" placeholder="请输入公司名称" clearable @keyup.enter.native="handleQuery"/> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button> <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button> </el-form-item> </el-form> <!-- 操作工具栏 --> <el-row :gutter="10" class="mb8"> <!-- <el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['pro:cus-user:create']">新增</el-button> </el-col> <el-col :span="1.5"> <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading" v-hasPermi="['pro:cus-user:export']">导出</el-button> </el-col> --> <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> </el-row> <!-- 列表 --> <el-table v-loading="loading" :data="list" border> <el-table-column label="用户ID" align="center" prop="userId" /> <el-table-column label="公司名称" align="center" prop="companyName" /> <el-table-column label="联系人" align="center" prop="contectName" /> <el-table-column label="联系电话" align="center" prop="mobile" /> <el-table-column label="联系地址" align="center" prop="address" /> <el-table-column label="注册时间" align="center" prop="createTime" /> <el-table-column label="状态" align="center" prop="status" > <template slot-scope="scope"> <dict-tag :type="DICT_TYPE.USER_STATUS" :value="scope.row.status"/> </template> </el-table-column> <el-table-column label="操作" align="center" class-name="small-padding fixed-width"> <template slot-scope="scope"> <el-button size="mini" type="text" @click="handleUpdateUserPassword(scope.row)" >重置密码</el-button> <el-button size="mini" type="text" @click="handleUpdateUserStatus(scope.row)" >{{scope.row.status === 0?"禁用":"启用"}}</el-button> <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['pro:cus-user:update']">修改</el-button> <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['pro:cus-user:delete']">删除</el-button> --> </template> </el-table-column> </el-table> <!-- 分页组件 --> <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getList"/> <!-- 对话框(添加 / 修改) --> <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="80px"> <el-form-item label="联系地址" prop="address"> <el-input v-model="form.address" placeholder="请输入联系地址" /> </el-form-item> <el-form-item label="公司名称" prop="companyName"> <el-input v-model="form.companyName" placeholder="请输入公司名称" /> </el-form-item> <el-form-item label="联系人" prop="contectName"> <el-input v-model="form.contectName" placeholder="请输入联系人" /> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="submitForm">确 定</el-button> <el-button @click="cancel">取 消</el-button> </div> </el-dialog> </div> </template> <script> import { createCusUser, updateCusUser, deleteCusUser, getCusUser, getCusUserPage, exportCusUserExcel,updateUserStatus,updateUserPassword } from "@/api/pro/cusUser"; import {DICT_TYPE, getDictDatas} from "@/utils/dict"; export default { name: "CusUser", components: { }, data() { return { // 遮罩层 loading: true, // 导出遮罩层 exportLoading: false, // 显示搜索条件 showSearch: true, // 总条数 total: 0, // 客户公司信息列表 list: [], // 弹出层标题 title: "", // 是否显示弹出层 open: false, // 查询参数 queryParams: { pageNo: 1, pageSize: 10, address: null, companyName: null, contectName: null, }, // 表单参数 form: {}, // 表单校验 rules: { address: [{ required: true, message: "联系地址不能为空", trigger: "blur" }], companyName: [{ required: true, message: "公司名称不能为空", trigger: "blur" }], contectName: [{ required: true, message: "联系人不能为空", trigger: "blur" }], }, userStatusDict: getDictDatas(DICT_TYPE.USER_STATUS), }; }, created() { this.getList(); }, methods: { /** 查询列表 */ getList() { this.loading = true; // 执行查询 getCusUserPage(this.queryParams).then(response => { this.list = response.data.list; this.total = response.data.total; this.loading = false; }); }, /** 取消按钮 */ cancel() { this.open = false; this.reset(); }, /** 表单重置 */ reset() { this.form = { status: undefined, companyName: undefined, }; this.resetForm("form"); }, // 重置密码 handleUpdateUserPassword(row){ var payload = { id:row.userId, password:"123456" } this.$modal.confirm('确认要重置' + '"' + row.contectName + '"用户密码吗?').then(function() { return updateUserPassword(payload); }).then(() => { // this.getList() this.$modal.msgSuccess("重置成功"); }).catch(function() { // row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE // : CommonStatusEnum.ENABLE; }); }, /** 禁用/启用 用户登录前端页面 */ handleUpdateUserStatus(row) { console.log("updateUserStatus",row) var label = row.status=== 0?"禁用":"启用" var payload = { id:row.userId, status:row.status===0?1:0 } this.$modal.confirm('确认要' + label + '"' + row.contectName + '"用户吗?').then(function() { return updateUserStatus(payload); }).then(() => { this.getList() this.$modal.msgSuccess(label + "成功"); }).catch(function() { // row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE // : CommonStatusEnum.ENABLE; }); }, /** 搜索按钮操作 */ handleQuery() { this.queryParams.pageNo = 1; this.getList(); }, /** 重置按钮操作 */ resetQuery() { this.resetForm("queryForm"); this.handleQuery(); }, /** 新增按钮操作 */ handleAdd() { this.reset(); this.open = true; this.title = "添加客户公司信息"; }, /** 修改按钮操作 */ handleUpdate(row) { this.reset(); const userId = row.userId; getCusUser(userId).then(response => { this.form = response.data; this.open = true; this.title = "修改客户公司信息"; }); }, /** 提交按钮 */ submitForm() { this.$refs["form"].validate(valid => { if (!valid) { return; } // 修改的提交 if (this.form.userId != null) { updateCusUser(this.form).then(response => { this.$modal.msgSuccess("修改成功"); this.open = false; this.getList(); }); return; } // 添加的提交 createCusUser(this.form).then(response => { this.$modal.msgSuccess("新增成功"); this.open = false; this.getList(); }); }); }, /** 删除按钮操作 */ handleDelete(row) { const userId = row.userId; this.$modal.confirm('是否确认删除客户公司信息编号为"' + userId + '"的数据项?').then(function() { return deleteCusUser(userId); }).then(() => { this.getList(); this.$modal.msgSuccess("删除成功"); }).catch(() => {}); }, /** 导出按钮操作 */ handleExport() { // 处理查询参数 let params = {...this.queryParams}; params.pageNo = undefined; params.pageSize = undefined; this.$modal.confirm('是否确认导出所有客户公司信息数据项?').then(() => { this.exportLoading = true; return exportCusUserExcel(params); }).then(response => { this.$download.excel(response, '客户公司信息.xls'); this.exportLoading = false; }).catch(() => {}); } } }; </script>
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: davidtor <davidtor@student.42barcelona. +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/10/05 12:15:11 by davidtor #+# #+# */ /* Updated: 2023/10/05 16:35:20 by davidtor ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strjoin(char const *s1, char const *s2) { unsigned long len_total; char *res; len_total = ft_strlen(s1) + ft_strlen(s2); if (!s1 && !s2) return (0); res = (char *)malloc((len_total + 1) * sizeof(char)); if (!res) return (0); if (!s1 || !s2) { if (!s1) ft_strlcpy(res, s2, len_total + 1); else if (!s2) ft_strlcpy(res, s1, len_total + 1); } else { ft_strlcpy(res, s1, len_total + 1); ft_strlcat(res, s2, len_total + 1); } return (res); }
// // MixedEventsStepsStrategyView.swift // TealiumSKAdNetwork_Example // // Created by Enrico Zannini on 09/01/23. // Copyright © 2023 CocoaPods. All rights reserved. // import SwiftUI struct MixedEventsStepsStrategyView: View { @State var events: [Int] = [0, 0, 0] @State var journeyStep = 0 var body: some View { List { Text("Events/Flags: \(events.reversed().description)") ForEach(events.indices, id: \.self) { index in if events[index] == 1 { Button { events[index] = 0 TealiumHelper.shared.track(title: "reset_event\(index)", data: [:]) } label: { Text("Reset Event/Flag \(index)") } } else { Button { events[index] = 1 TealiumHelper.shared.track(title: "event\(index)", data: [:]) } label: { Text("Set Event/Flag \(index)") } } } Text("Journey Step: \(journeyStep)") Button { if journeyStep < 7 { journeyStep += 1 TealiumHelper.shared.track(title: "journey_step", data: ["journey_step": journeyStep]) } } label: { Text("Next journey step [\(journeyStep+1)]") }.disabled(journeyStep >= 7) Section { Text("The ConversionValue will be determined by two different strategies. The Events and the Journey Steps.\nYou can specify any number of bits for the event and leave 6-N bit for the journey. \nIn this case we decided to use 3 and 3. So you can raise bits 3-4-5 like the Events Strategy, and have steps from 0 to 7 like the Journey Steps strategy.") } }.navigationTitle("Mixed Events/Steps Strategy") .onAppear { TealiumHelper.shared.tealium?.dataLayer.add(key: "strategy", value: "mixed_events_steps", expiry: .forever) } } }
// // ViewController.swift // Project21_localNotifs // // Created by may on 12/25/22. // import UIKit import UserNotifications class ViewController: UIViewController, UNUserNotificationCenterDelegate { var repeatIn24hrs = false var registered = false override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItems = [ UIBarButtonItem(title: "register", style: .plain, target: self, action: #selector(registerLocal)), UIBarButtonItem(title: "schedule", style: .plain, target: self, action: #selector(scheduleLocal)) ] } @objc func registerLocal(){ let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .badge, .sound]){ (granted, error) in if granted { print("Yay!") } else { print("D'oh") } } if registered{ showAlert(title: "Registered", message: "The app has already been given permission to notify alerts.") } registered = true } @objc func scheduleLocal(){ var trigger: UNNotificationTrigger let center = UNUserNotificationCenter.current() registerCategories() //setup our notif categories (groups) //remove all notifs center.removeAllPendingNotificationRequests() let content = UNMutableNotificationContent() content.title = "Late Wake Up Call" content.body = "body asdkdnaskndaskndasklnd lfahdsjahda" content.categoryIdentifier = "alarm" //category set created by UNNotificationCategory(identifier: "alarm", ...) //To attach custom data to the notification, e.g. an internal ID, use the userInfo dictionary property. // to be handled at func didReceive response content.userInfo = ["customData": "ID:911"] content.sound = UNNotificationSound.default if repeatIn24hrs { // when to notif in interval of secs trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: false) }else{ // get the current date and time let currentDateTime = Date() // get the user's calendar let userCalendar = Calendar.current // choose which date and time components are needed let requestedComponents: Set<Calendar.Component> = [ .hour, .minute, ] // get the components let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime) var triggerDate = DateComponents() triggerDate.hour = dateTimeComponents.hour triggerDate.minute = dateTimeComponents.minute! + 1 // when to notif daily trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true) print(triggerDate) } // trigger notif let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) } func registerCategories() { let center = UNUserNotificationCenter.current() center.delegate = self // create categories for center (UNUserNotificationCenter) // 1st setup the action for the category //show is a btn in notif screen let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground) let showLater = UNNotificationAction(identifier: "later", title: "Remind me later", options: .destructive) let categories = UNNotificationCategory(identifier: "alarm", actions: [show, showLater], intentIdentifiers: []) // let category2 = UNNotificationCategory(identifier: "anotherCategory", actions: [doThisAction, thenThisAction], intentIdentifiers: []) center.setNotificationCategories([categories]) } //triggered on our view controller because we’re the center’s delegate, so it’s down to us to decide how to handle the notification. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // pull out the buried userInfo dictionary let userInfo = response.notification.request.content.userInfo if let customData = userInfo["customData"] as? String { print("Custom data received: \(customData)") switch response.actionIdentifier { // the user swiped to unlock case UNNotificationDefaultActionIdentifier: print("Default identifier") // the user tapped our "show more info…" button case "show": print("Show more information…") showAlert(title: "Information", message: "something about the notification......") // alarm later case "later": print("show later is tapped") showAlert(title: "Notify later", message: "This notification will be silenced and will be shown after 24 hours.") repeatIn24hrs = true scheduleLocal() default: break } } // you must call the completion handler when you're done completionHandler() } func showAlert(title: String, message: String){ let ac = UIAlertController(title: title, message: message, preferredStyle: .alert) // actions let done = UIAlertAction(title: "Ok", style: .default) ac.addAction(done) present(ac,animated: true) } }
// Copyright 2024 International Digital Economy Academy // // 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. /// Sorts the array /// /// It's an stable sort(it will not reorder equal elements). The time complexity is *O*(*n* \* log(*n*)) in the worst case. /// /// # Example /// /// ``` /// let arr = [5, 4, 3, 2, 1] /// arr.stable_sort() /// debug(arr) //output: [1, 2, 3, 4, 5] /// ``` pub fn stable_sort[T : Compare](self : FixedArray[T]) -> Unit { timsort({ array: self, start: 0, end: self.length() }) } priv struct TimSortRun { len : Int start : Int } /// The algorithm identifies strictly descending and non-descending subsequences, which are called /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are /// satisfied: /// /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len` /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len` /// /// The invariants ensure that the total running time is *O*(*n* \* log(*n*)) worst-case. fn timsort[T : Compare](arr : FixedArraySlice[T]) -> Unit { // Slices of up to this length get sorted using insertion sort. let max_insertion = 20 // Short arrays get sorted in-place via insertion sort to avoid allocations. let len = arr.length() if len <= max_insertion { FixedArraySlice::insertion_sort(arr) } let mut end = 0 let mut start = 0 let runs : Array[TimSortRun] = [] while end < len { let (streak_end, was_reversed) = find_streak(arr.slice(start, arr.end)) end += streak_end if was_reversed { arr.slice(start, end).reverse() } // Insert some more elements into the run if it's too short. Insertion sort is faster than // merge sort on short sequences, so this significantly improves performance. end = provide_sorted_batch(arr, start, end) runs.push({ start, len: end - start }) start = end while true { match collapse(runs, len) { Some(r) => { let left = runs[r] let right = runs[r + 1] merge(arr.slice(left.start, right.start + right.len), left.len) runs[r + 1] = { start: left.start, len: left.len + right.len } runs.remove(r) |> ignore } None => break } } } } fn FixedArraySlice::insertion_sort[T : Compare]( arr : FixedArraySlice[T] ) -> Unit { for i = 1, len = arr.length(); i < len; i = i + 1 { for j = i; j > 0 && arr[j] < arr[j - 1]; j = j - 1 { arr.swap(j, j - 1) } } } /// Merges non-decreasing runs `arr[..mid]` and `arr[mid..]`. Copy `arr[mid..]` to buf and merge /// `buf` and `arr[..mid]` to `arr[..]` fn merge[T : Compare](arr : FixedArraySlice[T], mid : Int) -> Unit { let buf_len = arr.length() - mid let buf : FixedArray[T] = FixedArray::make(buf_len, arr[mid]) for i = 0; i < buf.length(); i = i + 1 { buf[i] = arr[mid + i] } let buf = { array: buf, start: 0, end: buf_len } let buf_remaining = for p1 = mid - 1, p2 = buf_len - 1, p = mid + buf_len - 1; p1 >= 0 && p2 >= 0; { if arr[p1] > buf[p2] { arr[p] = arr[p1] continue p1 - 1, p2, p - 1 } else { arr[p] = buf[p2] continue p1, p2 - 1, p - 1 } } else { p2 } for i = buf_remaining; i >= 0; i = i - 1 { arr[i] = buf[i] } } /// Finds a streak of presorted elements starting at the beginning of the slice. Returns the first /// value that is not part of said streak, and a bool denoting whether the streak was reversed. /// Streaks can be increasing or decreasing. fn find_streak[T : Compare](arr : FixedArraySlice[T]) -> (Int, Bool) { let len = arr.length() if len < 2 { return (len, false) } let assume_reverse = arr[1] < arr[0] if assume_reverse { for end = 2 { if end < len && arr[end] < arr[end - 1] { continue end + 1 } else { break (end, true) } } } else { for end = 2 { if end < len && arr[end] >= arr[end - 1] { continue end + 1 } else { break (end, false) } } } } fn provide_sorted_batch[T : Compare]( arr : FixedArraySlice[T], start : Int, end : Int ) -> Int { let len = arr.length() // This value is a balance between least comparisons and best performance, as // influenced by for example cache locality. let min_insertion_run = 10 // Insert some more elements into the run if it's too short. Insertion sort is faster than // merge sort on short sequences, so this significantly improves performance. let start_end_diff = end - start if start_end_diff < min_insertion_run && end < len { // v[start_found..end] are elements that are already sorted in the input. We want to extend // the sorted region to the left, so we push up MIN_INSERTION_RUN - 1 to the right. Which is // more efficient that trying to push those already sorted elements to the left. let sort_end = minimum(len, start + min_insertion_run) FixedArraySlice::insertion_sort(arr.slice(start, sort_end)) sort_end } else { end } } // TimSort is infamous for its buggy implementations, as described here: // http://envisage-project.eu/timsort-specification-and-verification/ // // This function correctly checks invariants for the top four runs. Additionally, if the top // run starts at index 0, it will always demand a merge operation until the stack is fully // collapsed, in order to complete the sort. fn collapse(runs : Array[TimSortRun], stop : Int) -> Int? { let n : Int = runs.length() if n >= 2 && (runs[n - 1].start + runs[n - 1].len == stop || runs[n - 2].len <= runs[n - 1].len || n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len || n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len) { if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) } } else { None } } /// Sorts the array /// /// It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case. /// /// # Example /// /// ``` /// let arr = [5, 4, 3, 2, 1] /// arr.sort() /// debug(arr) //output: [1, 2, 3, 4, 5] /// ``` pub fn sort[T : Compare](self : FixedArray[T]) -> Unit { fixed_quick_sort( { array: self, start: 0, end: self.length() }, None, fixed_get_limit(self.length()), ) } fn fixed_quick_sort[T : Compare]( arr : FixedArraySlice[T], pred : T?, limit : Int ) -> Unit { let mut limit = limit let mut arr = arr let mut pred = pred let mut was_partitioned = true let mut balanced = true let bubble_sort_len = 16 while true { let len = arr.length() if len <= bubble_sort_len { if len >= 2 { fixed_bubble_sort(arr) } return } // Too many imbalanced partitions may lead to O(n^2) performance in quick sort. // If the limit is reached, use heap sort to ensure O(n log n) performance. if limit == 0 { fixed_heap_sort(arr) return } let (pivot_index, likely_sorted) = fixed_choose_pivot(arr) // Try bubble sort if the array is likely already sorted. if was_partitioned && balanced && likely_sorted { if fixed_try_bubble_sort(arr) { return } } let (pivot, partitioned) = fixed_partition(arr, pivot_index) was_partitioned = partitioned balanced = minimum(pivot, len - pivot) >= len / 8 if not(balanced) { limit -= 1 } match pred { Some(pred) => // pred is less than all elements in arr // If pivot euqals to pred, then we can skip all elements that are equal to pred. if pred == arr[pivot] { let mut i = pivot while i < len && pred == arr[i] { i = i + 1 } arr = arr.slice(i, len) continue } _ => () } let left = arr.slice(0, pivot) let right = arr.slice(pivot + 1, len) // Reduce the stack depth by only call fixed_quick_sort on the smaller fixed_partition. if left.length() < right.length() { fixed_quick_sort(left, pred, limit) arr = right pred = Some(arr[pivot]) } else { fixed_quick_sort(right, Some(arr[pivot]), limit) arr = left } } } fn fixed_get_limit(len : Int) -> Int { let mut len = len let mut limit = 0 while len > 0 { len = len / 2 limit += 1 } limit } /// Try to sort the array with bubble sort. /// /// It will only tolerate at most 8 unsorted elements. The time complexity is O(n). /// /// Returns whether the array is sorted. fn fixed_try_bubble_sort[T : Compare]( arr : FixedArraySlice[T], ~max_tries : Int = 8 ) -> Bool { let mut tries = 0 for i = 1; i < arr.length(); i = i + 1 { let mut sorted = true for j = i; j > 0 && arr[j - 1] > arr[j]; j = j - 1 { sorted = false arr.swap(j, j - 1) } if not(sorted) { tries += 1 if tries > max_tries { return false } } } true } /// Try to sort the array with bubble sort. /// /// It will only tolerate at most 8 unsorted elements. The time complexity is O(n). /// /// Returns whether the array is sorted. fn fixed_bubble_sort[T : Compare](arr : FixedArraySlice[T]) -> Unit { for i = 1; i < arr.length(); i = i + 1 { for j = i; j > 0 && arr[j - 1] > arr[j]; j = j - 1 { arr.swap(j, j - 1) } } } test "fixed_try_bubble_sort" { let arr : FixedArray[_] = [8, 7, 6, 5, 4, 3, 2, 1] let sorted = fixed_try_bubble_sort({ array: arr, start: 0, end: 8 }) @assertion.assert_eq(sorted, true)? @assertion.assert_eq(arr, [1, 2, 3, 4, 5, 6, 7, 8])? } fn fixed_partition[T : Compare]( arr : FixedArraySlice[T], pivot_index : Int ) -> (Int, Bool) { arr.swap(pivot_index, arr.length() - 1) let pivot = arr[arr.length() - 1] let mut i = 0 let mut partitioned = true for j = 0; j < arr.length() - 1; j = j + 1 { if arr[j] < pivot { if i != j { arr.swap(i, j) partitioned = false } i = i + 1 } } arr.swap(i, arr.length() - 1) (i, partitioned) } /// Choose a pivot index for quick sort. /// /// It avoids worst case performance by choosing a pivot that is likely to be close to the median. /// /// Returns the pivot index and whether the array is likely sorted. fn fixed_choose_pivot[T : Compare](arr : FixedArraySlice[T]) -> (Int, Bool) { let len = arr.length() let use_median_of_medians = 50 let max_swaps = 4 * 3 let mut swaps = 0 let b = len / 4 * 2 if len >= 8 { let a = len / 4 * 1 let c = len / 4 * 3 fn sort_2(a : Int, b : Int) { if arr[a] > arr[b] { arr.swap(a, b) swaps += 1 } } fn sort_3(a : Int, b : Int, c : Int) { sort_2(a, b) sort_2(b, c) sort_2(a, b) } if len > use_median_of_medians { sort_3(a - 1, a, a + 1) sort_3(b - 1, b, b + 1) sort_3(c - 1, c, c + 1) } sort_3(a, b, c) } if swaps == max_swaps { arr.reverse() (len - b - 1, true) } else { (b, swaps == 0) } } fn fixed_heap_sort[T : Compare](arr : FixedArraySlice[T]) -> Unit { let len = arr.length() for i = len / 2 - 1; i >= 0; i = i - 1 { fixed_sift_down(arr, i) } for i = len - 1; i > 0; i = i - 1 { arr.swap(0, i) fixed_sift_down(arr.slice(0, i), 0) } } fn fixed_sift_down[T : Compare](arr : FixedArraySlice[T], index : Int) -> Unit { let mut index = index let len = arr.length() let mut child = index * 2 + 1 while child < len { if child + 1 < len && arr[child] < arr[child + 1] { child = child + 1 } if arr[index] >= arr[child] { return } arr.swap(index, child) index = child child = index * 2 + 1 } } fn fixed_test_sort(f : (FixedArray[Int]) -> Unit) -> Result[Unit, String] { let arr : FixedArray[_] = [5, 4, 3, 2, 1] f(arr) @assertion.assert_eq(arr, [1, 2, 3, 4, 5])? let arr : FixedArray[_] = [5, 5, 5, 5, 1] f(arr) @assertion.assert_eq(arr, [1, 5, 5, 5, 5])? let arr : FixedArray[_] = [1, 2, 3, 4, 5] f(arr) @assertion.assert_eq(arr, [1, 2, 3, 4, 5])? { let arr = FixedArray::make(1000, 0) for i = 0; i < 1000; i = i + 1 { arr[i] = 1000 - i - 1 } for i = 10; i < 1000; i = i + 10 { arr.swap(i, i - 1) } f(arr) let expected = FixedArray::make(1000, 0) for i = 0; i < 1000; i = i + 1 { expected[i] = i } @assertion.assert_eq(arr, expected)? } Ok(()) } test "fixed_heap_sort" { fixed_test_sort( fn(arr) { fixed_heap_sort({ array: arr, start: 0, end: arr.length() }) }, )? } test "fixed_bubble_sort" { fixed_test_sort( fn(arr) { fixed_bubble_sort({ array: arr, start: 0, end: arr.length() }) }, )? } test "sort" { fixed_test_sort(fn(arr) { arr.sort() })? } test "stable_sort" { let arr : FixedArray[_] = [5, 1, 3, 4, 2] arr.stable_sort() @assertion.assert_eq(arr, [1, 2, 3, 4, 5])? let arr = FixedArray::make(1000, 0) for i = 0; i < 1000; i = i + 1 { arr[i] = 1000 - i - 1 } for i = 10; i < 1000; i = i + 10 { arr.swap(i, i - 1) } arr.stable_sort() let expected = FixedArray::make(1000, 0) for i = 0; i < 1000; i = i + 1 { expected[i] = i } @assertion.assert_eq(arr, expected)? } pub fn FixedArray::is_sorted[T : Compare](arr : FixedArray[T]) -> Bool { for i = 1; i < arr.length(); i = i + 1 { if arr[i] < arr[i - 1] { break false } } else { true } } test "stable_sort_complex" { let run_lens = [86, 64, 21, 20, 22] let total_len = run_lens.fold_left(init=0, fn { acc, x => acc + x }) let arr = FixedArray::make(total_len, 0) let mut index = 0 for i = 0, len = run_lens.length(); i < len; i = i + 1 { for j = 0; j < run_lens[i]; j = j + 1 { arr[index] = j index += 1 } } @assertion.assert_false(is_sorted(arr))? arr.stable_sort() @assertion.assert_true(is_sorted(arr))? }
using BlogAspNet.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace BlogAspNet.Data.Mappings; public class UserMap :IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { //Tabela builder.ToTable("User"); //Chave Primária builder.HasKey(x => x.Id); //Identity builder.Property(x => x.Id) .ValueGeneratedOnAdd() .UseIdentityColumn(); //Primary key Identity(1,1) //Outras propriedades builder.Property(x => x.Name) .IsRequired() //Gera um NOT NULL .HasColumnName("Name") .HasColumnType("NVARCHAR") .HasMaxLength(80); builder.Property(x => x.Email) .IsRequired() //Gera um NOT NULL .HasColumnName("Email") .HasColumnType("VARCHAR") .HasMaxLength(200); builder.Property(x => x.PasswordHash) .IsRequired() //Gera um NOT NULL .HasColumnName("PasswordHash") .HasColumnType("VARCHAR") .HasMaxLength(255); builder.Property(x => x.Bio) .IsRequired(false) //Gera um NOT NULL .HasColumnName("Bio") .HasColumnType("TEXT"); builder.Property(x => x.Image) .IsRequired(false) //Gera um NOT NULL .HasColumnName("Image") .HasColumnType("VARCHAR") .HasMaxLength(2000); builder.Property(x => x.Slug) .IsRequired() //Gera um NOT NULL .HasColumnName("Slug") .HasColumnType("VARCHAR") .HasMaxLength(80); //Índices builder.HasIndex(x => x.Slug, "IX_User_Slug") .IsUnique(); // Relacionamento muitos para muitos builder.HasMany(x => x.Roles) .WithMany(x => x.Users) .UsingEntity<Dictionary<string,object>>( "UserRole", role => role.HasOne<Role>() .WithMany() .HasForeignKey("RoleId") .HasConstraintName("FK_UserRole_RoleId") .OnDelete(DeleteBehavior.Cascade), user => user.HasOne<User>() .WithMany() .HasForeignKey("UserId") .HasConstraintName("FK_UserRole_UserId") .OnDelete(DeleteBehavior.Cascade)); } }
from .models import * from django.forms import ModelForm, TextInput, Select, ChoiceField class SensorForm(ModelForm): class Meta: model = Sensor fields = ['position', 'description', 'cat', 'units'] widgets = { "position": TextInput(attrs={ 'class': 'form-control mt-2', 'placeholder': 'Позиционный номер', 'aria-describedby': 'position' }), "description": TextInput(attrs={ 'class': 'form-control mt-2', 'placeholder': 'Описание', 'aria-describedby': 'description' }), "cat": Select(attrs={ 'class': 'form-select form-control mt-2', 'placeholder': 'Описание', 'aria-describedby': 'description' }), "units": Select(attrs={ 'class': 'form-select form-control mt-2', 'placeholder': 'Описание', 'aria-describedby': 'description' }) } class EngUnitsForm(ModelForm): class Meta: model = EngUnits fields = ['name'] widgets = { "name": TextInput(attrs={ 'class': 'form-control mt-2', 'placeholder': 'Единицы измерения', 'aria-describedby': 'position' }) } class CategoryForm(ModelForm): class Meta: model = Category fields = ['name'] widgets = { "name": TextInput(attrs={ 'class': 'form-control mt-2', 'placeholder': 'Категория', 'aria-describedby': 'position' }) }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Worksheet4</title> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body onload="showPage()"> <div id="bodyLoad"> <img src="../5314_2.jpg" /> </div> <img src="../5314.jpg" /> <center style="display:none;" id="content"> <h1> <a href="../index.html" style="font-size:36px;">HOME</a> </h1> <div> <hr> <br> <h3> <a href="worksheet4_1.html">Worksheet 4 - part 1</a><br> <a href="worksheet4_2.html">Worksheet 4 - part 2</a><br> <a href="worksheet4_3.html">Worksheet 4 - part 3</a><br> <a href="worksheet4_4.html">Worksheet 4 - part 4</a><br> <a href="worksheet4_5.html" class="focus">Worksheet 4 - part 5</a><br> <a href="worksheet4_6.html">Worksheet 4 - part 6</a><br> </h3> <br> <hr> </div> <br> <div style="background-color: rgba(255, 255, 255, 0.5); padding: 20px; width: 50%; margin: 0 auto;"> <h3>Task : </h3> <p style="font-weight: normal; width: 80%; text-align: left;"> Use Phong shading by moving your implementation of the Phong reflection model to the fragment shader and varying positions and normals across triangles instead of colors. <br></p> </div> <div class="canvas-container"> <canvas id="gl-canvas" width="512" height="512" style="border:1px solid #000000;"> </canvas> <div class="container"> <div class="canvas-container"> <button id="increment" class="button"> Increase </button> <button id="decrement" class="button"> Decrease </button> <button id="changeorbitButton" class="button"> Stop Rotation</button> </div> <table style="background-color:#7BA6C7;"> <tbody> <tr> <td> K<sub>a</sub> <input id="ka" type="range" min="0" max="1" value="0.7" step="0.01"/> </td> </tr> <tr> <td> K<sub>d</sub> <input id="kd" type="range" min="0" max="1" value="0.7" step="0.01"/> </td> </tr> <tr> <td> K<sub>s</sub> <input id="ks" type="range" min="0" max="1" value="0.1" step="0.01"/> </td> </tr> <tr> <td> L<sub>e</sub> <input id="Le" type="range" min="0" max="1" value="0.9" step="0.01"/> </td> </tr> <tr> <td> Shininess <input id="alpha" type="range" min="0" max="200" value="100" step="5"/> </td> </tr> </tbody> </table> </div> </div> <p> 02561 Computer Graphics - George Stamatopoulos s230251 </p> </center> <script type="text/javascript"> function showPage() { setTimeout(() => { document.getElementById("content").style.display = "block"; document.getElementById("bodyLoad").style.display = "none"; }, 500); init() }; </script> </body> <script type="text/javascript" src="../angelCommon/initShaders.js"></script> <script type="text/javascript" src="./worksheet4_5.js"></script> <script type="text/javascript" src="../angelCommon/webgl-utils.js"></script> <script type="text/javascript" src="../angelCommon/MV.js"></script> <script id="vertex-shader" type="x-shader/x-vertex"> attribute vec4 vPosition; uniform mat4 modelViewMatrix; uniform mat4 projectionViewMatrix; varying vec4 fPosition; varying mat4 fModel; void main() { gl_Position = projectionViewMatrix * modelViewMatrix * vPosition; fPosition = vPosition; fModel = modelViewMatrix; } </script> <script id="fragment-shader" type="x-shader/x-fragment"> precision mediump float; varying mat4 fModel; vec4 vNormal; uniform vec4 lightPosition; uniform vec4 ka; uniform vec4 kd; uniform vec4 ks; uniform float shininess; uniform vec4 Le; varying vec4 fPosition; void main() { vec4 pos = (fModel * fPosition); vec4 n = normalize(fModel*vec4(vNormal.xyz,0.0)); vec4 light = fModel * lightPosition; // ambient vec4 ambient = ka * Le; // diffuse vec4 diffuse = kd * Le * max(0.0, dot(n, normalize(-light))); // specular vec4 view = normalize(vec4(0.0, 0.0, 0.0, 1.0)-vec4(pos.xyz,1.0)); vec4 reflection = normalize(reflect(-light, n)); vec4 specular = vec4(0,0,0,1); if (max(0.0, dot(n, light)) > 0.0) { float alpha = max(0.0, dot(view, reflection)); specular = ks * Le * pow(alpha, shininess); } vec4 baseColor = fPosition * 0.5 + 0.5; gl_FragColor = baseColor * (ambient + diffuse + specular);; } </script> <script type="text/javascript"> var subdivision = 5; var gl; function init() { const canvas = document.getElementById("gl-canvas"); gl = WebGLUtils.setupWebGL(canvas); var ext = gl.getExtension('OES_element_index_uint'); if (!ext) { console.log('Warning: Unable to use an extension'); } setupViewport(gl,canvas); program = initShaders(gl, "vertex-shader", "fragment-shader"); gl.useProgram(program); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.enable(gl.DEPTH_TEST); setupVertexBufferCube(gl,program,subdivision); var incrementBtn = document.getElementById("increment"); var decrementBtn = document.getElementById("decrement"); incrementBtn.onclick = function(){ if(subdivision < 6) subdivision++; setupVertexBufferCube(gl,program,subdivision); }; decrementBtn.onclick = function(){ if(subdivision > 0) subdivision--; setupVertexBufferCube(gl,program,subdivision); }; render(); } </script> </html>
import React, { useEffect, useState } from 'react'; import './UserPage.css'; import LogOutButton from '../LogOutButton/LogOutButton'; import { useDispatch, useSelector } from 'react-redux'; import axios from 'axios'; import { GoogleMap, useLoadScript, Marker, InfoWindow } from '@react-google-maps/api'; import { formatRelative } from 'date-fns'; import mapStyles from './mapStyles'; const libraries = ['places']; function UserPage() { const dispatch = useDispatch(); const user = useSelector((store) => store.user); const addresses = useSelector((store) => store.address); const { isLoaded, loadError } = useLoadScript({ googleMapsApiKey: process.env.REACT_APP_GOOGLE_API_KEY, libraries, }); useEffect(() => { dispatch({ type: 'FETCH_ADDRESS' }); }, [dispatch]); const [selectedMarker, setSelectedMarker] = useState(null); const [markers, setMarkers] = useState([]); const [center, setCenter] = useState({ lat: 40.748817, lng: -73.985428 }); const [openPopup, setOpenPopup] = useState(false); const [selectedItems, setSelectedItems] = useState([]); const [routeData, setRouteData] = useState(null); // State variable to store route data useEffect(() => { if (isLoaded && addresses.length > 0) { setMarkers(addresses); const firstMarkerWithAddress = addresses.find((marker) => marker.useraddress); if (firstMarkerWithAddress) { setCenter({ lat: Number(firstMarkerWithAddress.lat), lng: Number(firstMarkerWithAddress.lng) }); } } }, [isLoaded, addresses]); const mapContainerStyle = { width: '100%', height: '100%', }; const options = { styles: mapStyles, disableDefaultUI: true, zoomControl: true, }; if (loadError) return 'Error loading maps'; if (!isLoaded) return 'Loading Maps'; const generateAndSendRoute = () => { const selectedAddresses = selectedItems.map((item) => `${item.street}, ${item.city}`); const startAddress = addresses.find((item) => item.useraddress !== null); const startAddressString = startAddress ? `${startAddress.street}, ${startAddress.city}` : ''; console.log(selectedAddresses, startAddressString, 'req.body sending') }; const removeFromArray = (id) => { const updatedItems = selectedItems.filter((item) => item.id !== id); setSelectedItems(updatedItems); if (selectedMarker && selectedMarker.id === id) { setSelectedMarker(null); } }; return ( <div className="container"> <h1>Active Sales</h1> <div className="MapContainer"> <GoogleMap mapContainerStyle={mapContainerStyle} zoom={15} center={center} options={options} > {markers.map((marker) => { const currentDate = new Date(); const fromDate = new Date(marker.fromdate); const toDate = new Date(marker.todate); const isWithinDateRange = currentDate >= fromDate && currentDate <= toDate; const isUserAddressNotNull = marker.useraddress !== null; if (isWithinDateRange || isUserAddressNotNull) { return ( <Marker key={marker.id} position={{ lat: marker.lat, lng: marker.lng }} onMouseOver={() => { setSelectedMarker(marker); setOpenPopup(true); }} onClick={() => { if (!selectedItems.some((item) => item.id === marker.id)) { const updatedItems = [...selectedItems, marker]; setSelectedItems(updatedItems); } }} icon={{ url: marker.lat === center.lat ? '/images/house.png' : '/images/ls.png', scaledSize: new window.google.maps.Size(60, 60), origin: new window.google.maps.Point(0, 0), anchor: new window.google.maps.Point(18, 18), }} options={{ label: selectedItems.some((item) => item.id === marker.id) ? { text: 'Selected', color: 'black', fontWeight: 'bold', fontSize: '12px', background: 'rgba(0, 0, 255, 0.3)', borderRadius: '50%', padding: '5px', } : null, }} /> ); } })} {selectedMarker && openPopup && ( <InfoWindow position={{ lat: selectedMarker.lat, lng: selectedMarker.lng }} onCloseClick={() => setOpenPopup(false)} > <div> <h2>{selectedMarker.street}, {selectedMarker.city}</h2> <p>Sales Dates: {selectedMarker.fromdate.slice(0,10)} - {selectedMarker.todate.slice(0,10)}</p> </div> </InfoWindow> )} </GoogleMap> </div> <div className='arrayof'> {selectedItems.map((item) => ( <div key={item.id}> <span className='listof'>{` ${item.street}, ${item.city}, ${item.state}`} </span> <button onClick={() => removeFromArray(item.id)}>Remove</button> </div> ))} </div> <button onClick={generateAndSendRoute}>Generate Directions</button> <div> <h2>Generated Routes:</h2> <div>Coming Soon</div> </div> </div> ); } UserPage.libraries = libraries; export default UserPage;
export const revalidate = 0; // https://tailwindcomponents.com/component/hoverable-table import { getPaginatedOrders, getPaginatedProductsWithImages } from "@/actions"; import { Pagination, ProductImage, Title } from "@/components"; import DeleteProduct from "@/components/product/delete-product"; import { currencyFormat } from "@/utils"; import Image from "next/image"; import Link from "next/link"; import { redirect } from "next/navigation"; import { IoCardOutline } from "react-icons/io5"; interface Props { searchParams: { page?: string; }; } export default async function OrdersPage({ searchParams }: Props) { const page = searchParams.page ? parseInt(searchParams.page) : 1; const { products, currentPage, totalPages } = await getPaginatedProductsWithImages({ page }); return ( <> <Title title="Agregar o Editar Producto" /> <div className="flex justify-end mb-5"> <Link href="/admin/product/new" className="btn-primary"> Nuevo producto </Link> </div> <div className="mb-10"> <table className="min-w-full"> <thead className="bg-gray-200 border-b"> <tr> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Imagen </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Titulo </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Precio </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Género </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Inventario </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Tallas </th> <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left" > Eliminar </th> </tr> </thead> <tbody> {products.map((product) => ( <tr key={product.id} className="bg-white border-b transition duration-300 ease-in-out hover:bg-gray-100" > <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> <Link href={`/product/${product.slug}`}> <Image src={product.images[0] } width={100} height={100} style={{ width: "100px", height: "100px", }} alt={product.title} className="mr-5 rounded" /> </Link> </td> <td className="text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap"> <Link href={`/admin/product/${product.slug}`} className="hover:underline" > {product.title} </Link> </td> <td className="text-sm font-bold text-gray-900 px-6 py-4 whitespace-nowrap"> {currencyFormat(product.price)} </td> <td className="text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap"> {product.gender} </td> <td className="text-sm text-gray-900 font-bold px-6 py-4 whitespace-nowrap"> {product.inStock} </td> <td className="text-sm text-gray-900 font-bold px-6 py-4 whitespace-nowrap"> {product.sizes.join(", ")} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> <DeleteProduct id={product.id}/> </td> </tr> ))} </tbody> </table> <Pagination totalPages={totalPages} /> </div> </> ); }
@testset "Initialization" begin time_series = CSV.read(joinpath(@__DIR__, "data/timeseries_normal_rws_d1.csv"), DataFrame) y = time_series[:,1] T = length(y) X = rand(T, 2).+10 X_missing = missing stochastic = false @info("Test with Random Walk and Slope without AR and without explanatory") order = [nothing] max_order = 0 has_level = true has_slope = true has_seasonality = true has_ar1_level = false seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rws"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @info("Test with Random Walk with AR and without explanatory") order = [1] max_order = 2 has_level = true has_slope = false has_ar1_level = false has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rw"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .!= zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @info("Test with just Seasonality without explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = false has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @info("Test with Random Walk without seasonality and without explanatory") order = [nothing] max_order = 0 has_level = true has_slope = false has_ar1_level = false has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rw"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["seasonality"]["values"] .== zeros(T))) @info("Test with Random Walk Slope without seasonality and without explanatory") order = [nothing] max_order = 0 has_level = true has_slope = true has_ar1_level = false has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rws"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["seasonality"]["values"] .== zeros(T))) @info("Test with AR(1) with seasonality and without explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = true has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["ar1_level"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @info("Test with Random Walk and Slope without AR and with explanatory") stochastic = false order = [nothing] max_order = 0 has_level = true has_slope = true has_ar1_level = false has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rws"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with Random Walk with AR and with explanatory") order = [1] max_order = 2 has_level = true has_slope = false has_ar1_level = false has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rw"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .!= zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with just Seasonality with explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = false has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with Random Walk without seasonality and without explanatory") order = [nothing] max_order = 0 has_level = true has_slope = false has_ar1_level = false has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rw"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rws"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["seasonality"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with Random Walk Slope without seasonality and without explanatory") order = [nothing] max_order = 0 has_level = true has_slope = true has_ar1_level = false has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["rws"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["slope"]["values"], initial_values_state_space["slope"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["seasonality"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with AR(1) without seasonality and without explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = true has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X_missing, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["ar1_level"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @info("Test with AR(1) without seasonality and with explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = true has_seasonality = false seasonal_period = missing initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["ar1_level"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test with AR(1) with seasonality and with explanatory") order = [nothing] max_order = 0 has_level = false has_slope = false has_ar1_level = true has_seasonality = true seasonal_period = 12 initial_values_state_space = UnobservedComponentsGAS.define_state_space_model(y, X, (has_level || has_ar1_level), has_slope, has_seasonality, seasonal_period, stochastic) initial_values = UnobservedComponentsGAS.get_initial_values(y, X, has_level, has_ar1_level, has_slope, has_seasonality, seasonal_period, stochastic, order, max_order) @test(isapprox(initial_values["ar1_level"]["values"], initial_values_state_space["level"]; rtol = 1e-3)) @test(isapprox(initial_values["seasonality"]["values"],initial_values_state_space["seasonality"]; rtol = 1e-3)) @test(all(initial_values["seasonality"]["γ"] .== initial_values_state_space["γ"])) @test(all(initial_values["seasonality"]["γ_star"] .== initial_values_state_space["γ_star"])) @test(all(initial_values["ar"]["values"] .== zeros(T))) @test(all(initial_values["slope"]["values"] .== zeros(T))) @test(all(initial_values["rw"]["values"] .== zeros(T))) @test(all(initial_values["explanatories"] .== initial_values_state_space["explanatory"])) @info("Test create_output_initialization_from_fit") dist = UnobservedComponentsGAS.NormalDistribution() gas_model = UnobservedComponentsGAS.GASModel(dist, [true, false], 0.0, "random walk slope", "deterministic 12", 1) fitted_model = UnobservedComponentsGAS.fit(gas_model, y) output_initial_values = UnobservedComponentsGAS.create_output_initialization_from_fit(fitted_model, gas_model) @test(all(output_initial_values["rw"]["values"] .== 0)) @test(all(output_initial_values["seasonality"]["values"] .!= 0)) @test(all(output_initial_values["ar"]["values"] .!= 0)) @test(all(output_initial_values["slope"]["values"] .!= zeros(T))) @test(all(output_initial_values["rws"]["values"] .!= zeros(T))) dist = UnobservedComponentsGAS.NormalDistribution() gas_model = UnobservedComponentsGAS.GASModel(dist, [true, true], 0.0, ["random walk slope", "random walk"], ["deterministic 12", "deterministic 12"], [missing, missing]) fitted_model = UnobservedComponentsGAS.fit(gas_model, y) output_initial_values = UnobservedComponentsGAS.create_output_initialization_from_fit(fitted_model, gas_model) @test(all(output_initial_values["rw"]["values"][:,1] .== 0)) #@test(all(output_initial_values["rw"]["values"][:,2] .!= 0)) @test(all(output_initial_values["seasonality"]["values"] .!= 0)) @test(all(output_initial_values["ar"]["values"] .== 0)) @test(all(output_initial_values["slope"]["values"] .!= 0)) @test(all(output_initial_values["rws"]["values"] .!= 0)) end
import { Component, Input } from '@angular/core'; import { AuthService } from 'src/app/services/auth.service'; import { CartService } from 'src/app/services/cart.service'; import { IMG_API_PRE, IMG_API_SUF } from 'src/constants/constants'; import { ICardDet } from 'src/interfaces/ICardDet'; @Component({ selector: 'app-card', templateUrl: './card.component.html', styleUrls: ['./card.component.scss'] }) export class CardComponent { @Input() art!: ICardDet showSpinner: boolean = false; showFirst: Boolean = true; img_src_pre: string = IMG_API_PRE; img_src_suf: string = IMG_API_SUF; constructor(private cartServe: CartService, public auth: AuthService, private fav: CartService) { // initialising like/notLiked status if (!auth.isLogIn) this.showFirst = true; else{ try{ if (this.art != undefined){ if (fav.checkInFav(this.art.id)) this.showFirst = false; else this.showFirst = true; } } catch(e: any){ console.warn('Error found, Art Data Undefined', e) } } } /** * @description initialise Like/Favourite Status based on whether logged in, liked or not */ ngOnInit(){ if (!this.auth.isLogIn){ this.showFirst = false } this.showFirst = this.cartServe.checkInFav(this.art.id) } /** * * @param event Click event on the Like/Favourite Button * @description updates the Favourite array, for like/unlike, updating favourite status */ favToggle(event: MouseEvent){ if (!this.auth.isLogIn){ this.showFirst = false alert('User Not Logged In') } else { this.cartServe.toggleToFav(this.art.id); if (this.fav.checkInFav(this.art.id)) this.showFirst = true; else this.showFirst = false } } /** * @description when image is not available, activates the spinner from Angular Material */ toggleImgFailMode(){ this.showSpinner = true; } /** * * @param id Unique data ID for the artwork * @description for sharing the artwork on various social networks, etc. */ share(id: number){ if(navigator.share){ navigator.share({ title:"Checkout", text:"Check this art", url:`${window.location.origin}/view/${id}` }) } } }
import SystemConfiguration import UIKit @objc(DeviceDetailsModule) class DeviceDetailsModule: NSObject { @objc func getDeviceModel(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } let ipAddress = getIFAddresses() let macAddress = UIDevice().identifierForVendor?.uuidString ?? "" let deviceName = UIDevice.current.name let version = UIDevice.current.systemVersion let modelName = UIDevice.current.model let osName = UIDevice.current.systemName let localized = UIDevice.current.localizedModel print(mapToDevice(identifier: identifier)) resolve(["device":mapToDevice(identifier: identifier),"ip":ipAddress[0],"macAddress":macAddress,"deviceName":deviceName,"version":version,"modelName":modelName,"osName":osName,"localized":localized]) } @objc func getIFAddresses() -> [String] { var addresses = [String]() // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer<ifaddrs>? guard getifaddrs(&ifaddr) == 0 else { return [] } guard let firstAddr = ifaddr else { return [] } // For each interface ... for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let flags = Int32(ptr.pointee.ifa_flags) let addr = ptr.pointee.ifa_addr.pointee // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) { // Convert interface address to a human readable string: var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if (getnameinfo(ptr.pointee.ifa_addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0) { let address = String(cString: hostname) addresses.append(address) } } } } freeifaddrs(ifaddr) return addresses } @objc func mapToDevice(identifier: String) -> String { #if os(iOS) switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #endif } }
# Import libraries import pygame import os import random import neat # Setting up AI player and generation ai_player = True generation = 0 # Setting up screen dimensions SCREEN_WIDTH = 500 SCREEN_HEIGHT = 800 # Loading images for the game BARREL_IMAGE = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'pipe.png'))) FLOOR_IMAGE = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'base.png'))) BACKGROUND_IMAGE = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bg.png'))) IMAGES_BIRD = [ pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird1.png'))), pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird2.png'))), pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird3.png'))), ] # Initializing pygame font and setting up font for points pygame.font.init() POINTS_FONT = pygame.font.SysFont('arial', 50) # Class for Birds class Bird: IMGS = IMAGES_BIRD ROTATION_MAX = 25 SPEED_ROTATION = 20 TIME_ANIMATION = 5 # Initializing bird with position and image def __init__(self, x, y): self.x = x self.y = y self.angle = 0 self.speed = 0 self.hight = self.y self.time = 0 self.count_imagem = 0 self.imagem = self.IMGS[0] # Function for bird to jump def jump(self): self.speed = -10.5 self.time = 0 self.hight = self.y # Function for bird to move def move(self): self.time += 1 displacament = 1.5 * (self.time**2) + self.speed * self.time if displacament > 16: displacament = 16 elif displacament < 0: displacament -= 2 self.y += displacament if displacament < 0 or self.y < (self.hight + 50): if self.angle < self.ROTATION_MAX: self.angle = self.ROTATION_MAX else: if self.angle > -90: self.angle -= self.SPEED_ROTATION # Function to paint the bird on the screen def paint(self, screen): self.count_imagem += 1 if self.count_imagem < self.TIME_ANIMATION: self.imagem = self.IMGS[0] elif self.count_imagem < self.TIME_ANIMATION*2: self.imagem = self.IMGS[1] elif self.count_imagem < self.TIME_ANIMATION*3: self.imagem = self.IMGS[2] elif self.count_imagem < self.TIME_ANIMATION*4: self.imagem = self.IMGS[1] elif self.count_imagem < self.TIME_ANIMATION*4 + 1: self.imagem = self.IMGS[0] self.count_imagem = 0 if self.angle <= -80: self.imagem = self.IMGS[1] self.count_image = self.TIME_ANIMATION*2 image_rotation = pygame.transform.rotate(self.imagem, self.angle) pos_image_center = self.imagem.get_rect(topleft=(self.x, self.y)).center rectangle = image_rotation.get_rect(center=pos_image_center) screen.blit(image_rotation, rectangle.topleft) # Function to get mask of the bird image def get_mask(self): return pygame.mask.from_surface(self.imagem) # Class for Barrel class Barrel: distance = 200 speed = 5 # Initializing barrel with position and image def __init__(self, x): self.x = x self.hight = 0 self.pos_top = 0 self.pos_floor = 0 self.BARREL_TOP = pygame.transform.flip(BARREL_IMAGE, False, True) self.BARREL_FLOOR = BARREL_IMAGE self.happened = False self.def_hight() # Function to define height of the barrel def def_hight(self): self.hight = random.randrange(50, 450) self.pos_top = self.hight - self.BARREL_TOP.get_height() self.pos_floor = self.hight + self.distance # Function for move barrel def move(self): self.x -= self.speed ## Function to paint the barrel on the screen def paint(self, screen): screen.blit(self.BARREL_TOP, (self.x, self.pos_top)) screen.blit(self.BARREL_FLOOR, (self.x, self.pos_floor)) # Function to check collision with the bird def collide(self, bird): BIRD_IMAGE_mask = bird.get_mask() top_mask = pygame.mask.from_surface(self.BARREL_TOP) base_mask = pygame.mask.from_surface(self.BARREL_FLOOR) distance_top = (self.x - bird.x, self.pos_top - round(bird.y)) distance_floor = (self.x - bird.x, self.pos_floor - round(bird.y)) top_point = BIRD_IMAGE_mask.overlap(top_mask, distance_top) base_point = BIRD_IMAGE_mask.overlap(base_mask, distance_floor) if base_point or top_point: return True else: return False # Class for floor class Floor: SPEED = 5 WIDTH = FLOOR_IMAGE.get_width() IMAGEM = FLOOR_IMAGE # Initializing floor with position and image def __init__(self, y): self.y = y self.x1 = 0 self.x2 = self.WIDTH # Function for floor to move def move(self): self.x1 -= self.SPEED self.x2 -= self.SPEED if self.x1 + self.WIDTH < 0: self.x1 = self.x2 + self.WIDTH # WATCH if self.x2 + self.WIDTH < 0: self.x2 = self.x1 + self.WIDTH # Function to paint the floor on the screen def paint(self, screen): screen.blit(self.IMAGEM, (self.x1, self.y)) screen.blit(self.IMAGEM, (self.x2, self.y)) # Function to paint the screen def paint_screen(screen, birds, barrels, floor, points): screen.blit(BACKGROUND_IMAGE, (0, 0)) for bird in birds: bird.paint(screen) for barrel in barrels: barrel.paint(screen) text = POINTS_FONT.render(f'Points: {points}', 1, (255, 255, 255)) screen.blit(text, (SCREEN_WIDTH - 10 - text.get_width(), 10)) if ai_player: text = POINTS_FONT.render(f'Geração: {generation}', 1, (255, 255, 255)) screen.blit(text, (10, 10)) floor.paint(screen) pygame.display.update() def main(genomes, config): # Main function for the game global generation generation += 1 if ai_player: nets = [] list_genomes = [] birds = [] for _, genome in genomes: net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) genome.fitness = 0 list_genomes.append(genome) birds.append(Bird(230, 350)) else: birds = [Bird(230, 350)] floor = Floor(730) barrels = [Barrel(700)] screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) points = 0 watch = pygame.time.Clock() # Game loop runing = True while runing: watch.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: runing = False pygame.quit() quit() if not ai_player: if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: for bird in birds: bird.jump() index_barrel = 0 if len(birds) > 0: if len(barrels) > 1 and birds[0].x > (barrels[0].x + barrels[0].BARREL_TOP.get_width()): index_barrel = 1 else: runing = False break for i, bird in enumerate(birds): bird.move() list_genomes[i].fitness += 0.1 output = nets[i].activate((bird.y, abs(bird.y - barrels[index_barrel].hight), abs(bird.y - barrels[index_barrel].pos_floor))) # -1 e 1 --> If output > 0.5 then brid jump if output[0] > 0.5: bird.jump() floor.move() add_barrel = False remove_barrel = [] for barrel in barrels: for i, bird in enumerate(birds): if barrel.collide(bird): birds.pop(i) if ai_player: list_genomes[i].fitness -= 1 list_genomes.pop(i) nets.pop(i) if not barrel.happened and bird.x > barrel.x: barrel.happened = True add_barrel = True barrel.move() if barrel.x + barrel.BARREL_TOP.get_width() < 0: remove_barrel.append(barrel) if add_barrel: points += 1 barrels.append(Barrel(600)) for genome in list_genomes: genome.fitness += 5 for barrel in remove_barrel: barrels.remove(barrel) for i, bird in enumerate(birds): if (bird.y + bird.imagem.get_height()) > floor.y or bird.y < 0: birds.pop(i) if ai_player: list_genomes.pop(i) nets.pop(i) paint_screen(screen, birds, barrels, floor, points) def running(adress_config): config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, adress_config) population = neat.Population(config) population.add_reporter(neat.StdOutReporter(True)) population.add_reporter(neat.StatisticsReporter()) if ai_player: population.run(main, 50) else: main(None, None) if __name__ == '__main__': adress = os.path.dirname(__file__) adress_config = os.path.join(adress,'config.txt') running(adress_config)
import cloudImage from "./assets/cloud.png"; import gameBody from "./assets/game.svg"; import BetBox from "./components/BetBox"; import BroccoliIcon from "./assets/broccoli.svg"; import BreadIcon from "./assets/bread.svg"; import BurgerIcon from "./assets/burger.svg"; import LegIcon from "./assets/leg.svg"; import PizzaIcon from "./assets/pizza.svg"; import ChickenIcon from "./assets/chicken.svg"; import SandWichIcon from "./assets/sandwich.svg"; import SushiIcon from "./assets/sushi.svg"; import AmountBox from "./components/AmountBox"; import ResultBox from "./components/ResultBox"; import InstructionsModal from "./components/InstructionsModal"; import { useState } from "react"; import RevenueRankModal from "./components/RevenueRankModal"; import DiamondIcon from "./assets/diamond.svg"; function App() { const [showInstructionsModal, setShowInstructionsModal] = useState(false); const [showRevenueRankModal, setShowRevenueRankModal] = useState(false); const isHalfScreen = window.innerHeight <= 400; return ( <> <div className="bg-[#FBE170] w-full h-screen flex flex-col"> {/* Clouds */} <> <img className="h-[30px] absolute top-[20px] left-[120px]" src={cloudImage} alt="" /> <img className="h-[30px] absolute top-[50%] left-[20px]" src={cloudImage} alt="" /> </> <div className={`${isHalfScreen ? "pt-[10px]" : "pt-[50px]"}`}> {/* For Less height screen */} {/* Results */} {isHalfScreen && ( <div className="absolute left-[2%] top-[20%] flex flex-col items-center py-[2px] px-[2px] bg-[#7FC2F0] rounded-md border-2 border-black z-50"> <p className="text-black text-[11px] font-bold"> Results: </p> <div className="py-[5px] flex flex-col items-center gap-[4px]"> <ResultBox icon={BroccoliIcon} /> <ResultBox icon={BurgerIcon} /> <ResultBox icon={SushiIcon} /> <ResultBox icon={PizzaIcon} /> <ResultBox icon={BreadIcon} /> <ResultBox icon={SushiIcon} /> </div> </div> )} {isHalfScreen && ( <div className="flex flex-col items-center justify-between gap-[10px] absolute right-[2%] top-[19%] z-50"> <AmountBox short red point={100} /> <AmountBox short point={1000} /> <AmountBox short point={10000} /> <AmountBox short point={100000} /> </div> )} {/* Top Bar */} <div className="relative px-[20px] flex items-center justify-between z-10"> <div className="flex items-start gap-[5px]"> <div className="bg-[#58529A] w-[30px] h-[30px] rounded-sm"></div> <div className=""> <p className="text-[9px] font-semibold"> Today: Round <span>1113</span> </p> <p className="text-[9px] text-green-500 font-semibold"> 10ms </p> </div> </div> <div className="flex items-center gap-[10px]"> <div onClick={() => setShowInstructionsModal(true)} className="w-[32px] h-[32px] rounded-full bg-[#0B325B] border-[3px] relative border-[#2D8FD5] before:content-['Rules'] before:absolute before:bottom-[-10px] before:left-[-3px] before:text-[9px] before:px-[5px] before:text-white before:bg-[#006BBB] before:rounded-md" ></div> <div className="w-[32px] h-[32px] rounded-full bg-[#0B325B] border-[3px] relative border-[#2D8FD5] before:content-['Settings'] before:absolute before:bottom-[-10px] before:left-[-8px] before:text-[9px] before:px-[5px] before:text-white before:bg-[#006BBB] before:rounded-md"></div> </div> </div> {/* Main Game */} <div className={`relative w-max max-w-[95%] mx-auto scale-75 ${ isHalfScreen ? "scale-[55%] -mt-[45px]" : "scale-100 mt-[50px]" }`} > <img className="w-full max-h-[500px]" src={gameBody} alt="" /> {/* Bet Box */} <> <BetBox className="absolute top-[-70px] left-[38%]" icon={ChickenIcon} points={45} /> <BetBox className="absolute top-[-30px] left-[12%]" icon={BroccoliIcon} points={5} /> <BetBox className="absolute top-[58px] left-[3%]" icon={SushiIcon} points={5} /> <BetBox className="absolute top-[150px] left-[10%]" icon={PizzaIcon} points={5} /> <BetBox className="absolute top-[190px] left-[38%]" icon={SandWichIcon} points={5} /> <BetBox className="absolute top-[-30px] right-[12%]" icon={LegIcon} points={25} /> <BetBox className="absolute top-[58px] right-[3%]" icon={BreadIcon} points={15} /> <BetBox className="absolute top-[150px] right-[10%]" icon={BurgerIcon} points={10} /> </> {/* Amount Box */} <> {!isHalfScreen && ( <div className="flex items-center justify-between gap-[10px] absolute bottom-[5px] w-[85%] left-[8%]"> <AmountBox yellow point={100} /> <AmountBox point={1000} /> <AmountBox point={10000} /> <AmountBox point={100000} /> </div> )} </> {/* For Less Height */} {/* History and Revenue Rank */} {isHalfScreen && ( <div className="absolute bottom-[6px] left-[11%] flex items-center gap-[10px] mt-[10px]"> <div onClick={() => setShowRevenueRankModal(true) } className="w-[50%] h-[55px] bg-white rounded-md p-[5px] flex items-center gap-[4px] justify-between" > <div className="flex h-full gap-[5px]"> <div className="rounded-md h-full w-[45px] border-2 border-red-500"></div> <div className=""> <p className="text-[14px]"> প্রবাস... </p> <div className="flex items-center gap-[4px]"> <img src={DiamondIcon} /> <p className="text-[12px]"> 5,020,500 </p> </div> </div> </div> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6" > <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </div> <div className="w-[50%] h-[55px] bg-white rounded-md flex items-center justify-center"> <p className="">My History</p> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6 ml-[15px]" > <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </div> </div> )} </div> {/* Bottom Controls */} {/* Overlay */} <div className={`bg-[#FF6855] w-full h-[20px] ${ isHalfScreen ? "-mt-[115px]" : "-mt-[10px]" } rounded-tl-[25px] rounded-tr-[25px]`} ></div> <div className="bg-[#E33D21] w-full px-[20px] py-[10px]"> <div className="flex items-center justify-between"> {/* Left Profile and amount */} <div className="flex items-start"> <div className="w-[40px] h-[40px] border-2 border-black bg-[#864222] rounded-md"></div> <div className=""> <p className="text-white text-[11px] ml-[5px]"> 100Cr </p> <div className="w-[100px] h-[20px] bg-white rounded-tr-[20px] rounded-br-[20px] flex items-center"> <img className="ml-[5px]" src={DiamondIcon} /> <p className="text-[12px] ml-[10px]"> 80 </p> </div> </div> </div> {/* Today's Revenue */} <div className="flex flex-col items-center"> <p className="text-[11px] text-white"> Today's Revenue: </p> <div className="w-[100px] bg-white h-[20px] rounded-[20px] flex items-center justify-center"> <img className="mr-[5px]" src={DiamondIcon} /> <p className="">0</p> </div> </div> </div> {/* RESULTS */} {!isHalfScreen && ( <div className="mt-[10px] flex items-center py-[2px] px-[10px] bg-[#FF684B] rounded-md"> <p className="text-white text-[12px] font-semibold"> Results: </p> <div className="py-[5px] ml-[10px] flex items-center gap-[4px]"> <ResultBox icon={BroccoliIcon} /> <ResultBox icon={BurgerIcon} /> <ResultBox icon={SushiIcon} /> <ResultBox icon={PizzaIcon} /> <ResultBox icon={BreadIcon} /> <ResultBox icon={SushiIcon} /> </div> </div> )} {/* TWO BIG BOX */} {!isHalfScreen && ( <div className="flex items-center gap-[10px] mt-[10px]"> <div onClick={() => setShowRevenueRankModal(true) } className="w-[50%] h-[55px] bg-white rounded-md p-[5px] flex items-center gap-[4px] justify-between" > <div className="flex h-full gap-[5px]"> <div className="rounded-md h-full w-[45px] border-2 border-red-500"></div> <div className=""> <p className="text-[14px]"> প্রবাস... </p> <div className="flex items-center gap-[4px]"> <img src={DiamondIcon} /> <p className="text-[12px]"> 5,020,500 </p> </div> </div> </div> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6" > <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </div> <div className="w-[50%] h-[55px] bg-white rounded-md flex items-center justify-center"> <p className="">My History</p> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6 ml-[15px]" > <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </div> </div> )} </div> </div> </div> {showInstructionsModal && ( <InstructionsModal setShow={setShowInstructionsModal} /> )} {showRevenueRankModal && ( <RevenueRankModal setShow={setShowRevenueRankModal} /> )} </> ); } export default App;
<template> <div class="demo"> <h2>{{component.__sourceCodeTitle}}</h2> <div class="demo-component"> <component :is="component"/> </div> <div class="demo-actions"> <Button @click="hideCode" v-if="codeVisible">隐藏代码</Button> <Button @click="showCode" v-else>查看代码</Button> </div> <div class="demo-code" v-if="codeVisible"> <pre v-html="Prism.highlight(component.__sourceCode, Prism.languages.html, 'html')"/> </div> </div> </template> <script lang="ts"> import Button from '../lib/Button.vue' import 'prismjs'; import 'prismjs/themes/prism.css' import {ref} from 'vue'; const Prism = (window as any).Prism export default { components:{Button}, props: { component: Object }, setup(){ const showCode=()=>codeVisible.value=true const hideCode=()=>codeVisible.value=false const codeVisible=ref(false) return{ Prism,codeVisible,showCode,hideCode } } }; </script> <style lang="scss" scoped> $border-color: #d9d9d9; .demo { border: 1px solid $border-color; margin: 16px 0 32px; >h2 { font-size: 20px; padding: 8px 16px; border-bottom: 1px solid $border-color; } &-component { padding: 16px; } &-actions { padding: 8px 16px; border-top: 1px dashed $border-color; } &-code { padding: 8px 16px; border-top: 1px dashed $border-color; >pre { line-height: 1.1; font-family: Consolas, 'Courier New', Courier, monospace; margin: 0; } } } </style>
body{ margin: 0; /*all side margin is zero regardless of unit*/ color: #40514E; text-align: center; font-family: 'Merriweather', serif; /* font-size: 1em; when you double M to 2em then the h1 and and all other header elements will get double.Beacuse of inheritence. */ } h1{ margin: 60px auto 0 auto; font-family: 'Sacramento', cursive; /*font-size: 90px; Equivalent of 90px in % is 562.5%.That is 100% in terms of font size is 16px.So for 90px it would be 90/16 which is around 5.625 and 5.625*100 is 562.5%*/ /* font-size: 562.5%; */ font-size: 5.625em; color: #66BFBF; line-height: 2; } h2{ font-family: 'Montserrat', sans-serif; color: #66BFBF; padding-bottom: 10px; } h3{ font-family: 'Montserrat', sans-serif; color: #11999E; } .top-container { background-color: #e4f9f5; position: relative; padding-top: 100px; } .pro{ text-decoration: underline; } .programmer{ font-size: 2.5rem; color: #66BFBF; font-weight: normal; } .middle-container { margin: 100px 0px; } .bottom-container{ background-color: #66BFBF; padding: 50px 0px 20px; } .top-cloud{ position: absolute; right: 300px; top: 40px; /* 40 from the top,which means the colud moves from bottom to top*/ } .skill-row{ width: 50%; margin: 100px auto 100px auto; text-align: left; } p{ line-height: 2; } a{ color: #0E2954; font-family: 'Montserrat', sans-serif; margin: 10px 20px; text-decoration: none; } a:hover{ color: #EAF6F6; } .intro{ width: 30%; /*30% of it's parent middle-container*/ margin: auto; } hr{ border: dotted #EAF6F6 6px; /*6px is the width(തടി) with a height of zero pixel,you can see that when you remove, border-bottom: none;*/ border-bottom: none; width: 4%; /*means width from both end*/ margin: 100px auto; } .bottom-cloud{ position: absolute; left: 250px; bottom: 300px; /*bottom-cloud(child) has a bottom margin of 300px from the bottom of it's(bottom-cloud) parent top-container,the bottom and top cloud is set to absolute and these two moves relative to top-container(parent) which is set relative.If the top-container is not set to relative position the bottom and top cloud will move relative to body.In most case the parent is entire body.That is the body is the default parent.Top-container is parent,bottom and top clouds are children*/ } .ruby{ width: 35%; float: left; margin-right: 30px; } .contact-message{ width: 40%; margin: 40px auto 60px; } .perfume{ width: 35%; float: right; margin-left: 30px; } .superman{ width: 13%; } .copyright{ color: #EAF6F6; font-size: 0.75rem; /*75% of 16px*/ } .btn { background: #11cdd4; background-image: -webkit-linear-gradient(top, #11cdd4, #11999e); background-image: -moz-linear-gradient(top, #11cdd4, #11999e); background-image: -ms-linear-gradient(top, #11cdd4, #11999e); background-image: -o-linear-gradient(top, #11cdd4, #11999e); background-image: linear-gradient(to bottom, #11cdd4, #11999e); -webkit-border-radius: 8; -moz-border-radius: 8; border-radius: 8px; font-family: 'Montserrat', sans-serif; color: #ffffff; font-size: 20px; padding: 10px 20px 10px 20px; text-decoration: none; } .btn:hover { background: #30e3cb; background-image: -webkit-linear-gradient(top, #30e3cb, #2bc4ad); background-image: -moz-linear-gradient(top, #30e3cb, #2bc4ad); background-image: -ms-linear-gradient(top, #30e3cb, #2bc4ad); background-image: -o-linear-gradient(top, #30e3cb, #2bc4ad); background-image: linear-gradient(to bottom, #30e3cb, #2bc4ad); text-decoration: none; } /* .description1{ clear: left; } */ /* .description2{ clear: right; } */