text
stringlengths
184
4.48M
#include "places_brand_carousel.hpp" #include <fmt/format.h> #include <gtest/gtest.h> #include <userver/formats/json/serialize.hpp> #include <models/constructor/db_model.hpp> #include <sources/catalog/catalog_data_source.hpp> #include <widgets/places_brand_carousel/factory.hpp> namespace { using Response = eats_layout_constructor::sources::DataSourceResponses; namespace sources = eats_layout_constructor::sources; namespace catalog = sources::catalog; formats::json::Value GetWidgetData(const std::string& id, const std::string& title, const std::vector<int>& brands, std::optional<int> min_count, std::optional<int> limit, bool ignore_brands_order) { formats::json::ValueBuilder widget; widget["meta"] = formats::json::ValueBuilder{formats::json::Type::kObject}.ExtractValue(); widget["id"] = id; widget["payload"]["title"] = title; widget["type"] = "places_carousel"; widget["meta"]["brands"] = brands; widget["meta"]["ignore_brands_order"] = ignore_brands_order; if (min_count.has_value()) { widget["meta"]["min_count"] = *min_count; } if (limit.has_value()) { widget["meta"]["limit"] = *limit; } return widget.ExtractValue(); } std::shared_ptr<eats_layout_constructor::widgets::LayoutWidget> GetWidget( const std::string& id, const std::string& title, const std::vector<int>& brands, std::optional<int> min_count = std::nullopt, std::optional<int> limit = std::nullopt, bool ignore_brands_order = false) { const auto widget_data = GetWidgetData(id, title, brands, min_count, limit, ignore_brands_order); return eats_layout_constructor::widgets::places_brand_carousel:: PlacesBrandCarouselFactory( eats_layout_constructor::models::constructor::WidgetTemplateName{}, eats_layout_constructor::models::constructor::Meta{ widget_data["meta"]}, eats_layout_constructor::models::constructor::Payload{ widget_data["payload"]}, {}, widget_data["id"].As<std::string>()); } Response GetSource(int places_count) { using Catalog = eats_layout_constructor::sources::CatalogDataSource; Response response; std::vector<catalog::Place> places; places.reserve(places_count); for (auto i = 0; i < places_count; ++i) { formats::json::ValueBuilder place; place["id"] = fmt::format("id{}", i + 1); place["name"] = fmt::format("name{}", i + 1); places.push_back( catalog::Place{{sources::PlaceId(i), sources::BrandId(i), std::nullopt}, place.ExtractValue()}); } auto catalog_response = std::make_shared<Catalog::Response>(Catalog::Response{}); catalog_response->blocks["advertising"].places = places; response[Catalog::kName] = catalog_response; return response; } } // namespace TEST(PlacesBrandCarousel, MainFlow) { namespace widgets = eats_layout_constructor::widgets; auto places_carousel = GetWidget("advertising", "Рекламная пауза", {3, 2}); formats::json::ValueBuilder response; auto source = GetSource(4); EXPECT_FALSE(places_carousel->HasData()); places_carousel->FilterSourceResponse(source); EXPECT_TRUE(places_carousel->HasData()); places_carousel->UpdateLayout(response); auto json_response = response.ExtractValue(); EXPECT_EQ(json_response["layout"].GetSize(), 1); EXPECT_EQ(json_response["layout"][0]["type"].As<std::string>(), "places_carousel"); EXPECT_EQ(json_response["data"]["places_carousels"].GetSize(), 1); EXPECT_EQ(json_response["data"]["places_carousels"][0]["payload"]["places"] .GetSize(), 2); const auto& places = json_response["data"]["places_carousels"][0]["payload"]["places"]; size_t i = 0; for (int id : std::vector<int>{4, 3}) { EXPECT_EQ(places[i]["id"].As<std::string>(), fmt::format("id{}", id)); EXPECT_EQ(places[i]["name"].As<std::string>(), fmt::format("name{}", id)); ++i; } EXPECT_EQ( json_response["data"]["places_carousels"][0]["id"].As<std::string>(), "advertising"); } TEST(PlacesBrandCarousel, MainFlowIgnoreOrder) { namespace widgets = eats_layout_constructor::widgets; auto places_carousel = GetWidget("advertising", "Рекламная пауза", {0, 1, 3}, std::nullopt, std::nullopt, true); formats::json::ValueBuilder response; auto source = GetSource(3); EXPECT_FALSE(places_carousel->HasData()); places_carousel->FilterSourceResponse(source); EXPECT_TRUE(places_carousel->HasData()); places_carousel->UpdateLayout(response); auto json_response = response.ExtractValue(); EXPECT_EQ(json_response["layout"].GetSize(), 1); EXPECT_EQ(json_response["layout"][0]["type"].As<std::string>(), "places_carousel"); EXPECT_EQ(json_response["data"]["places_carousels"].GetSize(), 1); const auto& places = json_response["data"]["places_carousels"][0]["payload"]["places"]; EXPECT_EQ(places.GetSize(), 3); size_t i = 0; for (int id : std::vector<int>{1, 2, 3}) { EXPECT_EQ(places[i]["id"].As<std::string>(), fmt::format("id{}", id)); EXPECT_EQ(places[i]["name"].As<std::string>(), fmt::format("name{}", id)); ++i; } EXPECT_EQ( json_response["data"]["places_carousels"][0]["id"].As<std::string>(), "advertising"); } TEST(PlacesBrandCarousel, ContainLessThanMin) { namespace widgets = eats_layout_constructor::widgets; auto places_carousel = GetWidget("advertising", "Рекламная пауза", {1, 2}, 3); formats::json::ValueBuilder response; auto source = GetSource(4); EXPECT_FALSE(places_carousel->HasData()); places_carousel->FilterSourceResponse(source); EXPECT_FALSE(places_carousel->HasData()); places_carousel->UpdateLayout(response); auto json_response = response.ExtractValue(); EXPECT_FALSE(json_response.HasMember("layout")); EXPECT_FALSE(json_response.HasMember("data")); } TEST(PlacesBrandCarousel, ContainMoreThanMax) { namespace widgets = eats_layout_constructor::widgets; auto places_carousel = GetWidget("advertising", "Рекламная пауза", {2, 3, 4, 5, 6, 7, 1}, 3, 5); formats::json::ValueBuilder response; auto source = GetSource(7); EXPECT_FALSE(places_carousel->HasData()); places_carousel->FilterSourceResponse(source); EXPECT_TRUE(places_carousel->HasData()); places_carousel->UpdateLayout(response); auto json_response = response.ExtractValue(); EXPECT_EQ(json_response["data"]["places_carousels"][0]["payload"]["places"] .GetSize(), 5); } TEST(PlacesBrandCarousel, RequestParams) { namespace widgets = eats_layout_constructor::widgets; auto places_carousel = GetWidget("advertising", "Рекламная пауза", {}); eats_layout_constructor::sources::DataSourceParams params; places_carousel->FillSourceRequestParams(params); EXPECT_NE(params.find("catalog"), params.end()); auto catalog_params = std::any_cast<catalog::Params>(params["catalog"]); EXPECT_EQ(catalog_params.blocks.size(), 1); EXPECT_EQ(catalog_params.blocks.count("advertising"), 1); }
package com.java.vms; import com.fasterxml.jackson.databind.ObjectMapper; import com.java.vms.domain.Address; import com.java.vms.domain.Flat; import com.java.vms.domain.User; import com.java.vms.model.*; import com.java.vms.repos.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.time.OffsetDateTime; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @TestPropertySource(locations = ("classpath:application-test.properties")) @AutoConfigureMockMvc @EnableAutoConfiguration public class AdminApiTest { @Autowired private MockMvc mockMvc; private UserDTO userDTO; private User user; private Address address; private Flat flat; @Autowired private UserRepository userRepository; @Autowired private FlatRepository flatRepository; @BeforeEach public void setUp(){ address = Address.builder().id(1L).line1("Tulasi Nagar") .line2("Lingampet Road").city("jagtial").state("Telangana").country("India").pincode(505327).dateCreated(OffsetDateTime.now()) .lastUpdated(OffsetDateTime.now()).build(); user = new User(1L, "Anand", "[email protected]", 9381026991L, UserStatus.ACTIVE, Role.ADMIN, address, null, OffsetDateTime.now(),OffsetDateTime.now()); userDTO = UserDTO.builder().id(1L).name("Anand").email("[email protected]").phone(9381026991L).role(Role.ADMIN) .line1("Tulasi Nagar").line2("Lingampet Road").city("jagtial").state("Telangana").country("India") .pincode(505327).build(); flat = Flat.builder().flatNum("T-101").flatStatus(FlatStatus.AVAILABLE).build(); } @AfterEach public void tearDown() throws Exception { userRepository.deleteAll(); flatRepository.deleteAll(); } @Test public void testCreateUser() throws Exception { ObjectMapper mapper = new ObjectMapper(); String jsonData = mapper.writeValueAsString(userDTO); //Integer initialRelationSize = repository.findAll().size(); mockMvc.perform(post("/admin/user").contentType("application/json").content(jsonData)). andDo(print()).andExpect(status().isCreated()); //Integer finalRelationSize = repository.findAll().size(); User actual = userRepository.findUserByEmail("[email protected]").get(); assertThat(actual).isEqualTo(user); } @Test public void testAddFlat() throws Exception { FlatDTO flatDTO = FlatDTO.builder().flatNum("T-101").build(); ObjectMapper mapper = new ObjectMapper(); String flatJsonData = mapper.writeValueAsString(flatDTO); int initialSize = flatRepository.findAll().size(); mockMvc.perform(post("/admin/flat").contentType("application/json").content(flatJsonData)) .andDo(print()).andExpect(status().isCreated()); int finalSize =flatRepository.findAll().size(); assertThat(finalSize - initialSize).isEqualTo(1); } @Test public void testAddFlatWithFlatStatus() throws Exception { FlatDTO flatDTO = FlatDTO.builder().flatNum("T-101").flatStatus(FlatStatus.NOTAVAILABLE).build(); ObjectMapper mapper = new ObjectMapper(); String flatJsonData = mapper.writeValueAsString(flatDTO); int initialSize = flatRepository.findAll().size(); MvcResult result = mockMvc.perform(post("/admin/flat").contentType("application/json").content(flatJsonData)) .andDo(print()).andExpect(status().isCreated()).andReturn(); int finalSize =flatRepository.findAll().size(); assertThat(finalSize - initialSize).isEqualTo(1); Flat flat1 = flatRepository.findById(Long.valueOf(result.getResponse().getContentAsString())).get(); assertThat(flat1.getFlatStatus()).isEqualTo(FlatStatus.AVAILABLE); } @Test public void testChangeFlatStatusToUnAvailable() throws Exception { flatRepository.save(flat); MvcResult result = mockMvc.perform(put("/admin/changeFlatStatus").contentType("application/json") .param("num","T-101").param("st",String.valueOf(false))) .andDo(print()).andExpect(status().isOk()).andReturn(); assertThat(result.getResponse().getContentAsString().replace("\"","")).isEqualTo(FlatStatus.NOTAVAILABLE.toString()); } @Test public void testChangeFlatStatusToAvailable() throws Exception { flat.setFlatStatus(FlatStatus.NOTAVAILABLE); flatRepository.save(flat); MvcResult result = mockMvc.perform(put("/admin/changeFlatStatus").contentType("application/json") .param("num","T-101").param("st",String.valueOf(true))) .andDo(print()).andExpect(status().isOk()).andReturn(); assertThat(result.getResponse().getContentAsString().replace("\"","")).isEqualTo(FlatStatus.AVAILABLE.toString()); } }
import { useState } from 'react'; import { useReducer } from 'react'; import './App.scss'; import count from './Reducers/count'; import square from './Reducers/square'; function App() { const [number, dispatchNumber] = useReducer(count, 0); const [numberVal, setNumberVal] = useState(''); const [squareNum, dispatchSquareNum] = useReducer(square, []); const [sqVal, setSqVal] = useState(''); const add1 = () => { //pradedam nuo action objekto. Action type nusako ka mums reikes daryti const action = { type: 'plus_one' } dispatchNumber(action); //ideda, 'siuntini' i pastomata(dispatcheri). jis pristato sita objekta i reduceri. } const rem1 = () => { const action = { type: 'minus_one' } dispatchNumber(action); } const do0 = () => { const action = { type: 'reset' } dispatchNumber(action); } const add = () => { const action = { type: 'add', payload: sqVal } dispatchSquareNum(action); } const rem = () => { const action = { type: 'minus' } dispatchSquareNum(action); } const clear = () => { const action = { type: 'clear' } dispatchSquareNum(action); } const addSome = () => { const action = { type: 'add_some', payload: numberVal //tas skaicius, kuri reikia prideti } dispatchNumber(action); } const remSome = () => { const action = { type: 'rem_some', payload: numberVal } dispatchNumber(action); } const sortMin_Max = () => { const action = { type: 'min_max' } dispatchSquareNum(action); } const sortMax_max = () => { const action = { type: 'max_min' } dispatchSquareNum(action); } const even = () => { const action = { type: 'even' } dispatchSquareNum(action); } const odd = () => { const action = { type: 'odd' } dispatchSquareNum(action); } const all = () => { const action = { type: 'all' } dispatchSquareNum(action); } return ( <div className="App"> <header className="App-header"> <h1>useReducer</h1> <h2>Number now is: {number}</h2> <div className='container'> <button onClick={add1}>+1</button> <button onClick={rem1}>-1</button> <button onClick={do0}>0</button> <input className='inpt' type="text" value={numberVal} onChange={e => setNumberVal(e.target.value.length <= 2 ? e.target.value : numberVal)}></input> <button onClick={addSome}>+?</button> <button onClick={remSome}>-?</button> </div> <div className='container'> { squareNum.map((s, i) => s.show ? <div className='square-1' key={i}>{s.number}</div> : null) } </div> <div className='container'> <button onClick={add}>+[]</button> <input className='inpt' type="text" value={sqVal} onChange={e => setSqVal(e.target.value.length <= 2 ? e.target.value : sqVal)}></input> <button onClick={rem}>-[]</button> <button onClick={clear}>[x]</button> <button className='pinkish' onClick={sortMin_Max}>min-max</button> <button className='pinkish' onClick={sortMax_max}>max-min</button> </div> <div className='container'> <button className='blue' onClick={even}>Even</button> <button className='blue' onClick={odd}>Odd</button> <button className='blue' onClick={all}>All</button> </div> </header> </div> ); } export default App;
import puppeteer from 'puppeteer-core'; type Params = { html: string; width: number; height: number; }; export async function captureScreenshot({ html, width, height }: Params): Promise<Buffer | null> { const browser = await puppeteer.launch({ args: ['--headless', '--no-sandbox', '--hide-scrollbars'], channel: 'chrome', }); try { const context = await browser.createIncognitoBrowserContext(); const page = await context.newPage(); await page.setViewport({ width, height }); await page.setContent(html, { timeout: 60 * 1000, waitUntil: 'networkidle0', }); const screenshot = (await page.screenshot({ captureBeyondViewport: false, })) as Buffer; return screenshot; } finally { await browser.close(); } }
import React, {FC, useEffect} from 'react'; import {formatMoment} from 'common'; import {Bold, P} from 'common/styles/StyledText'; import {Row} from 'common/styles/layout'; import moment from 'moment'; import {View, Image, StyleSheet, useWindowDimensions} from 'react-native'; import {NotificationType} from '../reducers/notificationsReducer/types'; import theme from 'themes'; import {TouchableWithoutFeedback} from 'react-native-gesture-handler'; import Sound from 'react-native-sound'; import pingSound from '../assets/basic-ping.mp3'; const popoverStyle = (popup: boolean) => { if (!popup) { return {}; } return { shadowColor: '#000', shadowOffset: { width: 0, height: -3, }, shadowOpacity: 0.25, shadowRadius: 3.84, }; }; const Notification: FC<{ notification: NotificationType; popup?: boolean; deactivate?: () => void; }> = props => { const {content, image, timestamp, title, onPress} = props.notification; const {width} = useWindowDimensions(); // Enable playback in silence mode Sound.setCategory('Playback'); useEffect(() => { if (props.popup) { const ping = new Sound(pingSound, error => { if (error) { console.log('failed to load the sound', error); return; } // Play the sound with an onEnd callback // ping.play(success => { // if (success) { // ping.release(); // } else { // ping.release(); // } // }); }); return () => { ping.release(); }; } }, [props.popup]); const backgroundColor = () => { if (!props.popup) { ('#b2b0b092'); } return props.notification.backgroundColor || '#dbdbd9'; }; return ( <TouchableWithoutFeedback onPress={() => { if (onPress && props.popup && props.deactivate) { onPress(); props.deactivate(); } }}> <View style={[ styles.container, { backgroundColor: backgroundColor(), width: width - theme.spacing.p4, }, popoverStyle(props.popup), ]}> <Row> <Image source={image} style={styles.image} /> <View style={styles.contentContainer}> <Row style={styles.header}> <View style={styles.content}> <Bold style={styles.text} numberOfLines={1}> {title} </Bold> <P style={styles.text}>{content}</P> </View> <P style={styles.date}>{formatMoment(moment(timestamp))}</P> </Row> </View> </Row> </View> </TouchableWithoutFeedback> ); }; export default Notification; const styles = StyleSheet.create({ container: { borderRadius: 20, backgroundColor: '#b2b0b092', padding: theme.spacing.p1, borderColor: '#b2b0b092', borderWidth: 1, elevation: 5, }, contentContainer: { flexGrow: 1, width: 2, }, content: { flexShrink: 1, marginEnd: theme.spacing.p1, }, image: { height: 50, width: 50, borderRadius: 8, marginEnd: theme.spacing.p1, }, header: { alignItems: 'flex-start', }, date: { marginLeft: 'auto', marginTop: -1, color: '#343434', fontSize: 13, }, text: { color: '#343434', fontSize: 13, }, });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="preload" as="image" href="{{ asset('other_image/bg-perpis.jpg') }}"> <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}"> <title>History - {{ auth()->user()->name }}</title> </head> <style> .card-history { text-decoration: none; color: black; transition: transform .2s; } .card-history:hover { text-decoration: underline; transform: scale(1.2); } .nav-kasir { background-color: rgb(0, 76, 255); border-radius: 2px; } body { position: relative; } body::before { content: ''; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: url('{{ asset('other_image/bg-white.jpg') }}'); background-size: cover; background-repeat: no-repeat; opacity: 0.5; z-index: -1; } .wraps { padding-bottom: 200px; background-color: rgb(251, 251, 251); padding: 40px; border-radius: 5px; } </style> <body> @include('layout.nav') <div class="container mt-5 wraps"> <div class="d-flex justify-content-between"> <h2>History Pembelian</h2> <input type="search" class="form-control p-3 w-25" style="height: 40px;" name="searchHistory" id="searchHistory" placeholder="Cari Transaksi..."> </div> <div class="row mt-5" id="searchHistoryResult"> @foreach ($transaksi as $item) @php $jumlahSemua = 0; foreach ($item->detailtransaksi as $dtl) { $jumlahSemua += $dtl->qty; } @endphp <div class="col-6 mt-3"> <a href="{{ route('detail-history', $item->id) }}" class="card-history"> <div class="card"> <div class="d-flex"> <img src="{{ asset($item->detailtransaksi->first()->book->sampul_buku) }}" style="width: 130px; height: 210px; object-fit: cover;" alt="" class="card-img-top"> <div class="card-body"> <div class="d-flex justify-content-between"> <p style="font-size: large">{{ $item->nama_pembeli }} <span style="font-weight: 500">({{ \Carbon\Carbon::parse($item->created_at)->format('d F Y') }})</span></p> <p style="padding: 7px; border-radius: 2px; position: absolute; right: 0; top: 0;" class="text-white bg-success">{{ $item->invoice }} </p> </div> <div class="d-flex justify-content-between"> <p>Jumlah Semua Barang : </p> <p style="font-weight: 500;">{{ $jumlahSemua }}</p> </div> <div class="d-flex justify-content-between"> <p>Total Harga : </p> <p style="font-weight: 500;">Rp. {{ number_format($item->total_semua, 0, ',', '.') }} </p> </div> <div class="d-flex justify-content-between"> <p>Uang Dibayarkan : </p> <p style="font-weight: 500;">Rp. {{ number_format($item->uang_bayar, 0, ',', '.') }}</p> </div> </div> </div> </div> </a> </div> @endforeach </div> </div> <div style="margin-top: 400px;"> @include('layout.footer') </div> <script src="{{ asset('js/jquery-3.7.0.js') }}"></script> <script> $(document).ready(() => { $('#searchHistory').on('input', () => { var query = $('#searchHistory').val(); $.ajax({ url: '/pustakawan/search-history', method: 'GET', data: { query: query }, success: ((data) => { $('#searchHistoryResult').html(data); // data = JSON.parse(data); // let transaksi = data.transaksi; // console.log(transaksi); }), error: ((error) => { console.error('Error:', error); }), }); }); }); </script> </body> </html>
<template> <div style="overflow: hidden; height: 100vh"> <div class="login-container"> <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left" :style="{ width: windowWidth <= 992 ? '100%' : '520px', height: windowWidth <= 992 ? '100vh' : 'unset', marginTop: windowWidth <= 992 ? '0px' : '10vh', borderRadius: windowWidth <= 992 ? '0px' : '5px', }" > <div class="title-container"> <!--<img class="logo" :src="logo" alt="logo" />--> <h1 class="title-logo">Hồ sơ xây dựng</h1> <br> <h3 class="title-logo">Đăng nhập để bắt đầu!</h3> </div> <el-form-item prop="username"> <span class="svg-container"> <svg-icon icon-class="user" /> </span> <el-input ref="username" v-model="loginForm.username" placeholder="Email" name="username" type="text" tabindex="1" auto-complete="on" /> </el-form-item> <el-form-item prop="password"> <span class="svg-container"> <svg-icon icon-class="password" /> </span> <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="Mật khẩu" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" /> <span class="show-pwd" @click="showPwd"> <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /> </span> </el-form-item> <el-button type="text" size="small" @click="handlePass">Quên mật khẩu?</el-button> <el-row> <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:15px;" @click.native.prevent="handleLogin">Đăng nhập</el-button> </el-row> <el-row> <el-button :loading="loading" style="width:100%;margin-bottom:15px;" @click="handleSignup">Đăng ký</el-button> </el-row> <br> </el-form> </div> </div> </template> <script> // import { validUsername } from '@/utils/validate' import defaultSettings from '@/settings' // import logo from '@/assets/images/logo.png' export default { name: 'Login', data() { // const validateUsername = (rule, value, callback) => { // if (!validUsername(value)) { // callback(new Error('Vui lòng nhập Email')) // } else { // callback() // } // } // const validatePassword = (rule, value, callback) => { // if (value === '') { // callback(new Error('Vui lòng nhập mật khẩu')) // } else { // callback() // } // } return { title: defaultSettings.title || 'CMS', loginForm: { username: '', password: '' }, loginRules: { username: [{ required: true, trigger: 'blur' }], password: [{ required: true, trigger: 'blur' }] }, loading: false, passwordType: 'password', redirect: undefined, windowHeight: window.innerHeight, windowWidth: window.innerWidth } }, watch: { $route: { handler: function(route) { this.redirect = route.query && route.query.redirect }, immediate: true } }, mounted() { window.addEventListener('resize', this.onResize) }, beforeDestroy() { window.removeEventListener('resize', this.onResize) }, methods: { onResize() { this.windowWidth = window.innerWidth this.windowHeight = window.innerHeight }, showPwd() { if (this.passwordType === 'password') { this.passwordType = '' } else { this.passwordType = 'password' } this.$nextTick(() => { this.$refs.password.focus() }) }, handleSignup() { this.$router.push('/signup') }, handlePass() { this.$router.push('/') }, handleLogin() { this.$refs.loginForm.validate(valid => { if (valid) { this.loading = true this.$store.dispatch('user/login', this.loginForm).then(() => { this.$router.push({ path: this.redirect || '/' }) this.loading = false }).catch(() => { this.loading = false }) } else { console.log('error submit!!') return false } }) } } } </script> <style lang="scss"> $bg:#f3f4f6; $light_gray:#fff; $cursor: #fff; @supports (-webkit-mask: none) and (not (cater-color: $cursor)) { .login-container .el-input input { //color: $cursor; &:-webkit-autofill { box-shadow: 0 0 0px 1000px $bg inset !important; } } } /* reset element-ui css */ .login-container { position: relative; .logo { width: 220px; height: 210px; } .title-logo { span { color: #f43f5e; } } .title-content { font-weight: 600; font-size: 24px; color: #435b71; } .el-input { display: inline-block; height: 47px; width: 85%; input { background: transparent; border: 0; --webkit-appearance: none; border-radius: 0; padding: 12px 5px 12px 15px; height: 47px; } } .el-form-item { border: 1px solid #dcdfe6; border-radius: 5px; } } </style> <style lang="scss" scoped> $bg:#f3f4f6; $dark_gray:#889aa4; $light_gray:#eee; .login-container { min-height: 100%; width: 100%; background-color: $bg; overflow: hidden; .login-form { z-index: 2; position: relative; width: 520px; max-width: 100%; padding: 35px 35px 20px; margin: 10vh auto; overflow: hidden; box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; background: #fff; border-radius: 5px; } .tips { font-size: 14px; color: #fff; margin-bottom: 10px; span { &:first-of-type { margin-right: 16px; } } } .svg-container { padding: 6px 5px 6px 15px; color: $dark_gray; vertical-align: middle; width: 30px; display: inline-block; } .title-container { position: relative; text-align: center; .title { font-size: 26px; //color: $light_gray; margin: 0px auto 40px auto; text-align: center; font-weight: bold; } } .show-pwd { position: absolute; right: 10px; top: 7px; font-size: 16px; color: $dark_gray; cursor: pointer; user-select: none; } } </style>
#ifndef LEXER_H #define LEXER_H #include <QList> #include <QString> #include <QMap> #include <QRegExp> #include <QDebug> #include <QObject> #include <stdexcept> #include "lib/token.h" class Lexer : public QObject { Q_OBJECT public: /** * @brief constructor * * @param source String going to be tokenized */ Lexer(QString source); /** * @brief destructor */ ~Lexer(); /** * @brief tokenize the source * @return List of tokens */ QList<Token> run(); protected: /** * @brief Initialize Lexer::tokens static map * @return Map of TokenKind and it's associated regex */ static QMap<TokenKind, QRegExp> initializeTokens(); static QMap<TokenKind, QRegExp> tokens; protected: /** * @brief try to find a token on a string, begenning on given offset * * @param line QString source * @param offset index where to begin the search * * @return Token */ Token match(QString line, int offset); QString source; signals: void lexerError(QString line, int offset); }; #endif // LEXER_H
package ru.netology.nmedia.activity import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.ExperimentalCoroutinesApi import ru.netology.nmedia.R import ru.netology.nmedia.databinding.FragmentNewPostBinding import ru.netology.nmedia.databinding.FragmentSignInBinding import ru.netology.nmedia.viewmodel.PostViewModel import ru.netology.nmedia.viewmodel.SignInViewModel class SignInFragment : Fragment() { private val viewModel: SignInViewModel by viewModels() private var fragmentBinding: FragmentSignInBinding? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentSignInBinding.inflate( inflater, container, false ) fragmentBinding = binding binding.getIn.setOnClickListener { val login = binding.login.editText?.text.toString() val pass = binding.password.editText?.text.toString() viewModel.edited(login, pass) viewModel.uploadUser() } viewModel.singInState.observe(viewLifecycleOwner) { if (!it.error) findNavController().navigateUp() else Snackbar.make(binding.root, R.string.error_loading, Snackbar.LENGTH_LONG) .show() } return binding.root } override fun onDestroyView() { fragmentBinding = null super.onDestroyView() } }
# include <Siv3D.hpp> /* よりC++ライクな書き方 ・クラスベース ・継承を行う */ // 前方宣言 class Ball; class Bricks; class Paddle; bool isStart = false; bool isEnd = false; int32 Score = 0; // 定数 namespace constants { namespace brick { /// @brief ブロックのサイズ constexpr Size SIZE{ 40, 20 }; /// @brief ブロックの数 縦 constexpr int Y_COUNT = 5; /// @brief ブロックの数 横 constexpr int X_COUNT = 20; /// @brief 合計ブロック数 constexpr int MAX = Y_COUNT * X_COUNT; } namespace ball { /// @brief ボールの速さ constexpr double SPEED = 480.0; } namespace paddle { /// @brief パドルのサイズ constexpr Size SIZE{ 60, 10 }; } namespace reflect { /// @brief 縦方向ベクトル constexpr Vec2 VERTICAL{ 1, -1 }; /// @brief 横方向ベクトル constexpr Vec2 HORIZONTAL{ -1, 1 }; } } // クラス宣言 /// @brief ボール class Ball final { private: /// @brief 速度 Vec2 velocity; /// @brief ボール Circle ball; public: /// @brief コンストラクタ Ball() : velocity({ 0, -constants::ball::SPEED }), ball({ 400, 400, 8 }) {} /// @brief デストラクタ ~Ball() {} /// @brief 更新 void Update() { ball.moveBy(velocity * Scene::DeltaTime()); } /// @brief 描画 void Draw() const { ball.draw(); } Circle GetCircle() const { return ball; } Vec2 GetVelocity() const { return velocity; } /// @brief 新しい移動速度を設定 /// @param newVelocity 新しい移動速度 void SetVelocity(Vec2 newVelocity) { using namespace constants::ball; velocity = newVelocity.setLength(SPEED); } /// @brief 反射 /// @param reflectVec 反射ベクトル方向 void Reflect(const Vec2 reflectVec) { velocity *= reflectVec; } }; /// @brief ブロック class Bricks final { private: /// @brief ブロックリスト Rect brickTable[constants::brick::MAX]; public: /// @brief コンストラクタ Bricks() { using namespace constants::brick; for (int y = 0; y < Y_COUNT; ++y) { for (int x = 0; x < X_COUNT; ++x) { int index = y * X_COUNT + x; brickTable[index] = Rect{ x * SIZE.x, 60 + y * SIZE.y, SIZE }; } } } /// @brief デストラクタ ~Bricks() {} /// @brief 衝突検知 void Intersects(Ball* const target); /// @brief 描画 void Draw() const { using namespace constants::brick; for (int i = 0; i < MAX; ++i) { brickTable[i].stretched(-1).draw(HSV{ brickTable[i].y - 40 }); } } }; /// @brief パドル class Paddle final { private: Rect paddle; public: /// @brief コンストラクタ Paddle() : paddle(Rect(Arg::center(Cursor::Pos().x, 500), constants::paddle::SIZE)) {} /// @brief デストラクタ ~Paddle() {} /// @brief 衝突検知 void Intersects(Ball* const target) const; /// @brief 更新 void Update() { paddle.x = Cursor::Pos().x - (constants::paddle::SIZE.x / 2); } /// @brief 描画 void Draw() const { paddle.rounded(3).draw(); } }; /// @brief 壁 class Wall { public: /// @brief 衝突検知 static void Intersects(Ball* target) { using namespace constants; if (!target) { return; } auto velocity = target->GetVelocity(); auto ball = target->GetCircle(); // 天井との衝突を検知 if ((ball.y < 0) && (velocity.y < 0)) { target->Reflect(reflect::VERTICAL); } // 壁との衝突を検知 if (((ball.x < 0) && (velocity.x < 0)) || ((Scene::Width() < ball.x) && (0 < velocity.x))) { target->Reflect(reflect::HORIZONTAL); } } }; // 定義 void Bricks::Intersects(Ball* const target) { using namespace constants; using namespace constants::brick; if (!target) { return; } auto ball = target->GetCircle(); for (int i = 0; i < MAX; ++i) { // 参照で保持 Rect& refBrick = brickTable[i]; // 衝突を検知 if (refBrick.intersects(ball)) { // ブロックの上辺、または底辺と交差 if (refBrick.bottom().intersects(ball) || refBrick.top().intersects(ball)) { target->Reflect(reflect::VERTICAL); } else // ブロックの左辺または右辺と交差 { target->Reflect(reflect::HORIZONTAL); } // あたったブロックは画面外に出す refBrick.y -= 600; //スコアを足す Score = Score + 100; // 同一フレームでは複数のブロック衝突を検知しない break; } } } void Paddle::Intersects(Ball* const target) const { if (!target) { return; } auto velocity = target->GetVelocity(); auto ball = target->GetCircle(); if ((0 < velocity.y) && paddle.intersects(ball)) { target->SetVelocity(Vec2{ (ball.x - paddle.center().x) * 10, -velocity.y }); } } bool Button(const Rect& rect, const Font& font, const String& text) { rect.draw(ColorF{ 0.3, 0.7, 1.0 }); font(text).drawAt(40, (rect.x + rect.w / 2), (rect.y + rect.h / 2)); return (rect.leftClicked()); } // エントリー void Main() { Bricks bricks; Ball ball; Paddle paddle; const Font font{ FontMethod::MSDF, 48, Typeface::Bold }; // 終了操作を設定しない。 System::SetTerminationTriggers(UserAction::NoAction); Window::SetStyle(WindowStyle::Frameless); while (System::Update()) { if (isEnd) { font(U"Clear!").draw(50, Arg::center(400, 200), ColorF{ 1 }); if (Button(Rect{ 250, 300, 300, 80 }, font, U"もう一度")) { isEnd = false; isStart = true; ball = Ball(); bricks = Bricks(); Score = 0; } if (Button(Rect{ 250, 400, 300, 80 }, font, U"もうやめる")) { System::Exit(); } } else if (isStart) { // 更新 paddle.Update(); ball.Update(); // コリジョン bricks.Intersects(&ball); Wall::Intersects(&ball); paddle.Intersects(&ball); // 描画 bricks.Draw(); ball.Draw(); paddle.Draw(); font(U"Score:{}"_fmt(Score)).draw(40, Vec2{ 0, 0 }, ColorF{ 0.2, 0.6, 0.9 }); if (ball.GetCircle().center.y > Scene::Size().y) { isStart = false; ball = Ball(); bricks = Bricks(); Score = 0; } } else { font(U"ブロック崩し").draw(50, Arg::center(400, 200), ColorF{ 1 }); if (Button(Rect{ 250, 300, 300, 80 }, font, U"はじめる")) { isStart = true; } if (Button(Rect{ 250, 400, 300, 80 }, font, U"もうやめる")) { System::Exit(); } } //チートコード if (KeyLControl.pressed() && KeyLShift.pressed()) { Score = constants::brick::MAX * 100; } if (Score == constants::brick::MAX * 100) { isEnd = true; } } }
const express = require('express') const router = express.Router() const User = require('../../models/user') const passport = require('passport') const bcrypt = require('bcryptjs') router.get('/login', (req, res) => { res.render('login') }) router.post( '/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/users/login' }) ) router.get('/register', (req, res) => { res.render('register') }) router.post('/register', (req, res) => { const { name, email, password, confirmPassword } = req.body const errors = [] if (!name || !email || !password || !confirmPassword) { errors.push({ message: '所有欄位都要填寫。' }) } if (password !== confirmPassword) { errors.push({ message: '密碼與確認密碼不一致!' }) } if (errors.length) { return res.render('register', { errors, name, email, password, confirmPassword }) } User.findOne({ email }).then((user) => { if (user) { errors.push({ message: '該信箱已被註冊過了。' }) res.render('register', { errors, name, email, password, confirmPassword }) } }) return bcrypt .genSalt(10) .then((salt) => bcrypt.hash(password, salt)) .then((hash) => User.create({ name, email, password: hash })) .then(() => res.redirect('/')) .catch((err) => console.log(err)) }) router.get('/logout', (req, res) => { req.logout() req.flash('success_msg', '您已成功登出。') res.redirect('/users/login') }) module.exports = router
// LoginForm.js import React from 'react'; import { View, TextInput, Button, StyleSheet } from 'react-native'; const LoginForm = (props) => { const { handleLogin, handleChange, credentials } = props; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Correo electrónico" value={credentials.email} onChangeText={(text) => handleChange(text, 'email')} keyboardType="email-address" autoCapitalize="none" /> <TextInput style={styles.input} placeholder="Contraseña" value={credentials.password} onChangeText={(text) => handleChange(text, 'password')} secureTextEntry /> <Button style={styles.button} title="Iniciar sesión" onPress={handleLogin} color="#6200ee" /> </View> ); }; const styles = StyleSheet.create({ container: { padding: 20, }, input: { // width: '100%', height: 50, borderColor: '#ccc', borderWidth: 1, borderRadius: 8, marginBottom: 20, paddingHorizontal: 15, fontSize: 16, backgroundColor: '#fff', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, button: { color: '#fff', fontWeight: 'bold', fontSize: 16, textAlign: 'center', }, }); export default LoginForm;
import {useContext} from 'react'; import { Box, Table, TableContainer, TablePagination, Paper, Typography } from '@mui/material'; import EnhancedTableHead from './EnhancedTableHead'; import EnhancedTableToolbar from './EnhancedTableToolbar'; import EnhancedTableRows from './EnhancedTableRows'; import {CustomerContext} from '../../../context/CustomerContext'; export default function CustomerTable(){ const { totalCustomers, rowsPerPage, page, handleChangePage, handleChangeRowsPerPage } = useContext(CustomerContext); return ( <Box sx={{ width: '100%', marginTop:"0.8em"}}> {totalCustomers > 0 ? <Paper elevation={0} sx={{ width: '100%', mb: 2, border:"1px solid lightgray" }}> <EnhancedTableToolbar /> <TableContainer> <Table size='medium'> <EnhancedTableHead /> <EnhancedTableRows /> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={totalCustomers} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Paper> : <Typography>No customers are registered</Typography> } </Box> ); }
library(tidyverse) library(magrittr) library(data.table) library(glue) library(ungeviz) # geom_hpline library(patchwork) theme_set(theme_bw()) rm(list=ls()) filter <- dplyr::filter select <- dplyr::select desc <- dplyr::desc reduce <- purrr::reduce rename <- dplyr::rename options(stringsAsFactors = FALSE) set.seed(629) source("/analysis/lixf/my_script/my_R_function.R") setwd("/analysis/lixf/sgRNA/human/LINE_screening_combine/figure1/figure1_20220805/") act_fdr_FACS <- fread("../LINE1_activator_fdr_0.1_FACS_20220803.csv")%>% mutate(group = "supporter") colnames(act_fdr_FACS)[1] <- "id" act_fdr_FACS <- mutate(act_fdr_FACS,id2=fct_reorder(id,desc(value),mean)) act_fdr_FACS$id %>% table() %>% table sup_fdr_FACS <- fread("../LINE1_suppressor_fdr_0.1_FACS_20220803.csv") %>% mutate(group = "suppressor") colnames(sup_fdr_FACS)[1] <- "id" sup_fdr_FACS <- mutate(sup_fdr_FACS,id2=fct_reorder(id,desc(value),mean)) sup_fdr_FACS$id %>% table() %>% table() df <- rbind(act_fdr_FACS,sup_fdr_FACS) df$id2 <- factor(df$id2,c(levels(sup_fdr_FACS$id2), levels(act_fdr_FACS$id2)) %>% unique) filterDf <- df #### add another group of NC library(rstatix) tmp <- filterDf %>% mutate(group = factor(group,levels = c("suppressor","supporter"))) %>% filter(group == "suppressor") %>% filter(id != "NC") %>% select(id2,value) %>% mutate(group = "KO") length <- tmp$id2 %>% unique %>% length() ncValue <- tmp %>% filter(id == "NC") %>% pull(value) %>% unique() NC <- data.frame(id2 = rep(tmp$id2 %>% unique, each = 3 ),value = rep(c(ncValue),length)) %>% mutate(group = "NC") suppressor_pvalue <- rbind(tmp,NC) %>% group_by(id2) %>% t_test( value ~ group,alternative = "greater") fwrite(suppressor_pvalue,"suppressor_FACS_pvalue_df.tsv",sep = '\t') colorManual <- c(supporter = "#b92b27",suppressor = "#1565C0") Psupp <- filterDf %>% mutate(group = factor(group,levels = c("suppressor","supporter"))) %>% filter(id != "NC") %>% filter(group == "suppressor") %>% mutate(id2=fct_reorder(id,desc(value),mean)) %>% ggplot(aes(x=id2,y=value,color = group))+ #geom_bar(stat="identity")+ stat_summary(fun = "mean", colour = "black",width = 0.5,size=0.6,geom = "hpline",alpha=0.8)+ geom_hline(yintercept = 1,linetype=2,color="black",alpha=0.5,size=0.2)+ geom_point(shape=1,size=0.5)+ scale_color_manual(values = colorManual)+ #facet_wrap(~group,scales = "free",nrow = 2)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), text=element_text(size= 8,family = "ArialMT",color = "black"), plot.subtitle = element_text(hjust = 1), axis.ticks.length.x = unit(0.05, "cm"), axis.text.x = element_text(angle=90,vjust=0.5,hjust = 1), plot.margin = margin(0.3,1,0.3,0.3, "cm"), strip.placement = "outside", strip.background = element_blank(), legend.position = "bottom", legend.key.width= unit(6, 'pt'), legend.key.height= unit(4, 'pt'), )+guides(fill=guide_legend(title=""),color = "none")+xlab("")+ylab("FACS GFP value \n(relative to NC)") library(rstatix) tmp <- filterDf %>% mutate(group = factor(group,levels = c("suppressor","supporter"))) %>% filter(group == "supporter") %>% filter(id != "NC") %>% select(id2,value) %>% mutate(group = "KO") length <- tmp$id2 %>% unique %>% length() NC <- data.frame(id2 = rep(tmp$id2 %>% unique, each = 3 ),value = rep(c(ncValue),length)) %>% mutate(group = "NC") supporter_pvalue <- rbind(tmp,NC) %>% group_by(id2) %>% t_test( value ~ group,alternative = "less") fwrite(supporter_pvalue,"activator_FACS_pvalue_df.tsv",sep = '\t') Pacti <- filterDf %>% mutate(group = factor(group,levels = c("suppressor","supporter"))) %>% filter(id != "NC") %>% filter(group == "supporter") %>% mutate(id2=fct_reorder(id,desc(value),mean)) %>% ggplot(aes(x=id2,y=value,color = group))+ #geom_bar(stat="identity")+ stat_summary(fun = "mean", colour = "black",width = 0.5,size=0.6,geom = "hpline",alpha=0.8)+ geom_hline(yintercept = 1,linetype=2,color="black",alpha=0.5,size=0.2)+ geom_point(shape=1,size=0.5)+ scale_color_manual(values = colorManual)+ #facet_wrap(~group,scales = "free",nrow = 2)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), text=element_text(size= 8,family = "ArialMT",color = "black"), plot.subtitle = element_text(hjust = 1), axis.ticks.length.x = unit(0.05, "cm"), axis.text.x = element_text(angle=90,vjust=0.5,hjust = 1), plot.margin = margin(0.3,1,0.3,0.3, "cm"), strip.placement = "outside", strip.background = element_blank(), legend.position = "bottom", legend.key.width= unit(6, 'pt'), legend.key.height= unit(4, 'pt'), )+guides(fill=guide_legend(title=""),color = "none")+xlab("")+ylab("FACS GFP value \n(relative to NC)") Psupp/Pacti ggsave("GFP_FACS_combine_usingMean_230102.pdf",height=2.8,width = 3.2,useDingbats = F)
package com.junq.practice.springboot.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith ( SpringRunner.class ) @SpringBootTest ( webEnvironment = RANDOM_PORT ) public class IndexControllerTest { @Autowired private TestRestTemplate restTemplate; @Test public void 메인페이지_로딩() { // when // '/' url 로 부터 String 객체를 받아서 body 변수에 대입 String body = this.restTemplate.getForObject( "/", String.class ); //then assertThat( body ).contains( "스프링 부트로 시작하는 웹 서비스" ); } }
require 'spec_helper' describe UsersController do render_views before :each do User.all.each { |d| d.remove } @user = FactoryGirl.create :user Tag.all.each { |d| d.remove } @tag = FactoryGirl.create :user_tag Report.clear @r1 = FactoryGirl.create :r1 @r2 = FactoryGirl.create :r2 @r3 = FactoryGirl.create :r3 @r1.tag = @tag && @r1.save @r1.user = @user @r1.save @r3.tag = @tag && @r3.save @r3.user = @user @r3.save setup_sites end describe 'reports' do it 'should show reports' do @request.host = 'test.host' @site = Site.where( :domain => 'test.host', :lang => 'en' ).first Report.all.each do |r| r.site = @site r.save end n_reports = Report.where( :user => @user ).length get :reports, :username => @user.username response.should be_success response.should render_template('users/reports') rs = assigns(:reports) rs.should_not be nil rs.length.should > 1 rs.length.should eql n_reports rs.each_with_index do |r, idx| unless idx == rs.length-1 nnext = rs[idx+1] r.created_at.should be >= nnext.created_at end end end it 'should show one report' do get :report, :name_seo => @user.reports.first.name_seo, :username => @user.username response.should be_success response.should render_template('users/report') assigns( :report ).should_not eql nil assigns( :report ).user.should eql @user end end describe 'galleries' do it 'should list galleries' do get :galleries, :username => @user.username response.should be_success assigns( :galleries ).should_not eql nil end it 'lists galleries ONLY for this domain' do get :galleries, :username => @user.username assigns( :galleries ).each do |g| g.site.domain.should eql @request.host end end it 'should show gallery' do Gallery.all.each { |g| g.remove } @g = FactoryGirl.create :gallery @g.galleryname = '1234a' @g.name = 'Name' @g.user = @user @g.is_public = true flag = @g.save puts! @g.errors if !flag ( flag ).should eql true get :gallery, :username => @user.username, :galleryname => @user.galleries.first.galleryname response.should be_success assigns( :gallery ).should_not eql nil end end describe 'organizer' do it 'should GET organizer' do sign_in :user, @user get :organizer response.should be_success assigns(:cities_user).should_not eql nil response.should render_template('organizer') assigns(:current_user).should_not eql nil end it 'should redirect to login if the user is not logged in' do sign_out :user get :organizer response.should be_redirect response.should redirect_to("/en/users/sign_in") end it 'should let edit user' do sign_in :user, @user user = { :id => @user.id, :github_path => 'http://github.com/piousbox', :display_ads => false } post :update, :user => user, :id => @user.id result = User.find @user.id result.github_path.should eql user[:github_path] result.display_ads.should eql user[:display_ads] end end describe 'github page' do it 'should show the github page inside piousbox' do sign_out :user get :github_page, :username => @user.username response.should be_success response.should render_template('github') end end describe 'profiles' do it 'should GET new profile' do sign_in :user, @user get :new_profile response.should be_success response.should render_template('users/new_profile') assigns(:user_profile).should_not eql nil end it 'sets current user as the owner of the profile when creating' do sign_in :user, @user @user.user_profiles.each { |p| p.remove } profile = { :education => 'education', :objectives => 'objectives', :lang => 'ru' } post :create_profile, :user_profile => profile User.find( @user.id ).user_profiles.length.should eql 1 end it 'GETs edit profile' do sign_in :user, @user @user.user_profiles << UserProfile.new( :lang => :en, :about => 'A little about me' ) @user.save.should eql true get :edit_profile, :username => @user.username, :profile_id => @user.user_profiles[0].id response.should be_success # todo end end describe 'gallery' do it 'should have list of this users galleries' do get :galleries, :username => @user.username response.should render_template('users/galleries') assigns(:galleries).should_not eql nil end end describe 'report' do it 'should GET report of a user' do get :reports, :username => @user.username, :name_seo => @r1.name_seo response.should render_template('users/report') end end describe 'index' do it 'only shows users with a gallery or report' do get :index response.should render_template('users/index') us = assigns(:users) us.each do |u| if u.reports.length > 0 ; elsif u.galleries.length > 0 ; else false.should eql true end end end end describe 'about' do it 'should GET about' do sign_out :user get :about response.should be_success response.should render_template('users/about') p end end describe 'set layout of organizer' do ## The layout is now hardcoded # # it 'should display layout organizer' do # sign_in :user, @user # get :organizer, :layout => 'organizer' # response.should be_success # response.should render_template('users/organizer') # end it 'should display layout application' do sign_in :user, @user get :organizer response.should be_success response.should render_template('layouts/application') get :organizer, :layout => 'application_mini' response.should be_success response.should render_template('layouts/application_mini') end end describe 'settings' do it 'gets settings' do get :edit response.should be_success response.should render_template('users/edit') end it 'POSTs to settings' do post :update, :user => { } response.should be_redirect response.should redirect_to( :action => :organizer ) end end end
import 'package:flutter/material.dart'; class DrawerScreen extends StatelessWidget { const DrawerScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Drawer'), ), drawer: const Drawer( child: Column( children: [ UserAccountsDrawerHeader( accountName: Text('Hitan'), accountEmail: Text('[email protected]'), currentAccountPicture: CircleAvatar(child: Icon(Icons.person))), ListTile( title: Text('Inbox'), leading: Icon(Icons.mail), ), ListTile( title: Text('Primary'), leading: Icon(Icons.stay_primary_portrait), ), ListTile( title: Text('Social'), leading: Icon(Icons.people), ), ListTile( title: Text('Promotions'), leading: Icon(Icons.local_offer), ), ListTile( title: Text('Spam'), leading: Icon(Icons.warning), ), ListTile( title: Text('Starred'), leading: Icon(Icons.star), ), ], )), body: Center( child: Text('This is Drawer'), ), ); } }
using Simple_Task_List_Application; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Simple_Task_List_Application { public class Task { public String task_title; public String task_description; } internal class Program { List<Task> tasks = new List<Task>(); public void run() { int input_choice =0 ; do { Console.WriteLine("Welcome! This is a Simple Task List Application"); Console.WriteLine("Below are the features:"); Console.WriteLine("1. Add a new Task."); Console.WriteLine("2. Display the list of Tasks"); Console.WriteLine("3. Update a task"); Console.WriteLine("4. Delete a task"); Console.WriteLine("5. Exit"); Console.WriteLine("Enter your choice: "); try { input_choice = int.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("Please Enter a Valid Input"); continue; } switch (input_choice) { case 1: add_task(); break; case 2: display_tasks(); break; case 3: update_task(); break; case 4: delete_task(); break; case 5: Console.WriteLine("Successfully Exited"); break; default: Console.WriteLine("Please Enter a Number with in the range"); break; } Console.WriteLine("\n\n"); } while (input_choice != 5); } void add_task() { Task new_task=new Task(); Console.WriteLine("Enter the task title"); new_task.task_title = Console.ReadLine(); Console.WriteLine("Enter the task description"); new_task.task_description = Console.ReadLine(); tasks.Add(new_task); Console.WriteLine("Task is Successfully added"); } void display_tasks() { if (tasks.Count() == 0) { Console.WriteLine("There are no tasks to display"); } else { int i = 1; foreach ( var Task in tasks) { Console.WriteLine($"Task {i} title is :{Task.task_title}"); Console.WriteLine($"Task {i} description is :{Task.task_description}"); i++; } } } void update_task() { int count = 0; if (tasks.Count()==0) { Console.WriteLine("There are no tasks to update"); } else { Console.WriteLine("Enter the title of the task to update"); String title_of_task= Console.ReadLine(); for (int i = 0; i < tasks.Count; i++) { if (title_of_task == tasks[i].task_title) { Console.WriteLine("Enter the new title of the task"); tasks[i].task_title = Console.ReadLine(); Console.WriteLine("Enter the new description of the task"); tasks[i].task_description = Console.ReadLine(); count++; } } if (count == 0) { Console.WriteLine("There is no task with the given title"); } else { Console.WriteLine("Task is Successfully updated"); } } } void delete_task() { int count = 0; if (tasks.Count() == 0) { Console.WriteLine("There are no tasks to delete"); } else { Console.WriteLine("Enter the title of the task to delete"); String title_of_task = Console.ReadLine(); for (int i = 0; i < tasks.Count; i++) { if (title_of_task == tasks[i].task_title) { tasks.RemoveAt(i); count++; } } if (count == 0) { Console.WriteLine("There is no task with the given title"); } else { Console.WriteLine("Task is Successfully deleted"); } } } static void Main(string[] args) { Program Application = new Program(); Application.run(); } } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('translation_values', function (Blueprint $table) { $table->id(); $table->foreignId('translation_id')->constrained()->cascadeOnDelete(); $table->string('language', 10)->index(); $table->text('value')->fulltext()->nullable(); $table->timestamp('verified_at')->nullable(); $table->timestamps(); $table->unique(['translation_id', 'language']); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('translation_values'); } };
// components import ArtistsGridItem from "@components/ArtistsGridItem"; import Select from "@ui/Select"; import Pagination from "@ui/Pagination"; import CategoryHeader from "@ui/CategoryHeader"; // hooks import { useState, useEffect } from "react"; import usePagination from "@hooks/usePagination"; // constants import { PRODUCT_CATEGORIES, PRODUCT_SORT_OPTIONS } from "@constants/options"; // utils import { sortProducts } from "@utils/helpers"; // data placeholder // import products from "@db/artists"; import AddArtistModal from "@components/AddArtistModal"; import { getAllAtrists } from "../api/artists_api"; import { useSelector } from "react-redux"; const ItemsGrid = () => { const options = PRODUCT_CATEGORIES.filter( (option) => option.value !== "all" ); const pending = useSelector((state) => state.artist.isPending); const [category, setCategory] = useState(options[0]); const [sort, setSort] = useState(PRODUCT_SORT_OPTIONS[0]); const [modal, setModal] = useState(false); const [artists, setArtists] = useState([]); const [preview, setPreview] = useState({ image: null, }); useEffect(() => { const getArtists = async () => { const response = await getAllAtrists({ limit: 10, offset: 2 }); console.log(response.data); setArtists(response.data); }; getArtists(); }, [pending]); const productsByCategory = artists.filter( (artist) => artist.category === category.value ); console.log(productsByCategory); const sortedProducts = sortProducts(productsByCategory, sort.value); console.log(sortedProducts); const pagination = usePagination(sortedProducts, 12); const handleAddNewSong = () => { setModal(true); }; console.log(pagination.currentItems()); useEffect(() => { pagination.goToPage(0); // eslint-disable-next-line react-hooks/exhaustive-deps }, [category, sort]); return ( <> <AddArtistModal modal={modal} setClose={() => setModal(false)} /> <div className="grid gap-[26px] lg:grid-cols-4 2xl:grid-cols-6"> {/* <CategoryHeader category={category.value} /> */} <button className="btn btn--primary" onClick={handleAddNewSong}> Add new artist <i className="icon-circle-plus-regular" /> </button> <div className="flex flex-col-reverse gap-4 lg:flex-col lg:gap-3 lg:col-start-3 lg:col-end-5 2xl:col-start-5 2xl:col-end-7" > <span className="lg:text-right"> View artists: {pagination.showingOf()} </span> {/* <div className="grid gap-2.5 sm:grid-cols-2 sm:gap-[26px]"> <Select value={category} onChange={setCategory} options={options} /> <Select value={sort} onChange={setSort} options={PRODUCT_SORT_OPTIONS} /> </div> */} </div> </div> <div className="grid flex-1 items-start gap-[26px] mt-5 mb-[30px] sm:grid-cols-2 md:grid-cols-3 md:mt-7 lg:grid-cols-4 2xl:grid-cols-6" > {artists.map((product, index) => ( <ArtistsGridItem key={index} product={product} index={index} isSlide={"div"} /> ))} </div> {pagination.maxPage > 1 && <Pagination pagination={pagination} />} </> ); }; export default ItemsGrid;
import { CommandHandler, ICommandHandler } from "@nestjs/cqrs" import { Contract } from "../../../../../infrastructure/utils/contract" import { UsersRepository } from "../../../../sa/repository/mongoose/users.repository" import { ErrorEnums } from "../../../../../infrastructure/utils/error-enums" export class ConfirmationCommand { constructor(public code: string) { } } @CommandHandler(ConfirmationCommand) export class Confirmation implements ICommandHandler<ConfirmationCommand> { constructor( protected usersRepository: UsersRepository, ) { } async execute(command: ConfirmationCommand): Promise<Contract<null | boolean>> { const confirmationCodeDto = ["emailConfirmation.confirmationCode", command.code] const user = await this.usersRepository.findUser(confirmationCodeDto) if (user === null) return new Contract(null, ErrorEnums.USER_NOT_FOUND) if (user.checkConfirmation() === true) return new Contract(null, ErrorEnums.USER_EMAIL_CONFIRMED) if (user.checkExpiration() === false) return new Contract(null, ErrorEnums.CONFIRMATION_CODE_EXPIRED) user.updateUserConfirmation() await this.usersRepository.saveDocument(user) return new Contract(true, null) } }
<!-- templates/home.html --> {% extends 'base.html' %} {% load static %} {% load thumbnail %} {% block title %}Главная страница{% endblock %} {% block content %} {% include 'components/header.html' %} <main class="main-background"> <div class="home-container"> <div class="home-welcome"> <h2 class="home-welcome-title">Начните свою карьеру<br>в сельскохозяйственной сфере!</h2> <p class="home-welcome-subtitle">Наша платформа помогает связать<br>работодателей и соискателей в одном месте.</p> <div class="home-welcome__buttons"> <button class="btn-primary-large btn-fluid">Смотреть вакансии</button> <button class="btn-secondary-large btn-fluid">Смотреть соискателей</button> </div> </div> <div class="home-menu"> <div class="home-menu__card"> <a href="#" class="home-menu__card-link"> <div class="home-menu__card-item"> <img src="{% static 'img/internships/1.png' %}" class="home-menu__card-img" alt="меню стажировки"> <div class="home-menu__card-content"> <h3 class="home-menu__card-content-title">Стажировки</h3> <p class="home-menu__card-content-subtitle">Отличный старт для будущей карьеры и шанс улучшить свои навыки.</p> </div> </div> </a> </div> <div class="home-menu__card"> <a href="#" class="home-menu__card-link"> <div class="home-menu__card-item"> <img src="{% static 'img/internships/2.png' %}" class="home-menu__card-img" alt="меню стажировки"> <div class="home-menu__card-content"> <h3 class="home-menu__card-content-title">Практики</h3> <p class="home-menu__card-content-subtitle">Получайте ценные знания и навыки, которые помогут в будущей карьере.</p> </div> </div> </a> </div> <div class="home-menu__card"> <a href="#" class="home-menu__card-link"> <div class="home-menu__card-item"> <img src="{% static 'img/internships/3.png' %}" class="home-menu__card-img" alt="меню стажировки"> <div class="home-menu__card-content"> <h3 class="home-menu__card-content-title">Поиск жилья</h3> <p class="home-menu__card-content-subtitle">Предоставление места для проживания от работодателей.</p> </div> </div> </a> </div> <div class="home-menu__card"> <a href="#" class="home-menu__card-link"> <div class="home-menu__card-item"> <img src="{% static 'img/internships/4.png' %}" class="home-menu__card-img" alt="меню стажировки"> <div class="home-menu__card-content"> <h3 class="home-menu__card-content-title">Блог о карьере</h3> <p class="home-menu__card-content-subtitle">Делитесь своим опытом с другими и заводите полезные знакомства.</p> </div> </div> </a> </div> </div> <div class="home-article"> <div class="home-article__header"> <h2 class="home-article__header-name">Новые вакансии</h2> <a class="home-article__header-link" href="#">Показать всё</a> </div> <div class="home-article__items"> {% for vac in vacancies %} {% include 'components/home-entity-card-vacancy.html' %} {% empty %} <p class="other-inf__item-promt">Нет вакансий</p> {% endfor %} </div> </div> <div class="home-article"> <div class="home-article__header"> <h2 class="home-article__header-name">Компании недели</h2> <a class="home-article__header-link" href="#">Показать всё</a> </div> <div class="home-article__items"> {% for c in companies %} {% include 'components/home-entity-card-company.html' %} {% empty %} <p class="other-inf__item-promt">Нет компаний</p> {% endfor %} </div> </div> <div class="home-article"> <div class="home-article__header"> <h2 class="home-article__header-name">Соискатели недели</h2> <a class="home-article__header-link" href="#">Показать всё</a> </div> <div class="home-article__items"> {% for w in workers %} {% include 'components/home-entity-card-worker.html' %} {% empty %} <p class="other-inf__item-promt">Нет работников</p> {% endfor %} </div> </div> <div class="home-article"> <div class="home-article__header"> <h2 class="home-article__header-name">Новости агросферы</h2> <a class="home-article__header-link" href="#">Показать всё</a> </div> <div class="home-article__items"> {% for n in news %} <div class="box"> <div class="home-news__title"></div> <div class="home-news__body"></div> <div class="home-nes__img"></div> </div> {% empty %} <p class="other-inf__item-promt">Новостей нет</p> {% endfor %} </div> </div> </div> </main> {% include 'components/footer.html' %} {% endblock %}
import React from "react"; import Button from "@mui/material/Button"; import TextField from "@mui/material/TextField"; export default function seatType({seatTypes, setSeatTypes, numberOfSeatTypes, setNumberOfSeatTypes}) { return ( <div className={"seat-type-container"}> <div className={"seat-type-header"}> <Button onClick={(e) => { e.preventDefault(); setNumberOfSeatTypes(numberOfSeatTypes + 1); setSeatTypes([...seatTypes, { name: "", price: "", numberOfSeats: "", // "description": "" }]) }}>Add Seat Type </Button> <Button onClick={(e) => { e.preventDefault(); if (numberOfSeatTypes > 0) { setNumberOfSeatTypes(numberOfSeatTypes - 1); setSeatTypes(seatTypes.slice(0, -1)); // Remove the last element } }} > Remove Seat Type </Button> </div> <div className={"seat-type-body"}> { seatTypes.map((seatType) => { return ( <div className={"seat-type"}> <TextField id="outlined-basic" label="Seat Type Name" type ="text" variant="outlined" required={true} value={seatType.name} onChange={(event) => { seatType.name = event.target.value; setSeatTypes([...seatTypes]) }} sx={{width: "25%"}} /> <TextField id="outlined-basic" label="Seat Type Price" variant="outlined" required={true} type="number" value={seatType.price} onChange={(event) => { seatType.price = event.target.value; if(seatType.price < 0) { seatType.price = 0; } setSeatTypes([...seatTypes]) }} sx={{width: "25%"}} /> <TextField id="outlined-basic" label="Seat Type Capacity" variant="outlined" required={true} type="number" value={seatType.numberOfSeats} onChange={(event) => { if(event.target.value < 0) { event.target.value = 0; } seatType.numberOfSeats = event.target.value; setSeatTypes([...seatTypes]) }} sx={{width: "25%"}} /> {/*<TextField id="outlined-basic" label="Seat Type Description"*/} {/* variant="outlined" required={true}*/} {/* value={seatType.description}*/} {/* onChange={(event) => {*/} {/* seatType.description = event.target.value;*/} {/* setSeatTypes([...seatTypes])*/} {/* }}*/} {/* sx={{width: "25%"}}*/} {/*/>*/} </div> ) }) } </div> </div> ); }
<?php namespace My; use Monolog\Logger; use Monolog\Handler\StreamHandler; use Monolog\Handler\FirePHPHandler; class Helpers { const MAX_FILE_SIZE = 2097152; private static $_logger; public static function log() : Logger { if (is_null(self::$_logger)) { self::$_logger = new Logger("app"); $path = __DIR__ . "/../logs/app.log"; // self::$_logger->pushHandler(new StreamHandler($path, Logger::DEBUG)); self::$_logger->pushHandler(new FirePHPHandler()); } return self::$_logger; } /** * Decir hola al usuario * * @return string */ public static function sayHello($username) { return "Hello {$username}"; } public static function url(string $path, bool $ssl = false): string { $protocol = $ssl ? "https" : "http"; return "{$protocol}://localhost/tarda/Projecte/microframework/web/{$path}"; } public static function render(string $path, array $__params = []):string { ob_start(); $root = __DIR__ . "/../web"; include("{$root}/{$path}"); $content = ob_get_contents(); ob_end_clean(); return $content; } public static function redirect(string $url) : string { ob_clean(); //ob_flush(); // use ob_clean() instead to discard previous output header("Location: {$url}"); exit(); } public static function upload(array $file, string $folder = "") : string { if ($file["error"]) { throw new \Exception("Upload error with code " . $file["error"]); } else if ($file["size"] > self::MAX_FILE_SIZE) { throw new \Exception("Upload maximum file exceeded (2MB)"); } else { $dir = __DIR__ . "/../uploads/{$folder}"; $path = $dir . "/" . basename($file["name"]); $tmp = $file["tmp_name"]; if (move_uploaded_file($tmp, $path)) { return $path; } else { throw new \Exception("Unable to upload file at {$path}"); } } } public static function flash(string $msg = ""): array { session_start(); $list = $_SESSION["flash"] ?? []; if(empty($msg)) { unset($_SESSION['flash']); }else { $list[] = $msg; $_SESSION["flash"] = $list; } return $list; } }
package ru.practicum.shareit.booking; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.practicum.shareit.booking.service.BookingService; import static org.springframework.http.HttpStatus.CREATED; import static org.springframework.http.HttpStatus.OK; /** * TODO Sprint add-bookings. */ @RestController @RequestMapping(path = "/bookings") public class BookingController { private final BookingService bookingService; public BookingController(BookingService bookingService) { this.bookingService = bookingService; } @PostMapping public ResponseEntity<?> add(@RequestHeader("X-Sharer-User-Id") Long bookerId, @RequestBody Booking booking) { return new ResponseEntity<>(bookingService.addBooking(bookerId, booking), CREATED); } @PatchMapping("/{id}") public ResponseEntity<?> approve(@RequestHeader("X-Sharer-User-Id") Long bookerId, @PathVariable("id") Long id, @RequestParam(value = "approved") Boolean approved) { return new ResponseEntity<>(bookingService.approved(bookerId, id, approved), OK); } @GetMapping("/{id}") public ResponseEntity<?> get(@RequestHeader("X-Sharer-User-Id") Long userId, @PathVariable("id") Long id) { return new ResponseEntity<>(bookingService.findBooking(userId, id), OK); } @GetMapping public ResponseEntity<?> getAllUserBookings(@RequestHeader("X-Sharer-User-Id") Long bookerId, @RequestParam(value = "state", required = false) String bookingState, @RequestParam(value = "from", required = false) Integer from, @RequestParam(value = "size", required = false) Integer size) { return new ResponseEntity<>(bookingService.findAllBookerBookings(bookerId, bookingState, from, size), OK); } @GetMapping("/owner") public ResponseEntity<?> getAllOwnerBookings(@RequestHeader("X-Sharer-User-Id") Long ownerId, @RequestParam(value = "state", required = false) String bookingState, @RequestParam(value = "from", required = false) Integer from, @RequestParam(value = "size", required = false) Integer size) { return new ResponseEntity<>(bookingService.findAllOwnerBookings(ownerId, bookingState, from, size), OK); } }
import {reactive, unref} from "vue"; import type {Todo} from "@/interfaces/todo"; import {addToLocalStorage, getTodoListFromLocalStorage} from "@/utils/todoUtils"; import {ToastMessage} from "@/state-management/ToastMessage"; export const TodoList = reactive({ todos: [] as Todo[], loadTodos(){ this.todos = getTodoListFromLocalStorage() }, addNewTodo(todo: string) { if (getIndex(todo) === -1) { this.todos.push({name: todo, isFinished: false}) addToLocalStorage(this.todos) } else { ToastMessage.toast = { severity: 'error', summary: 'Todo Already Exist!', detail: 'Please Choose Another Name', life: 4000 } } }, removeTodo(todo: Todo) { const index = getIndex(todo.name) if (index !== -1) { this.todos.splice(index, 1) addToLocalStorage(this.todos) } }, finishTodo(todo: Todo) { const index = getIndex(todo.name) if (index !== -1) { this.todos[index].isFinished = true addToLocalStorage(this.todos) } } }) function getIndex(todo: string) { return TodoList.todos.findIndex(value => value.name === todo ) }
package com.example.app2_bussinesscard import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Phone import androidx.compose.material.icons.filled.Share import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.app2_bussinesscard.ui.theme.App2_BussinessCardTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App2_BussinessCardTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { App() } } } } } @Composable fun IntroSection(){ val image = painterResource(R.drawable.icon) Column { Image( painter = image, contentDescription = null, modifier = Modifier .padding(1.dp) .align(alignment = Alignment.CenterHorizontally) ) Text( text = "My Business", fontSize = 24.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray, modifier = Modifier .padding(1.dp) .align(alignment = Alignment.CenterHorizontally) ) Text( text = "Here join My Business to get more Profit", color = Color.Gray, fontSize = 10.sp, modifier = Modifier .padding(1.dp) .align(alignment = Alignment.CenterHorizontally) ) } } @Composable fun ContactSection(){ Column { Row { Icon(Icons.Filled.Phone, contentDescription = "Phone Icon", tint = Color.DarkGray) Spacer(modifier = Modifier.width(15.dp)) Text( text = "+92 300 0000000", color = Color.Gray ) } Spacer(modifier = Modifier.height(10.dp)) Row { Icon(Icons.Filled.Share, contentDescription = "Phone Icon", tint = Color.DarkGray) Spacer(modifier = Modifier.width(15.dp)) Text( text = "@MyBusiness", color = Color.Gray ) } Spacer(modifier = Modifier.height(10.dp)) Row { Icon(Icons.Filled.Email, contentDescription = "Phone Icon", tint = Color.DarkGray) Spacer(modifier = Modifier.width(15.dp)) Text( text = "[email protected]", color = Color.Gray ) } } } @Composable fun App(){ Box(modifier = Modifier.background(color = Color.LightGray)){ Column( modifier = Modifier .fillMaxSize() .padding(bottom = 26.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.weight(1f)) IntroSection() Spacer(modifier = Modifier.weight(1f)) ContactSection() } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { App2_BussinessCardTheme { App() } }
import React, { useState } from 'react'; import Image from 'next/image'; import { Modal, Button } from 'react-bootstrap'; const ImgProfesor = 'https://firebasestorage.googleapis.com/v0/b/coiner-2022.appspot.com/o/profesores%2FWEB_COINER_PROFESORES_Jennifer%20Mc%20Donald.png?alt=media&token=b51a7de6-199e-4399-9b9d-f6a14fa5c49e'; interface ProfesorGProps { nombre?: string; titulo?: string; trayectoria?: string; onHide?: () => void; show?: boolean; } function ProfesorG() { const [modalShow, setModalShow] = useState(false); function MyVerticallyCenteredModal(props: ProfesorGProps) { return ( <Modal className="text-light" {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Body> <div className="contenedor-modal"> <Button className="boton-cerrar" onClick={props.onHide}> x </Button> <Image width={310} height={422} className="p-4 m-4 " src={ImgProfesor} alt="Jennifer Mc Donald" /> <div className="texto"> <p className="nombre">Jennifer Mc Donald</p> <p className="titulo-ponente"> MKT Jennifer Mingramm Paciente AAT{' '} </p> <p className="trayectoria text-cyan-900"> Maestra en mercadotecnia otorgada por la Universidad de Bérgamo en Italia en 1999. En 2013 padeció un evento que le cambió la vida y la mantuvo fuera de cualquier actividad hasta el 2015. A partir de 2017 se ha dedicado a realizar múltiples conferencias sobre su testimonio en diversos estados de la república; buscando crear conciencia de la existencia de enfermedades raras. Jennifer ha tenido que enfrentarse a muchas negativas y adversidades y se ha convertido desde entonces en un puñado de tenacidad al ejercer su derecho a la salud para obtener la medicación necesaria y vivir con una mejor calidad al no permitir que la realidad distorsione su entorno. Actualmente se encuentra matriculada en la carrera de derecho, y es parte clave en el área de idiomas en la ONG en la que cede su tiempo para personas de recursos limitados. El testimonio de Jennifer es una muestra que cuando uno está convencido de que se quiere sobrevivir aparecen fuerzas necesarias y se adoptan actitudes que la acercan a su objetivo. Diagnóstico: Deficiencia de alfa 1 antitripsina (2014){' '} </p> </div> </div> </Modal.Body> </Modal> ); } return ( <> {' '} <div onClick={() => setModalShow(true)} className="flex flex-wrap place-content-center items-center p-8 transition-colors duration-200 transform cursor-pointer group s,sm:flex-col-reverse " > <img className="object-cover w-42 h-52 m-4 " src={ImgProfesor} alt="Jennifer Mc Donald Coiner 2022" /> <div className="flex flex-col "> <span className="bg-[#0c4e8b] rounded-[4rem] px-[3rem] py-2 pb-5 ml-4 "> <h3 className=" mt-4 text-3xl text-center font-semibold text-[#1ed4ff] capitalize dark:text-white "> Jennifer Mc Donald </h3> <p className="mt-2 text-[white] text-center capitalize dark:text-gray-300 max-w-xs "> MKT Jennifer Mingramm Paciente AAT{' '} </p> </span> </div> </div> <MyVerticallyCenteredModal show={modalShow} onHide={() => setModalShow(false)} /> </> ); } export default ProfesorG;
:py:mod:`ifcpatch.recipes.FixArchiCADToRevitSpaces` .. py:module:: ifcpatch.recipes.FixArchiCADToRevitSpaces Module Contents --------------- .. py:class:: Patcher(src, file, logger) Allow ArchiCAD IFC spaces to open as Revit rooms The underlying problem is that Revit does not bring in IFC spaces as spaces / rooms in Revit when you link an IFC in Revit. This has been broken for at least 3 years and counting. This is a problem typically for ArchiCAD architects who want to send rooms to MEP folks using Revit. See bug: https://github.com/Autodesk/revit-ifc/issues/15 The solution is to open an IFC in Revit instead of linking it, which will convert IFC spaces into Revit rooms. However, there are very specific scenarios where Revit will convert these rooms, which have been painstakingly reverse engineered through trial and error. Firstly, the rooms should have a lower bound with a Z value matching the Z value of the storey it is on. Secondly, although faceted breps do work in some scenarios (I assume Revit has an internal topological analysis tool), conversion to an extruded area solid yield much more robust results. Finally, changing the Precision value to an obscene number very strangely seems to cause a lot more rooms to be converted successfully. This patch is designed to only work on ArchiCAD IFC exports where the only contents of the IFC is IFC space and `nothing else`. It also requires you to run it using Blender, as the geometric modification uses the Blender geometry engine. Example: .. code:: python ifcpatch.execute({"input": "input.ifc", "file": model, "recipe": "FixArchiCADToRevitSpaces", "arguments": []}) .. py:method:: patch()
# 🚀 Radarr to Plex Collections 🍿 Welcome to Radarr to Plex Collections! Say goodbye to scattered movies and hello to organized collections, all with the click of a button (or command)! ## 🎥 About Plex attempts automatically create collections (if you have that setting enabled), but is inconsistent at best and does nothing at worst. Radarr to Plex Collections automates the process of creating Plex movie collections directly from your existing Radarr movie collections, streamlining your media management experience. ## ❓ What are plex collections? Plex collections allow you to organize your media library by grouping related movies together. These collections are visible in the Plex interface under the "Collections" tab within a movie library, making it easy to browse and access movies within each collection. Additionally, within each movie's details in Plex, the collection it belongs to is displayed, providing a convenient way to watch movies in order or explore related content. ## 🌟 Features - **Automated Collection Creation**: Radarr to Plex Collections seamlessly generates movie collections in Plex based on your existing collections in Radarr. > **Note:** This application will not work for movies that are not managed in Radarr. For example, if you have three Harry Potter movies in Plex that are not managed by Radarr, they will not be added to the Harry Potter Collection. - **Effortless Automation**: With Radarr to Plex Collections, automate the entire process effortlessly. Set it up once, and let the tool handle the rest. Save time and effort by automating the management of your collections seamlessly. ## 🛠️ Prerequisites Before setting up Radarr to Plex Collections, make sure you have the following: 1. **Radarr and Plex Servers**: Ensure you have both Radarr and Plex servers set up, you will need administrator access to both Radarr and Plex. 2. **Radarr API Version**: This application was built using v3 of the Radarr API, ensure you're able to use version 3 of the API for your Radarr install. Once you have these prerequisites in place, you'll be ready to set up Radarr to Plex Collections seamlessly. ## 🖥️ Supported Operating Systems Radarr to Plex Collections is compatible with the following operating systems and architectures: | Operating System | Architecture | Compatibility | |------------------|--------------|---------------| | Windows 11 | x64 | ✅ | | Windows 10 | x86, x64 | ✅ | | Linux (Ubuntu) | x86, x64, ARM| ✅ | | Linux (Debian) | x86, x64, ARM| ✅ | | macOS | x64, ARM | ✅ | ## 💾 Backup Plex It's recommended that you back up your Plex server before running this application. Backing up your Plex server ensures that you can recover your media library and settings in case you don't like what Radarr to Plex Collections does or in case of data loss/system failure. If you're not familiar with how to backup your Plex server, I recommend [Lon.Tv's Guide](https://www.youtube.com/watch?v=aA4GMoUU2Zg) as the process varies depending on your operating system. ## 💡 Getting Started To get started with Radarr to Plex Collections, follow these simple steps: 1. **Download the Latest Release**: Visit the [Releases](https://github.com/gingersnap96/radarr-to-plex-collections/releases) page and download the latest release of Radarr to Plex Collections. Look for the release package named something like `radarr-to-plex-vX.X.X-win-x64.zip`. Make sure to select the release package appropriate for your operating system (Windows, Linux or macOS) and architecture (x86, x64, arm). 2. **Extract the Files**: After downloading the zip file, extract its contents to a directory of your choice on your machine. 3. **Navigate to the Directory**: Open the folder where you extracted the files. ## ⚙️ Usage Using Radarr to Plex Collections is a breeze: 1. **Configure Settings**: Open the `config.json` file and provide your Radarr and Plex server details. - **RadarrURL**: Replace `"your_radarr_url_here"` with the URL of your Radarr instance. This typically looks like `http://localhost:7878` unless you've configured it differently. - **RadarrAPIKey**: Replace `"your_radarr_api_key_here"` with your Radarr API key. You can find this in Radarr under Settings > General > Security. - **PlexURL**: Replace `"your_plex_url_here"` with the URL of your Plex instance. This typically looks like `http://localhost:32400`. - **PlexToken**: Replace `"your_plex_token_here"` with your Plex authentication token. To obtain the token, follow these steps: 1. Log in to your Plex account in the Plex Web App. 2. Browse to any library item in your Plex server. 3. Select "Get Info" on the library item. 4. Select View XML button on the Get Info page. 5. View the URL of the xml and locate the value associated with the `X-Plex-Token` parameter (usually at the end of the URL). 6. Copy the value of the `X-Plex-Token` parameter (value after =) and paste it into the `PlexToken` field in your `config.json` file. 7. Save and close the confif file. - **MinForCollection**: Set `"MinForCollection"` to the minimum number of movies required to create a collection. For example, if you set it to `2`, collections will only be created when you have 2 or more movies in that collection in your Plex library. - **LibraryName**: Replace `"Movies"` with the name of the library in Plex for which you want to create collections if yours is different. - **DeleteExistingPlexCollections**: Acceptable values are `true` or `false`. If set to true the application will delete all pre-existing collections within plex. It is advised to set to true if Plex auto-generated some collections as this application may generate a duplicate collection with a slightly different name. Keep in Mind this will delete any collections you created manually as well. - **Exclusions**: Optionally, fill out the `"Exclusions"` array with the names of collections you want to exclude from synchronization. Do not delete the placeholders if you don't need to exclude any collections. Ensure to follow the format mentioned in the Exclusions Configuration section below. 2. **Run the Application**: - **For Windows**: - Double-click the `RadarrToPlex.exe` executable to launch the application. - To add it as a scheduled task, open Task Scheduler, click "Create Basic Task", and follow the wizard to schedule the `RadarrToPlex.exe` to run at your desired intervals. Set the "Start in" field to the directory where the `RadarrToPlex.exe` file is located. - **For Linux**: - Open a terminal and navigate to the directory containing the `RadarrToPlex` executable (It will have no extension). - Ensure that the `config.json` file is also located in this directory. - Run the following command to add execute permissions to the executable: (you only need to do this once) ```bash chmod +x RadarrToPlex ``` - Run the following command to add execute the application: ```bash ./RadarrToPlex ``` - To add it as a scheduled task using cron jobs: 1. Open the crontab editor by running `crontab -e`. 2. Add a new line specifying the desired schedule and command to run the `RadarrToPlex` executable. Make sure to specify the full path to the directory containing the executable. - **For macOS**: - Double-click the `RadarrToPlex` executable to launch the application(It will have no extension). - You may get a security warning and your OS will prevent the app from running, if so follow the steps below. - Open Settings > Security and Privacy > General Tab - If you just tried to run the application there should be an option to allow the application, select allow. - Double-click the `RadarrToPlex` executable to launch the application 3. **Review Log File:** Each time the application runs it will create a log file for you to review the output of the application. - For Windows and Linux this folder will be created in the folder the executable is in. - For macOS the log file will be created in `{Mac HD}/users/{user}/logs` 4. **Sit Back and Enjoy**: Once the application has finished running, navigate to your Plex server to enjoy your newly organized movie collections! ## 🛑 Exclusions Configuration In the `config.json` file, you have the option to specify collections that you want to exclude from the synchronization process. The collection name can be found in Radarr in the collections tab. Here's how to fill out the exclusions section: ```json "Exclusions": [ { "CollectionName": "Harry Potter Collection" }, { "CollectionName": "Star Wars Collection" } ] ``` ## ℹ️ Additional Information ### Showing or Hiding Plex Collections In Plex, you have the option to show or hide collections within a library. Here's how you can manage this: 1. **Log in to Plex**: Open the Plex Web App and log in to your Plex account. 2. **Access Library Settings**: Navigate to the library where you want to manage collections. 3. **Click on the Library**: Hover over the library in the sidebar and click on the ellipsis (`...`) icon that appears. 4. **Select Library Settings**: From the dropdown menu, select "Manage Library" then "Edit" (the exact wording may vary depending on the Plex version). 5. **Toggle Collection Visibility**: In the Library Settings under advanced, you'll find an option related to collections. Toggle the setting to either show or hide collections within this library. 6. **Save Changes**: Once you've adjusted the collection visibility setting to your preference, make sure to save your changes. By managing collection visibility, you can customize the presentation of your library to suit your preferences and browsing habits. ## 🔍 Troubleshooting Encountering issues? Here are some common problems and suggested solutions: - **401 Unauthorized Error**: If you encounter a 401 Unauthorized error, double-check your API key for Radarr and Plex. Ensure that the API keys provided in the `config.json` file are correct and properly configured with the required permissions. - **Application Not Running**: If the application fails to run, verify that the executable file (`RadarrToPlex` or `RadarrToPlex.exe`) has the appropriate permissions to execute. You may need to adjust the file permissions using the `chmod` command on Linux/macOS. - **Empty Plex Collections**: If Plex collections are not created or appear empty, ensure that your Radarr library contains movies with associated collections. Collections will only be created in Plex for movies that are managed within Radarr. - **Schedule Not Working**: If the scheduled task fails to run as expected, review the task scheduler settings to ensure that the task is configured correctly with the appropriate start time, frequency, and working directory. If you continue to experience issues after troubleshooting, feel free to open an issue for further assistance. ## 📄 License This project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details. ## 🤝 Contributing Contributions are welcome from everyone! Whether you're a seasoned developer or simply have an idea to share! ### Contribution Guidelines: 1. Fork the repository. 2. Create a new branch for your feature or bug fix. 3. Make your changes. 4. Submit a pull request with a clear description of your changes and their purpose. 5. Your pull request will be reviewed by the maintainers, and feedback may be provided for further improvements. 6. Once approved, your changes will be merged into the main branch. Happy contributing! ## 📧 Contact Have questions or suggestions? Feel free to open an issue!
import { getTopMovies } from 'api'; import { Loader } from 'components/Loader/Loader'; import { TopList } from 'components/TopList/TopList'; import { useEffect, useState } from 'react'; import toast from 'react-hot-toast'; const HomePage = () => { const [topMovies, setTopMovies] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => { async function getMovies() { try { setIsLoading(true); const fetchedMovies = await getTopMovies(); setTopMovies(fetchedMovies.results); } catch { return toast.error('Something went wrong... Try again!'); } finally { setIsLoading(false); } } getMovies(); }, []); return ( <> <Loader statuse={isLoading} /> <h2> Trending today</h2> <TopList movieList={topMovies} /> </> ); }; export default HomePage;
from tkinter import * from tkinter import messagebox import pyperclip import random import json # ---------------------------- PASSWORD GENERATOR ------------------------------- # def generate_password(): password_entry.delete(0, END) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] password_list = [] password_list += [random.choice(letters) for _ in range(random.randint(8, 10))] password_list += [random.choice(numbers) for _ in range(random.randint(2, 4))] password_list += [random.choice(symbols) for _ in range(random.randint(2, 4))] random.shuffle(password_list) password = "".join(password_list) password_entry.insert(0, password) pyperclip.copy(password) # ---------------------------- SAVE PASSWORD ------------------------------- # def save_password(): website = website_entry.get() username = username_entry.get() password = password_entry.get() new_data = { website: { "email": username, "password": password, } } if "" not in {website_entry.get(), username_entry.get(), password_entry.get()}: try: with open("passwords.json", "r") as password_file: # Read old data data = json.load(password_file) # Updating old data with new data data.update(new_data) except FileNotFoundError: data = new_data finally: with open("passwords.json", "w") as password_file: # Saving updated data json.dump(data, password_file, indent=4) clear_form() else: messagebox.showerror(title="Incomplete Information", message="Please fill all data fields.") def clear_form(): website_entry.delete(0, END) username_entry.delete(0, END) username_entry.insert(0, "[email protected]") password_entry.delete(0, END) def search_password(): try: site = website_entry.get() with open("passwords.json", 'r') as password_file: data = json.load(password_file) email = data[site]["email"] password = data[site]["password"] messagebox.showinfo(title=site, message=f"Email: {email}\nPassword: {password}") except FileNotFoundError: messagebox.showinfo(title="File not found", message=f"No password file found.") except KeyError: messagebox.showinfo(title="Entry not found", message=f"No details for '{site}' found.") # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.config(padx=50, pady=50) window.title("Password Manager") canvas = Canvas(width=200, height=200) logo_img = PhotoImage(file="logo.png") canvas.create_image(100, 100, image=logo_img) canvas.grid(row=0, column=1) # Website label, website entry (width:35) website_label = Label(text="Website:", width=15, anchor='e') website_label.grid(row=1, column=0, sticky='e') website_entry = Entry(width=32) website_entry.grid(row=1, column=1, columnspan=2, sticky='w') website_entry.focus() website_button = Button(text="Search", command=search_password, width=13) website_button.grid(row=1, column=2, sticky='w') # Email/Username label, email/username entry (width: 35) username_label = Label(text="Email/Username:", width=15, anchor='e') username_label.grid(row=2, column=0, sticky='e') username_entry = Entry(width=50) username_entry.grid(row=2, column=1, columnspan=2, sticky='w') username_entry.insert(0, "[email protected]") # Password label, password entry (width: 21), generate button password_label = Label(text="Password:", width=15, anchor='e') password_label.grid(row=3, column=0, sticky='e') password_entry = Entry(width=32) password_entry.grid(row=3, column=1, sticky='w') password_button = Button(text="Generate", command=generate_password, width=13) password_button.grid(row=3, column=2, sticky='w') # Add button (width: 35) add_button = Button(text="Add", width=42, command=save_password) add_button.grid(row=4, column=1, columnspan=2, sticky='w') window.mainloop()
<body style="background-color:rgba(125, 125, 155);"> <h1>Ejercicios "Variables y tipos de datos"</h1> <p>1. variables</p> </body> <?php /* El comando echo y print permiten mostrar el valor de una variable e información en general. La diferencia principal es que echo no devuelve ningún valor y print devuelve 1, por lo que puede ser usado en expresiones. Por ello, echo es más rápido. Ambos se pueden usar con o si paréntesis. Crear dos variables que contengan números. Luego, crea otra variable para la suma. Crealiza un "echo" con una frase que contenga la variable suma. Crea un "print" con la misma frase y guardalo en una variable, por último, comprueba se la variable creada devuelve un 1. */ $num1 = 8; $num2 = 7; $suma = $num1 + $num2; echo "La suma de los dos números es: " . $suma; echo "<br><br>"; $pri = print("La suma de los dos números es: " . $suma); echo "<br><br>"; echo $pri; ?> <p>2. tipos de datos</p> <?php /* PHP puede inferir y trabajar con los siguientes tipos de datos: cadenas, enteros, flotantes, booleanos, arrays, objetos y null. Crea una variable de cada tipo y luego muestra por pantalla con la función var_dump() el tipo de valor de la expresión. Recuerda que no necesitas realizar echo o print para mostrar la función. */ $cadena = "Hola Mundo"; var_dump($cadena); echo "<br>"; $entero = 4; var_dump($entero); echo "<br>"; $flotante = 8.05; var_dump($flotante); echo "<br>"; $booleano = False; var_dump($booleano); echo "<br>"; $array = array(23, "Manuel", True); var_dump($array); echo "<br>"; $nulo = null; var_dump($nulo); echo "<br>"; $objeto = new class(){}; var_dump($objeto); echo "<br>"; ?> <p>2.1 Strings</p> <?php /* Algunas de las muchas funciones para trabajar con strings en PHP: ◦ strlen(): devuelve la longitud de una cadena. ◦ str_word_count(): devuelve el numero de palabras de una cadena. ◦ strrev(): devuelve la cadena invertida. ◦ strpos(): busca un texto en una cadena y devuelve su posición. ◦ str_repalce(): busca un texto en una cadena y lo reemplaza por otro. Crea una sentencia "echo" para cada función de los string, haciendo referencia a las caracteristicas de la función. Ejemplo: echo "La longitud de la cadena es: " . strlen($c) . "<br>"; Puedes usar la cadena que quiera, o esta cadena de ejemplo: $cad= "Esto es una cadena de caracteres" */ $cad = "Exemplaris Excomvinicationis"; echo "La longitud de la cadena es: " . strlen($cad) . "<br>"; echo "La cadena tiene: " . str_word_count($cad) . " palabras. <br>"; echo "La cadena inversa es: " . strrev($cad) . "<br>"; echo "La cadena pla está en la posición: " . strpos($cad, "pla") . "<br>"; echo "Reemplazo: " . str_replace($cad, "Exemplaris", "Mundo") . "<br>";
#pragma once #include "WeakPtr.h" #include <utility> #include <algorithm> #include <exception> #include <iostream> class RefCounter{ public: RefCounter(unsigned int users = 0, unsigned int weak_users = 0) : users(users), weak_users(weak_users) { std::cout << "Users" << users << " Weak-users" << weak_users << "\n"; } ~RefCounter() { } unsigned int getUsers() {return users;} void setUsers(unsigned int value) {users = value;} unsigned int getWeakUsers() {return weak_users;} void setWeakUsers(unsigned int value) {weak_users = value;} void increment_users() {users++;} void decrement_users() {if (users > 0) users--;} void increment_weak_users() {weak_users++;} void decrement_weak_users() {if (weak_users > 0) weak_users--;} private: unsigned int users; unsigned int weak_users; }; template<typename T> class SharedPtr { public: /* * Constructors */ SharedPtr() : ptr(nullptr), refs(new RefCounter()){} SharedPtr(std::nullptr_t nptr) : ptr(nptr), refs(new RefCounter()){} SharedPtr(T* obj) : ptr(obj), refs(new RefCounter(1)){} //SharedPtr(WeakPtr<T> obj) {} //Some questions has arised SharedPtr(SharedPtr& obj) : ptr(obj.ptr), refs(obj.refs) { refs->increment_users(); } SharedPtr(SharedPtr&& obj) : ptr(nullptr), refs(new RefCounter()) { this->swap(obj); } ~SharedPtr() { if(refs != nullptr) { if(refs->getUsers() <= 1) { if(ptr != nullptr) delete ptr; delete refs; } else { refs->decrement_users(); ptr = nullptr; refs = nullptr; } } } /* * Operators */ SharedPtr& operator=(SharedPtr& obj) { if(obj != *this) { ptr = obj.get(); refs->decrement_users(); refs = obj.refs; refs->increment_users(); } return *this; } SharedPtr& operator=(SharedPtr&& obj) { if(obj != *this) { swap(obj); obj.reset(); } return *this; } bool operator==(std::nullptr_t nptr) const { return ptr == nptr; } bool operator==(const SharedPtr& compare_to) const { return ptr == compare_to.ptr; } bool operator<(const SharedPtr& compare_to) { return ptr < compare_to.ptr; } operator bool() { return ptr != nullptr; } bool operator<(std::nullptr_t nptr){ return this < nptr; } T& operator*() { return *ptr; } T* operator->() { return ptr; } T* get() { return ptr; } bool unique(){ return refs->getUsers() == 1; } void reset() { if(!ptr) return; if(refs->getUsers() <= 1) { delete ptr; ptr = nullptr; refs->setUsers(0); } else { refs->decrement_users(); ptr = nullptr; refs = new RefCounter(); } } private: T* ptr; //unsigned int* users; RefCounter* refs; void swap(SharedPtr& obj) { std::swap(ptr, obj.ptr); std::swap(refs, obj.refs); } };
import { BsFillInfoSquareFill, BsCameraFill } from "react-icons/bs"; import { HiPlus } from "react-icons/hi"; import { useState } from "react"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import Modal from "react-bootstrap/Modal"; import "./firstCard.scss"; import { useDispatch, useSelector } from "react-redux"; import { putFirstPageAction } from "../../redux/action"; import "./Modale.scss"; import { addFotoProfile, getProfileAction } from "../../redux/action/index"; const Modale = (props) => { const dispatch = useDispatch(); const profile = useSelector((state) => state.linkedin.profile); const [profileInternal, setProfileInternal] = useState(profile); const [fd, setFd] = useState(new FormData()); const handleFile = (ev) => { setFd((prev) => { prev.delete("profile"); prev.append("profile", ev.target?.files[0]); return prev; }); }; const handleSubmit = (ev) => { ev.preventDefault(); dispatch(addFotoProfile(fd, props.id)); }; return ( <> <Modal.Header closeButton> <Modal.Title id="example-modal-sizes-title-lg">Modifica introduzione</Modal.Title> </Modal.Header> <Modal.Body className="modale"> <p style={{ fontSize: "0.8em" }}>*Indica che è obbligatorio</p> <Form> <p className="text-black">Aggiungi la tua foto di profilo</p> <Form.Group onSubmit={handleSubmit} className="mb-3"> <input type="file" id="file" onChange={(e) => { setProfileInternal((prev) => ({ ...prev, image: handleFile(e) })); }} /> <label for="file" className="inputFile"> <BsCameraFill /> <small>Aggiungi foto</small> </label> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Nome*</Form.Label> <Form.Control className="ModalFormControl" placeholder={profileInternal.name} type="text" autoFocus value={profileInternal.name} onChange={(e) => { setProfileInternal((prev) => ({ ...prev, name: e.target.value })); }} /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Cognome*</Form.Label> <Form.Control className="ModalFormControl" type="text" autoFocus value={profileInternal.surname} onChange={(e) => { setProfileInternal((prev) => ({ ...prev, surname: e.target.value })); }} /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Nome aggiuntivo*</Form.Label> <Form.Control className="ModalFormControl" type="text" autoFocus /> </Form.Group> <p style={{ fontSize: "0.8em" }}>Pronuncia del nome</p> <p style={{ fontSize: "0.8em", color: "#1f1f1f" }}> <BsFillInfoSquareFill /> Può essere aggiunta solo usando la nostra app per dispositivi mobili </p> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Inserisci i pronomi personalizzati</Form.Label> <Form.Control className="ModalFormControl" type="text" autoFocus /> <p style={{ fontSize: "0.8em" }}> Indica i pronomi di genere che vuoi che gli altri usino per riferirsi a te. </p> </Form.Group> <p> Scopri di più sui <span className="ModalSpan">pronomi di genere</span> </p> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Sommario*</Form.Label> <Form.Control className="ModalFormControl" type="text" autoFocus value={profileInternal.bio} onChange={(e) => { setProfileInternal((prev) => ({ ...prev, bio: e.target.value })); }} /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p style={{ fontSize: "1.3em", color: "black" }}>Posizione attuale</p> <Form.Label style={{ color: "#1f1f1f" }}>Posizione lavorativa*</Form.Label> <Form.Select className="ModalFormControl" aria-label="Default select example" type="text" autoFocus> <option value="3">Seleziona</option> </Form.Select> </Form.Group> <p> <Button className="ModalButton"> <HiPlus /> Aggiungi una nuova posizione lavorativa </Button> </p> <form className="d-flex align-items-center me"> <input type="checkbox" id="check" hidden /> <label for="check" className="checkmark"></label> <label className="ms-1">Mostra l’azienda attuale nella mia presentazione</label> </form> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p>Settore*</p> <Form.Control className="ModalFormControl" type="text" autoFocus value={profileInternal.title} onChange={(e) => { setProfileInternal((prev) => ({ ...prev, title: e.target.value })); }} /> </Form.Group> <p> Scopri di più sulle <span className="ModalSpan">opzioni relative al settore</span> </p> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p style={{ fontSize: "1.3em", color: "black" }}>Formazione</p> <p>Formazione*</p> <Form.Select className="ModalFormControl" aria-label="Default select example" type="text" autoFocus> <option value="3">Seleziona</option> </Form.Select> </Form.Group> <div> <Button className="ModalButton"> <HiPlus /> Aggiungi un nuovo grado di formazione </Button> </div> <form className="d-flex align-items-center me"> <input type="checkbox" id="check1" hidden /> <label for="check1" className="checkmark1"></label> <label className="ms-1">Mostra la formazione nella mia presentazione</label> </form> <p style={{ fontSize: "1.3em", color: "black" }}>Località</p> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p>Paese/Area geografica*</p> <Form.Control className="ModalFormControl" type="text" autoFocus /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p>CAP*</p> <Form.Control className="ModalFormControl" type="text" autoFocus /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <p>Città*</p> <Form.Control className="ModalFormControl" type="text" autoFocus value={profileInternal.area} onChange={(e) => { setProfileInternal((prev) => ({ ...prev, area: e.target.value })); }} /> </Form.Group> <p style={{ fontSize: "1.3em", color: "black" }}>Informazioni di contatto</p> <p>Aggiungi o modifica il tuo profilo URL, indirizzo email e altro</p> <Button className="LastModalButton">Modifica le informazioni di contatto</Button> </Form> </Modal.Body> <Modal.Footer> <Button style={{ borderRadius: "5em", width: "5em" }} variant="primary" onClick={() => { dispatch(addFotoProfile(fd, props.id)); dispatch(putFirstPageAction(profileInternal)); dispatch(getProfileAction(props.id)); window.location.reload(); }} > Salva </Button> </Modal.Footer> </> ); }; export default Modale;
<?php namespace App\Http\Middleware; use App\Providers\RouteServiceProvider; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class RedirectIfAuthenticated { // /** // * Handle an incoming request. // * // * @param \Illuminate\Http\Request $request // * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next // * @param string|null ...$guards // * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse // */ // public function handle(Request $request, Closure $next, ...$guards) // { // $guards = empty($guards) ? [null] : $guards; // foreach ($guards as $guard) { // if (Auth::guard($guard)->check()) { // return redirect(RouteServiceProvider::HOME); // } // } // return $next($request); // } public function handle($request, Closure $next) { if (auth('web')->check()) { return redirect(RouteServiceProvider::HOME); } if (auth('student')->check()) { return redirect(RouteServiceProvider::STUDENT); } if (auth('teacher')->check()) { return redirect(RouteServiceProvider::TEACHER); } if (auth('parent')->check()) { return redirect(RouteServiceProvider::PARENT); } return $next($request); } }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>balancedSampling</title> <link href="../css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" type="text/css" href="../css/template_index.css"> </head> <body> <div> <div><img src="../img/bitl.png"></div> <div class="navbar"> <div class="navbar-inner"> <ul class="nav"> <li><a href="../index.html">HOME</a></li> <li><a href="../introduction/introduction.html">Intreoduction</a></li> <li><a href="../professor/professor.html">Professor</a></li> <li><a href="../members/members.html">Members</a></li> <li><a href="../research/research_journal.html">Research</a></li> <li><a href="../education/education.html">Education</a></li> <li class="active"><a href="../sw/software.html">Software</a></li> </ul> </div> </div> </div> <div class="board"> <div class="menu"> <ul class="nav nav-pills nav-stacked"> <li> <a href="./software.html">BIO SOFTWARE</a> </li> <li> <a href="./balancedSampling.html">balancedSampling</a> </li> <li> <a href="./f_interaction.html">f_interaction</a> </li> <li> <a href="./Hybrid_RFE.html">Hybrid RFE</a> </li> </ul> </div> <div class="content"> <h3>[ Balanced Train/Test set sampling ]</h3> <h4>1. introduction</h4> <div> <p>In machine learning, classification is the technique of identifying to which categories or classes a new observation belongs, based on a training set. The performance of a classification model is generally measured by classification accuracy of a test set. The first step of developing a classification model is to divide the obtained whole dataset into training and test sets by random sampling. In general, random sampling does not guarantee that test accuracy reflects performance of a developed classification model. If random sampling makes biased training/test sets, classification model may produce biased accuracy. In this study, we show the problems of random sampling, and propose balanced sampling as an alternative to random sampling. We also propose a measure for evaluating sampling methods. We perform empirical experiments to verify our sampling algorithm produces proper training/test sets using benchmark datasets. The results confirm that our method leads to better training/test sets than random sampling and several non-random sampling methods.</p> <img width="100%" height="100%" src="figure2.jpg"> <div allign="center">Figure1. Pseudo Code of balanced sampling</div> </div> <br> <h4>2. Download</h4> <div> <ul> <li>Source code of balanced sampling : <a href="balancedSampling.R" download> balancedSampling.R</a> </li> <li>Test code of balanced sampling : <a href="test.R" download> test.R</a> </li> <li>Sample dataset : <a href="dataset.csv" download>dataset</a> </li> </ul> </div> <br> <h4>3. Basic Usage</h4> <div> <ol> <li>Install <a href="https://cran.r-project.org/bin/windows/base/">R software.</a></li> <li>Run R software.</li> <li>Run test code in R console.</li> </ol> <p>※We assume all downloaded files are in 'c:\works' folder.</p> </div> <br> <h4>4. citation request</h4> <div> <p>[Author], Balanced Training/Test Set Sampling for Proper Evaluation of Classification Models, [institution], [page]</p> </div> </div> </div> </body> </html>
import { useState, useEffect } from 'react'; import { userService } from '@/services'; import { NavLink } from './NavLink'; export { Nav }; function Nav() { const [token, setToken] = useState(null); useEffect(() => { const subscription = userService.token.subscribe(x => setToken(x)); return () => subscription.unsubscribe(); }, []); function logout() { userService.logout(); } // Show only after log in if (!token) return null; return ( <nav className='navbar navbar-expand navbar-dark bg-dark'> <div className='navbar-nav'> <NavLink href="/" exact className="nav-item nav-link"></NavLink> <a onClick={logout} className='nav-item nav-link'>Logout</a> </div> </nav> ); }
""" Dedicated flow to generate M8 report process """ from datetime import datetime from datetime import date from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.providers.amazon.aws.transfers.sql_to_s3 import SqlToS3Operator from airflow.providers.postgres.operators.postgres import PostgresOperator """ Below is Dag's property :property:: 'owner': 'airflow', 'start_date': datetime(2023, 9, 6), 'retries': 1, """ default_args = { 'owner': 'airflow', 'start_date': datetime(2023, 9, 6), 'retries': 1, } s3_report_path = str(date.today().year) + '/' + str(date.today().month) + '/' + str(date.today().day) with DAG( dag_id='dev_m8_report_daily', default_args=default_args, schedule_interval=None, ) as dag: start_workflow = DummyOperator(task_id='start_workflow') load_m8_reporting_table = PostgresOperator( task_id="load_m8_reporting_table", postgres_conn_id="citris_postgres_conn_id", sql='sql/payment_monitoring/m8_transfer_return_payment_reconciliation.sql' ) store_m8_report_into_s3 = SqlToS3Operator( task_id='store_m8_report_into_s3', sql_conn_id='citris_postgres_conn_id', query='select * from citrisfinancial_report.m8_transfer_return_payment_reconciliation where report_date = current_date', s3_bucket='dev-monitoring-control-reports', s3_key=s3_report_path + '/m8_transfer_return_payment_reconciliation.csv', replace=True, ) end_workflow = DummyOperator(task_id='end_workflow') start_workflow >> load_m8_reporting_table >> store_m8_report_into_s3 >> end_workflow
package study_spring.domain; import java.time.LocalDateTime; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity public class Article { @Id // 기본키 @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false) private long id; @Column(name = "title", nullable = false) private String title; @Column(name = "content", nullable = false) private String content; @Builder // 빌더패턴 (받아오는 값으로 생성) public Article (String title, String content) { this.title = title; this.content = content; } public void update(String title, String content) { this.title = title; this.content = content; } @CreatedDate // 엔티티 생성시각 @Column(name = "created_at") private LocalDateTime createdAt; @LastModifiedDate // 엔티티 수정시각 @Column(name = "updated_at") private LocalDateTime updatedAt; // // 기본생성자 @@NoArgsConstructor 로 대체 // protected Article() { // } // // // Getter // public Long getId() { // return id; // } // // // Getter // public String getTitle() { // return title; // } // // // Getter // public String getContent() { // return content; // } }
# replaceitem ## replaceitem - Nr: 0 Replaces items in inventories. ```mcfunction replaceitem block <position x: coordinate> <position y: coordinate> <position z: coordinate> slot.container <slot id: slotID> <item name: item> amount data components ``` |Parameter|Type|Required|Other| |:---|:---|:---|:---| |`replaceitem`|keyword|true|| |`block`|keyword|true|| |`position x`|coordinate|true|| |`position y`|coordinate|true|| |`position z`|coordinate|true|| |`slot.container`|keyword|true|| |`slot id`|slotID|true|| |`item name`|item|true|| |`amount`|keyword|false|| |`data`|keyword|false|| |`components`|keyword|false|| ## replaceitem - Nr: 1 Replaces items in inventories. ```mcfunction replaceitem block <position x: coordinate> <position y: coordinate> <position z: coordinate> slot.container <slotId: slotID> <replacemode: replaceMode> <item name: item> amount data components ``` |Parameter|Type|Required|Other| |:---|:---|:---|:---| |`replaceitem`|keyword|true|| |`block`|keyword|true|| |`position x`|coordinate|true|| |`position y`|coordinate|true|| |`position z`|coordinate|true|| |`slot.container`|keyword|true|| |`slotId`|slotID|true|| |`replacemode`|replaceMode|true|| |`item name`|item|true|| |`amount`|keyword|false|| |`data`|keyword|false|| |`components`|keyword|false|| ## replaceitem - Nr: 2 Replaces items in inventories. ```mcfunction replaceitem entity <selector: selector> <slot.container: slotType> <slotId: slotID> <item name: item> [amount: integer] [data: integer] [components: jsonItem] ``` |Parameter|Type|Required|Other| |:---|:---|:---|:---| |`replaceitem`|keyword|true|| |`entity`|keyword|true|| |`selector`|selector|true|| |`slot.container`|slotType|true|| |`slotId`|slotID|true|| |`item name`|item|true|| |`amount`|integer|false|| |`data`|integer|false|| |`components`|jsonItem|false|| ## replaceitem - Nr: 3 Replaces items in inventories. ```mcfunction replaceitem entity <selector: selector> <slot type: slotType> <slot id: slotID> <replace mode: replaceMode> <item name: item> [amount: integer] [data: integer] [components: jsonItem] ``` |Parameter|Type|Required|Other| |:---|:---|:---|:---| |`replaceitem`|keyword|true|| |`entity`|keyword|true|| |`selector`|selector|true|| |`slot type`|slotType|true|| |`slot id`|slotID|true|| |`replace mode`|replaceMode|true|| |`item name`|item|true|| |`amount`|integer|false|| |`data`|integer|false|| |`components`|jsonItem|false||
import express, { Request, Response } from "express"; import { isPasswordSame, generateHash, generateToken } from "../utils/user"; import User from "../db/models/user"; import { Errors } from "../constants/errors"; import { auth } from "../middleware/auth"; import RequestModel from "../db/models/request"; const router = express.Router(); // create user with username and password router.post("/", async (req: Request, res: Response) => { try { const { username, password } = req.body; if (username && username.length < 3 || !password) { return res.status(400).send({ error: Errors.INVALID_REQUEST }) } const existingUser = await User.findOne({ username }); if (existingUser) { return res.status(403).send({ error: Errors.USER_EXISTS }) } const hashedPassword = await generateHash(password); const newUser = new User({ username, password: hashedPassword }); const user = await newUser.save(); return res.send({ data: user.toJSON(), error: "" }); } catch (err: any) { return res.status(400).send({ error: err.message }); } }) router.post("/login", async (req: Request, res: Response) => { try { const { username, password } = req.body; const user = await User.findOne({ username }); if (!user) { return res.status(400).send({ error: Errors.USER_NOT_FOUND }) } const isPasswordCorrect = await isPasswordSame(password, user.password); if (isPasswordCorrect) { return res.send({ error: "", data: generateToken(user.username) }) } return res.status(400).send({ error: Errors.INCORRECT_PASSWORD }) } catch (err: any) { return res.status(400).send({ error: err.message }); } }) router.get("/", auth, async (req: Request, res: Response) => { try { const { search, page = 1 } = req.query; const options = { page: typeof page === "string" ? parseInt(page) : 1, limit: 5 } if (!search) { return res.status(400).send({ error: Errors.SEARCH_PARAM_REQUIRED, }) } const regexpForStartingWithSearchKey = new RegExp("^" + search, 'i'); const users = await User.paginate({ username: { $ne: req.username, $regex: regexpForStartingWithSearchKey, } } , options); const usernames = users.docs.map((user) => user.username); const requestsForGivenUsers = await RequestModel.find({ from: req.username, to: { $in: usernames, } }); const userDocsAgain = users.docs.map((eachUser) => { const requestForCurrentUser = requestsForGivenUsers.find((request) => request.to === eachUser.username); return { ...eachUser.toJSON(), status: requestForCurrentUser?.status || null } }); return res.send({ error: "", data: { ...users, docs: userDocsAgain } }) } catch (err: any) { return res.status(400).send({ error: err.message }); } }) export default router;
<template> <div> <div class="min-h-screen flex flex-col bg-gray-100"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2 -mt-16"> <div class="bg-white px-6 py-8 rounded shadow-md text-black w-full"> <h1 class="mb-8 text-3xl text-center">Sign up</h1> <input type="text" class="block border border-grey-light w-full p-3 rounded mb-4" name="fullname" v-model="username" placeholder="Username" /> <input class="block border border-grey-light w-full p-3 rounded mb-4" type="email" v-model="email" name="email" placeholder="Email" /> <input type="password" class="block border border-grey-light w-full p-3 rounded mb-4" name="password" v-model="password" placeholder="Password" /> <div class="error" v-html="error"> </div> <button @click="register" type="submit" class="w-full text-center py-3 rounded bg-green-400 text-white hover:bg-green-500 focus:outline-none my-1" >Create Account</button> </div> <div class="text-grey-dark mt-6"> Already have an account? <router-link to="/login"><a class="no-underline border-b border-blue text-blue"> Log in </a></router-link>. </div> </div> </div> </div> </template> <script> import AuthService from '../services/AuthService' export default { mounted() { if (this.$store.state.isUserLoggedIn) { this.$router.push({ name: "welcome" }); } }, data() { return { username: '', password: '', email: '', error: null } }, methods: { async register() { try { const resp = await AuthService.register({ username: this.username, password: this.password, email: this.email }) this.$store.dispatch('setToken', resp.data.token) this.$store.dispatch('setUser', resp.data.user) console.log(resp) if (this.error) { this.error = null } this.$router.push({ name: "login" }); } catch (error) { this.error = error.resp.data.error } } } } </script> <style> .error { color: red; } </style>
/* * BaseDirectories+Utils.swift * swift-xdg * * Created by François Lamboley on 2023/01/13. */ import Foundation #if canImport(System) import System #else import SystemPackage #endif public extension BaseDirectories { func configFilePath(for path: FilePath) throws -> FilePath { return try configHomePrefixed.lexicallyResolving(path) } func dataFilePath(for path: FilePath) throws -> FilePath { return try dataHomePrefixed.lexicallyResolving(path) } func cacheFilePath(for path: FilePath) throws -> FilePath { return try cacheHomePrefixed.lexicallyResolving(path) } func stateFilePath(for path: FilePath) throws -> FilePath { return try stateHomePrefixed.lexicallyResolving(path) } /** Get the runtime file path. - Throws: If there was an error retrieving the runtime dir during the init of the `BaseDirectories` (checks for permissions and co are only done at init). */ func runtimeFilePath(for path: FilePath) throws -> FilePath { return try runtimeDirPrefixed.get().lexicallyResolving(path) } }
from django.db import models # Create your models here. class Products(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='productsImg/') category = models.CharField(max_length=50) description = models.TextField(max_length=500) rate = models.IntegerField(range(1,5)) price = models.IntegerField(default=0) def __str__(self): return self.name
// // Copyright (C) 2016 Broentech Solutions AS // Contact: https://broentech.no/#!/contact // // // GNU Lesser General Public License Usage // This file may be used under the terms of the GNU Lesser // General Public License version 3 as published by the Free Software // Foundation and appearing in the file LICENSE.LGPL3 included in the // packaging of this file. Please review the following information to // ensure the GNU Lesser General Public License version 3 requirements // will be met: https://www.gnu.org/licenses/lgpl-3.0.html. // // // // \file polygonSelection.h // // \brief Definition of a class that defines a polygon selection // // \author Stian Broen // // \date 08.12.2011 // // \par Copyright: // // Stian Broen // // \par Revision History // // \par 01 08.12.2011 Original version // // // // #ifndef POLYGON_SELECTION_HEADERFILE #define POLYGON_SELECTION_HEADERFILE // Qt includes #include <QObject> #include <QPolygon> #include <QHash> #include <QRect> #include <QPen> // solution includes #include <common/definitions.h> // local includes #include "selectionBase.h" // Qt forward declarations class QPixmap; class QPaintDevice; namespace sdraw { class CPolygonSelection : public CSelectionBase { Q_OBJECT public: explicit CPolygonSelection(const QPolygon &polygon, const QPixmap *_content = 0); ~CPolygonSelection(); TPolygonDragArea getAreaAtPoint(const QPoint &pt); void updateContent(const QPixmap *newContent, const QRect *newContentRect = 0); void storeThisPixmap(const QPixmap *worldPixmap, bool enforce = false); void drawContentToWorld(QPaintDevice *targetPixmap); void drawSelectionToWorld(QPaintDevice *targetPixmap); void dragSelection(int dx, int dy); void makeWorldShadow(const QPixmap *worldPixmap); void collapseContents(); bool setMoving(bool onOrOff); void toggle(); inline QPolygon getWorldPolygon(){ return m_world_polygon; } inline QPolygon getLocalPolygon(){ return m_local_polygon; } void changePen(const QPen *pen, bool redrawContent = false); QPen getCurrentPen(); void moveDragBox(int dx, int dy, const QPixmap *worldPixmap); void setDragboxIndex(int index); void clearContent(); void drawIntersectionContent(const QPixmap *outsideContent, const QRect &world_outsideContentRect, const QRect &local_outsideContentRect, QPolygon &interpoly); signals: void printSig(QRect &target, const QPixmap &content, QRect &source, const QString &text); private: void makeWorldGeo(const QPolygon &polygon); void makeLocalGeo(const QPolygon &polygon); QPolygon translateToLocal(const QPolygon &polygon); void defineDragboxes(); void drawSelection(const QPen *pen = 0, bool keepPen = false); void drawContent(const QPixmap *source); private: QRect worldSelectionRect; QRect worldContentRect; QRect localSelectionRect; QRect localContentRect; QPolygon m_world_polygon; QPolygon m_local_polygon; QPen m_pen; TPolygonDragArea currentClickArea; QHash<int, QRect > world_polygonDragBoxes; QHash<int, QRect > local_polygonDragBoxes; int activeDragboxIndex; }; } #endif
import {it, expect} from "vitest"; import {add} from "./math"; it("should summarize all number values in an array", () => { //Arrange const numbers = [1,2,3]; //Act const result = add(numbers); //Assert const expectedResult = numbers.reduce((sum, currentValue)=>{ return sum+=currentValue; },0) expect(result).toBe(expectedResult); }); it('should yield NaN if at least one invalid number is provided', ()=>{ const inputs = ['invalid', 1]; const result = add(inputs); expect(result).toBeNaN(); }) it('should yield a correct sum if an array of numeric values is provided', ()=>{ const numbers = ['1', '2']; const result = add(numbers); const expectedResult = numbers.reduce((sum, currentValue)=> +sum + +currentValue,0) expect(result).toBe(expectedResult); }) it('should yeild 0 if an empty array is provided', ()=>{ const numbers = []; const result = add(numbers); expect(result).toBe(0); }) it('should throw an error if no value is passed into the function', ()=>{ const resultFn = ()=>{ add(); }; expect(resultFn).toThrow(/is not iterable/); }) it('should throw an error if provided with multiple arguments instead of an array', ()=>{ const num1 = 1; const num2 = 2; const resultFn = ()=>{ add(num1, num2); }; expect(resultFn).toThrow(/is not iterable/); })
<!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> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="index.css"> </head> <body> <nav class="navbar navbar-expand-lg"> <div class="container"> <a href="#" class="navbar-brand"><img src="img/Logo.png"></a> <button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#NavbarIcon"><img src="img/icon.png"></button> <div class="collapse navbar-collapse" id="NavbarIcon"> <ul class="navbar-nav ms-auto"> <li class="nav-item"><a href="#" class="nav-link">Used Cars</a></li> <li class="nav-item"><a href="#" class="nav-link">Auctions</a></li> <li class="nav-item"><a href="#" class="nav-link">New Cars</a></li> <li class="nav-item"><a href="#" class="nav-link">Sell Cars</a></li> <li class="nav-item"><a href="#" class="nav-link">Local Dealers</a></li> <li class="nav-item"><a href="#" class="nav-link">Support</a></li> <li class="nav-item"><a href="#" class="nav-link SignUp"><img src="img/person-fill.svg"> Sign Up</a></li> </ul> </div> </div> </nav> <section class="section1"> <div class="container"> <h1>Say hello to your next <br> awesome vehicle</h1> <br> <p>Featuring Used, Wholesale and Salvage Cars, Trucks <br> & SUVs for Sale</p> <div class="TopFooterSection"> <div class="row"> <div class="col-md-2 borderRight"> <p>Type</p> <select class="form-select"> <option selected>Used Card</option> <option value="1">1 card</option> <option value="2">2 card</option> <option value="3">3 card</option> </select> </div> <div class="col-md-2 borderRight"> <p>Make</p> <select class="form-select"> <option selected>Infiniti</option> <option value="1">1 card</option> <option value="2">2 card</option> <option value="3">3 card</option> </select> </div> <div class="col-md-2 withoutP borderRight"> <p class="someMargin"></p> <select class="form-select"> <option selected>Year</option> <option value="1">1 card</option> <option value="2">2 card</option> <option value="3">3 card</option> </select> </div> <div class="col-md-2 withoutP borderRight"> <p class="someMargin"></p> <select class="form-select"> <option selected>Model</option> <option value="1">1 card</option> <option value="2">2 card</option> <option value="3">3 card</option> </select> </div> <div class="col-md-2 withoutP"> <p></p> <select class="form-select"> <option selected>Price</option> <option value="1">1 card</option> <option value="2">2 card</option> <option value="3">3 card</option> </select> </div> <div class="col-md-2 withoutP"> <button class="btn searchBtn"><img src="img/search.svg"> Search</button> </div> </div> </div> </div> </div> </section> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script> </body> </html>
<?php namespace App\Entity; use App\Repository\CategoriesRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * @ORM\Entity(repositoryClass=CategoriesRepository::class) */ class Categories { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @Gedmo\Slug(fields={"name"}) * @ORM\Column(type="string", length=255) */ private $slug; /** * @ORM\Column(type="string", length=100) */ private $name; /** * @ORM\OneToMany(targetEntity=Products::class, mappedBy="categories") */ private $products; public function __construct() { $this->products = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getSlug(): ?string { return $this->slug; } public function setSlug(string $slug): self { $this->slug = $slug; return $this; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } /** * @return Collection|Products[] */ public function getProducts(): Collection { return $this->products; } public function addProduct(Products $product): self { if (!$this->products->contains($product)) { $this->products[] = $product; $product->setCategories($this); } return $this; } public function removeProduct(Products $product): self { if ($this->products->contains($product)) { $this->products->removeElement($product); // set the owning side to null (unless already changed) if ($product->getCategories() === $this) { $product->setCategories(null); } } return $this; } public function __toString() { return $this->name; } }
import { motion } from "framer-motion"; import { useNavigate, useParams } from "react-router-dom"; import styled from "styled-components"; import { getSingleSubject, getSubjectQuestionsLen, } from "../../services/dataApi"; import Button from "../../ui/Button"; import Heading from "../../ui/Heading"; import Modal from "../../ui/Modal"; import Row from "../../ui/Row"; import QuizIntermediate from "./QuizIntermediate"; const StyledQuizInitial = styled(motion.div)` display: flex; flex-direction: column; align-items: center; justify-items: center; gap: 1.3rem; & p { text-align: center; &:has(span) { span { font-weight: bold; } } } `; const StyledHeading = styled(Heading)` font-size: 4rem; letter-spacing: 1.2px; background: var(--bg-brand); background-clip: text; -webkit-background-clip: text; color: transparent; background-size: cover; background-position: center; `; const StyledIcon = styled.div` padding: 2rem; border-radius: 100%; height: 10rem; width: 10rem; display: flex; justify-content: center; align-items: center; background-color: var(--color-grey-800); box-shadow: var(--shadow-md); `; const StyledHeader = styled.div` display: flex; align-items: center; justify-content: center; gap: 1.7rem; `; const TimeCard = styled.div` padding: 2rem; box-shadow: var(--shadow-md); display: flex; flex-direction: column; align-items: flex-start; gap: 1rem; `; function QuizInitial() { const navigate = useNavigate(); const { subject } = useParams(); const questionLen = getSubjectQuestionsLen(subject!); const { title, icon } = getSingleSubject(subject!); return ( <StyledQuizInitial layout="position" layoutId="quiz"> <StyledHeader> <StyledIcon> <img src={icon} alt={subject} /> </StyledIcon> <StyledHeading>{title?.toUpperCase()} QUIZ</StyledHeading> </StyledHeader> <p>Do you you want to continue with the quiz</p> <p> <span>Note</span> , once the quiz begins you wont be able to change.{" "} <br /> A question can only be attempted once.{" "} </p> <TimeCard> <p> Number of questions <span>{questionLen}</span> </p> <p> Alloted time for quiz <span>{questionLen * 2}min</span>{" "} </p> </TimeCard> <Row type="horizontal"> <Button variation="secondary" onClick={() => { navigate("/"); }} > Back{" "} </Button> <Modal> <Modal.Open opens="intermediate"> <Button>Start Quiz </Button> </Modal.Open> <Modal.Window name="intermediate"> <QuizIntermediate /> </Modal.Window> </Modal> </Row> </StyledQuizInitial> ); } export default QuizInitial;
import React from "react"; import { Text } from "react-native"; import { Table, Col, Row } from "."; import { useBirthHistory, useMedicalHistory, useNutritionalHistory, useVaccinationHistory, } from "../store"; import { styles } from "../style"; import { FitTextToCell } from "./FixTextToCell"; import { Input } from "./Input"; import { SimpleQuestion } from "./Question"; export function AdditionalPatientInformation() { const { updateBirthHistory, ...birthHistory } = useBirthHistory( (state) => state ); const { updateNutritionalHistory, ...nutritionHistory } = useNutritionalHistory((state) => state); const { updateVaccinationHistory, ...vaccinationHistory } = useVaccinationHistory((state) => state); const { updateMedicalHistory, ...medicalHistory } = useMedicalHistory( (state) => state ); return ( <Table headerTitle="Additional Patient Information:"> <Col style={styles.headerDarkGray}> <Text>Birth History</Text> </Col> <Row> <Col style={styles.headerLightGray}> <Text>Gestation</Text> </Col> <Col cols={3}> <SimpleQuestion options={["full term", "pre-term", "post term"]} checked={birthHistory.gestation} setChecked={(text: string | string[]) => { updateBirthHistory({ gestation: text as string }); }} /> </Col> <Col style={styles.headerLightGray}> <Text>Mother’s age at delivery:</Text> </Col> <Col cols={2}> <FitTextToCell> <Input text={birthHistory.mothersAgeAtDelivery} setText={(text: string) => { updateBirthHistory({ mothersAgeAtDelivery: text, }); }} /> </FitTextToCell> </Col> </Row> <Row> <Col style={styles.headerLightGray}> <Text>Complications after delivery</Text> </Col> <Col cols={2}> <SimpleQuestion options={["yes", "no"]} checked={birthHistory.complicationsAfterDelivery} setChecked={(text: string | string[]) => { updateBirthHistory({ complicationsAfterDelivery: text as string, }); }} /> </Col> <Col cols={2} style={styles.headerLightGray}> <Text>(If Yes) Apgar Score:</Text> </Col> <Col cols={2}> <FitTextToCell> <Input text={birthHistory.apgarScore} setText={(text: string | string[]) => { updateBirthHistory({ apgarScore: text as string, }); }} /> </FitTextToCell> </Col> </Row> <Row> <Col cols={2} style={styles.headerLightGray}> <Text>Additional birth history notes:</Text> </Col> <Col cols={4}> <FitTextToCell> <Input text={birthHistory.additionalBirthHistoryNotes} setText={(text: string) => { updateBirthHistory({ additionalBirthHistoryNotes: text, }); }} /> </FitTextToCell> </Col> </Row> <Col style={styles.headerDarkGray}> <Text>Nutritional History</Text> </Col> <Row> <Col style={styles.headerLightGray}> <Text>Was the child breast fed?</Text> </Col> <Col> <SimpleQuestion options={["yes", "no"]} checked={nutritionHistory.breastfed} setChecked={(text: string | string[]) => { updateNutritionalHistory({ breastfed: text as string, }); }} /> </Col> <Col style={styles.headerLightGray}> <Text>(If yes) Was it exclusive?</Text> </Col> <Col> <SimpleQuestion options={["yes", "no"]} checked={nutritionHistory.wasBreastFeedingExclusive} setChecked={(text: string | string[]) => { updateNutritionalHistory({ wasBreastFeedingExclusive: text as string, }); }} /> </Col> </Row> <Row> <Col style={styles.headerLightGray}> <Text>(If yes) When did the breastfeeding start?</Text> </Col> <Col cols={2}> <SimpleQuestion options={["At Birth", "After Birth"]} checked={nutritionHistory.breastFeedingStartTime} setChecked={(text: string | string[]) => { updateNutritionalHistory({ breastFeedingStartTime: text as string, }); }} /> <Text> If after birth, breastfeeding started after how many days?{" "} </Text> <Input text={nutritionHistory.breastFeedingStartTimeDays} label="Days" setText={(text: string) => { updateNutritionalHistory({ breastFeedingStartTimeDays: text, }); }} /> </Col> </Row> <Row> <Col style={styles.headerLightGray}> <Text>(If yes) When did the breastfeeding start?</Text> </Col> <Col> <FitTextToCell> <Input text={nutritionHistory.breastFeedingStartTimeMonths} label="Months" setText={(text: string) => { updateNutritionalHistory({ breastFeedingStartTimeMonths: text, }); }} /> </FitTextToCell> </Col> <Col style={styles.headerLightGray}> <Text>Was the child on vitamin A supplements?</Text> </Col> <Col> <SimpleQuestion options={["yes", "no"]} checked={nutritionHistory.vitaminASupplements} setChecked={(text: string | string[]) => { updateNutritionalHistory({ vitaminASupplements: text as string, }); }} /> </Col> </Row> <Col style={styles.headerDarkGray}> <Text>Vaccination History</Text> </Col> <Row> <Col style={styles.headerLightGray}> <Text>Is the child up to date on all vaccines?</Text> </Col> <Col> <SimpleQuestion options={["yes", "no"]} checked={vaccinationHistory.updateOnAllVaccines} setChecked={(text: string | string[]) => { updateVaccinationHistory({ updateOnAllVaccines: text as string, }); }} /> </Col> <Col style={styles.headerLightGray}> <Text> If no, please note below which ones they are missing: </Text> </Col> </Row> <Col> <FitTextToCell> <Input text={vaccinationHistory.missingNotes} setText={(text: string) => { updateVaccinationHistory({ missingNotes: text }); }} /> </FitTextToCell> </Col> <Col style={styles.headerDarkGray}> <Text>Previous Medical History</Text> </Col> <Row> <Col> <SimpleQuestion label="Any previous admission ?" options={["yes", "no"]} checked={medicalHistory.previousAdmission} setChecked={(text: string | string[]) => { updateMedicalHistory({ previousAdmission: text as string, }); }} /> </Col> <Col> <FitTextToCell> <Input placeholder="If yes, why?" text={medicalHistory.whyPreviousAdmission} setText={(text: string) => { updateMedicalHistory({ whyPreviousAdmission: text, }); }} /> </FitTextToCell> </Col> <Col> <SimpleQuestion label="History of antibiotic use?" options={["yes", "no"]} checked={medicalHistory.antibioticUse} setChecked={(text: string | string[]) => { updateMedicalHistory({ antibioticUse: text as string, }); }} /> </Col> </Row> </Table> ); }
const bcrypt = require('bcryptjs') const usersRouter = require('express').Router() const User = require('../models/user') usersRouter.get('/', async (request, response) =>{ const users = await User.find({}) .populate('blogs', {title:1, author:1, url:1, likes:1}) response.status(200).json(users.map(user => user.toJSON())) }) usersRouter.get('/:id', async (request, response) => { const user = await User.findById(request.params.id) if(user) { response.status(200).json(user.toJSON()) } else { response.status(404).end() } }) usersRouter.post('/', async (request, response) => { const {body} = request if(!body.username || !body.password) { return response.status(400).json({ error: "password or username is missing" }) } if(body.username.length < 3) { return response.status(400).json({ error: "username must be 3 characters or longer" }) } if(body.password.length < 3) { return response.status(400).json({ error: "password must be 3 characters or longer" }) } const saltRounds = 10 const passwordHash = await bcrypt.hash(body.password, saltRounds) const user = new User({ username: body.username || "Default user", name: body.name, passwordHash }) const savedUser = await user.save() response.status(201).json(savedUser) }) module.exports = usersRouter
import express, { Express, Request, Response } from "express"; import { ErrorHandler } from "./http/middlewares/ErrorHandler"; import bodyParser from "body-parser"; import cors from "cors"; import blogRoute from "./routes/blogPost" import sectionRoute from "./routes/section" import tagRoute from "./routes/tag"; import userRoute from "./routes/users"; import authRoute from "./routes/auth"; import commentRouter from "./routes/comment"; import contentRouter from "./routes/content"; import categoryRouter from "./routes/category"; import fileRoute from "./routes/file" import pageRoute from "./routes/page"; import socialAccountRoute from "./routes/socialAccount"; import swaggerUi from 'swagger-ui-express'; import swaggerSpec from '../swagger'; import path from "path" import menuRoute from "./routes/menu"; import { refreshTokenMiddleware } from "./http/middlewares/RefreshTokenMiddleware"; const app: Express = express() app.use(cors()) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use("/uploads", express.static(path.join(__dirname, "../public/uploads"))) // Sử dụng middleware làm mới token cho tất cả các route cần làm mới token app.use(refreshTokenMiddleware) app.use("/socialAccount", socialAccountRoute); app.use("/posts", blogRoute) app.use("/section", sectionRoute) app.use("/tags", tagRoute); app.use("/user", userRoute); app.use("/auth", authRoute); app.use("/category", categoryRouter); app.use("/comment", commentRouter); app.use("/content", contentRouter); app.use("/file", fileRoute) app.use("/page", pageRoute) // app.get("/images/:type/:id", imageController.get); app.use("/menu", menuRoute) app.get('/check', (req, res) => { res.status(200).send('Server is healthy!'); }); // Serve Swagger UI app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.use("*", (req: Request, res: Response) => { return res.status(404).json({ success: false, message: "Invalid route", }) }) app.use(ErrorHandler.handleErrors) export default app
--- description: Caixa de entrada do agente - Documentação do Marketo - Documentação do produto title: Caixa de entrada do agente feature: Dynamic Chat exl-id: 656f8716-d982-4c02-8311-17add0fcd924 source-git-commit: 38274b4859ae38c018ee73d4f1715fdf6a78e815 workflow-type: tm+mt source-wordcount: '367' ht-degree: 2% --- # Caixa de entrada do agente {#agent-inbox} Os agentes colocarão bate-papos em tempo real dentro da Caixa de entrada do agente. Além das conversas ativas, eles podem ver conversas passadas, informações de visitantes e muito mais. ![](assets/agent-inbox-1.png) ## Alternância de disponibilidade {#availability-toggle} No lado superior direito da tela Caixa de entrada do agente, você tem a opção de definir seu status como disponível ou indisponível. ![](assets/agent-inbox-2.png) >[!IMPORTANT] > >**Isso substituirá** o [disponibilidade do chat ao vivo](/help/marketo/product-docs/demand-generation/dynamic-chat/setup-and-configuration/agent-settings.md#live-chat-availability){target="_blank"} estabelecido em Configurações do agente. O status permanecerá até que você o alterne de volta ou para o próximo bloco de tempo em sua disponibilidade. >[!NOTE] > >Configurar seu status como indisponível não afetará nenhum bate-papo ativo. ## Notificações de bate-papo ao vivo {#live-chat-notifications} Quando um chat ao vivo for roteado para um agente, ele verá um banner azul na parte superior da tela pedindo que ele aceite. ![](assets/agent-inbox-3.png) >[!TIP] > >Você também tem a opção de configurar notificações do navegador, que o alertará caso não esteja conectado ao Dynamic Chat. > >* Ativar notificações do navegador no [Google Chrome](https://support.google.com/chrome/answer/3220216?hl=en&amp;co=GENIE.Platform%3DDesktop){target="_blank"} >* Ativar notificações do navegador no [Mozilla Firefox](https://support.mozilla.org/en-US/kb/push-notifications-firefox){target="_blank"} ### Itens a Observar {#things-to-note} * Os agentes têm 45 segundos para responder antes que a mensagem &quot;Accept chat&quot; expire. * No momento, há um limite de 10 bate-papos ao vivo por agente ## Conversas {#conversations} No lado esquerdo da tela da Caixa de entrada do agente, você pode optar por exibir somente as conversas ativas, ou todas elas. ![](assets/agent-inbox-4.png) >[!NOTE] > >Embora você possa ver conversas passadas (inativas) de você mesmo e de outros agentes, você só poderá ver suas próprias conversas ativas. ## Informações sobre os visitantes {#visitor-information} No lado direito da tela da Caixa de entrada do agente, você poderá ver (de cima para baixo) o nome, o cargo, o endereço de email, o número de telefone e o status do CRM. Qualquer informação não transmitida será exibida como um traço (-). ![](assets/agent-inbox-5.png) ## Histórico de atividades {#activity-history} Abaixo das informações do visitante está o histórico de atividades. Visualize tipos de atividades e datas, e até mesmo visualize transcrições do chat. ![](assets/agent-inbox-6.png) >[!NOTE] > >As informações são exibidas somente para os últimos 90 dias. ## Compartilhamento de calendário {#calendar-sharing} Na parte inferior da janela de bate-papo ao vivo há um ícone que permite compartilhar o calendário do ou de outro agente com o visitante do bate-papo. 1. Clique no ícone do calendário. ![](assets/agent-inbox-7.png) 1. Escolha o calendário do agente desejado e clique em **Enviar**. ![](assets/agent-inbox-8.png) 1. O visitante do chat poderá agendar uma reunião. ![](assets/agent-inbox-9.png)
import style from "../styles/login.module.css"; import completedIcon from "../images/icon-complete.svg"; import { useState } from "react"; const Login = () => { const [nameError, setNError] = useState(false); const [cNumBlankError, setNumBlankError] = useState(false); const [cNumFormatError, setNumFormatError] = useState(false); const [dateError, setDateError] = useState(false); const [cvcError, setCvcError] = useState(false); const [completed, setCompleted] = useState(false); const handleSubmit = (event) => { event.preventDefault(); setNError(false); setNumBlankError(false); setNumFormatError(false); setDateError(false); setCvcError(false); let name = document.getElementById("holderName").value; let cardNum = document.getElementById("cardNum").value; let date = document.getElementById("dateMonth").value; let dateYear = document.getElementById("dateYear").value; let cvc = document.getElementById("cvc").value; if (name == "") { setNError(true); } else if (cardNum == "") { setNumBlankError(true); } else if (isNaN(cardNum)) { setNumFormatError(true); } else if (date == "" || dateYear == "") { setDateError(true); } else if (cvc == "") { setCvcError(true); } else { setCompleted(true); } }; if (completed) { return ( <> <div className={style.login} id={style.completed} style={{ textAlign: "center" }} > <div> <img style={{ position: "relative", bottom: "20px" }} src={completedIcon} alt="" /> </div> <div style={{ fontSize: "2em", textTransform: "uppercase" }}> Thank You !!! </div> <div style={{ marginTop: "10px" }}>We've added your card details</div> <button>Continue</button> </div> </> ); } else { return ( <> <form className={style.login} onSubmit={handleSubmit}> <section> <label htmlFor="holderName">cardholder name </label> <br /> <input type="text" id="holderName" name="holderName" placeholder="e.g. Jane Appleseed" /> {nameError == true ? ( <> <br /> <strong className={style.error}>Can't be blank</strong> </> ) : ( <></> )} </section> <section> <label htmlFor="cardNum">card number</label> <br /> <input type="tel" name="cardNum" id="cardNum" placeholder="e.g. 1234 5678 9123 0000" /> {cNumBlankError == true ? ( <> <br /> <strong className={style.error}>Can't be blank</strong> </> ) : ( <></> )} {cNumFormatError == true ? ( <> <br /> <strong className={style.error}> Wrong format, numbers only </strong> </> ) : ( <></> )} </section> <section style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}> <div> <label htmlFor="date">Exp. date (mm/yy)</label> <br /> <input style={{ width: "30%" }} type="number" id="dateMonth" name="date" placeholder="MM" /> <input style={{ width: "30%" }} type="number" id="dateYear" name="date" placeholder="YY" /> {dateError == true ? ( <> <br /> <strong className={style.error}>Can't be blank</strong> </> ) : ( <></> )} </div> <div> <label htmlFor="CVC">cvc</label> <br /> <input type="number" name="CVC" id="cvc" placeholder="e.g. 123" /> {cvcError == true ? ( <> <br /> <strong className={style.error}>Can't be blank</strong> </> ) : ( <></> )} </div> </section> <button type="submit">Confirm</button> </form> </> ); } }; export default Login;
const Jison = require('../setup').Jison const Lexer = require('../setup').Lexer const assert = require('assert') const lexData = { rules: [ ['x', "return 'x';"], ['y', "return 'y';"] ] } exports['test left-recursive nullable grammar'] = function () { const grammar = { tokens: ['x'], startSymbol: 'A', bnf: { A: ['A x', ''] } } const gen = new Jison.Generator(grammar, { type: 'slr' }) const parser = gen.createParser() parser.lexer = new Lexer(lexData) assert.ok(parser.parse('xxx'), "parse 3 x's") assert.ok(parser.parse('x'), 'parse single x') assert.throws(function () { parser.parse('y') }, 'throws parse error on invalid token') assert.ok(gen.conflicts == 0, 'no conflicts') } exports['test right-recursive nullable grammar'] = function () { const grammar = { tokens: ['x'], startSymbol: 'A', bnf: { A: ['x A', ''] } } const skipRightRecursiveTest = true if (skipRightRecursiveTest) { console.log('Skipping test right-recursive nullable grammar') return } const gen = new Jison.Generator(grammar, { type: 'slr' }) const parser = gen.createParser() parser.lexer = new Lexer(lexData) assert.ok(parser.parse('xxx'), "parse 3 x's") assert.ok(gen.table.length == 4, 'table has 4 states') assert.ok(gen.conflicts == 0, 'no conflicts') assert.equal(gen.nullable('A'), true, 'A is nullable') }
package ru.yandex.autotests.metrika.appmetrica.tests.ft.management.segment; import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import ru.yandex.autotests.metrika.appmetrica.data.User; import ru.yandex.autotests.metrika.appmetrica.data.Users; import ru.yandex.autotests.metrika.appmetrica.steps.UserSteps; import ru.yandex.autotests.metrika.appmetrica.tests.Requirements; import ru.yandex.autotests.metrika.appmetrica.wrappers.GrantWrapper; import ru.yandex.metrika.api.management.client.external.GrantType; import ru.yandex.metrika.mobmet.dao.MobSegment; import ru.yandex.metrika.mobmet.management.Application; import ru.yandex.metrika.mobmet.model.MobmetGrantE; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; import ru.yandex.qatools.allure.annotations.Title; import java.util.Collection; import java.util.Collections; import java.util.List; import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat; import static ru.yandex.autotests.metrika.appmetrica.data.Users.SIMPLE_USER; import static ru.yandex.autotests.metrika.appmetrica.data.Users.SIMPLE_USER_2; import static ru.yandex.autotests.metrika.appmetrica.matchers.ResponseMatchers.equivalentTo; import static ru.yandex.autotests.metrika.appmetrica.tests.ft.management.TestData.GrantCreator.forUser; import static ru.yandex.autotests.metrika.appmetrica.tests.ft.management.TestData.defaultSegment; import static ru.yandex.autotests.metrika.appmetrica.tests.ft.management.TestData.getDefaultApplication; @Features(Requirements.Feature.Management.SEGMENT) @Stories({ Requirements.Story.Segments.ADD, Requirements.Story.Segments.LIST, }) @Title("Просмотр сегментов") @RunWith(Parameterized.class) public class GetSegmentTest { private static final User OWNER = Users.SIMPLE_USER; private final UserSteps ownerSteps = UserSteps.onTesting(OWNER); @Parameterized.Parameter public User segmentCreator; @Parameterized.Parameter(1) public User segmentViewer; @Parameterized.Parameter(2) public GrantWrapper grant; private UserSteps segmentViewerSteps; private MobSegment expectedSegment; private Long appId; private Long segmentId; @Parameterized.Parameters(name = "Создатель {0}. Пользователь {1}. {2}") public static Collection<Object[]> createParameters() { return ImmutableList.of( param(SIMPLE_USER, SIMPLE_USER, null), param(SIMPLE_USER_2, SIMPLE_USER, forUser(SIMPLE_USER_2).grant(GrantType.EDIT)), param(SIMPLE_USER, SIMPLE_USER_2, forUser(SIMPLE_USER_2).grant(GrantType.EDIT)) ); } @Before public void setup() { UserSteps segmentCreatorSteps = UserSteps.onTesting(segmentCreator); segmentViewerSteps = UserSteps.onTesting(segmentViewer); final MobSegment segmentToAdd = defaultSegment(); expectedSegment = segmentToAdd; final Application addedApplication = ownerSteps.onApplicationSteps().addApplication(getDefaultApplication()); appId = addedApplication.getId(); if (grant.getGrant() != null) { ownerSteps.onGrantSteps().createGrant(appId, grant); } segmentId = segmentCreatorSteps.onSegmentSteps().addSegment(appId, segmentToAdd).getSegmentId(); } @Test public void getSegment() { final MobSegment actualSegment = segmentViewerSteps.onSegmentSteps().getSegment(appId, segmentId); assertThat("добавленный сегмент эквивалентен ожидаемому", actualSegment, equivalentTo(expectedSegment)); } @Test public void getSegmentList() { final List<MobSegment> segments = segmentViewerSteps.onSegmentSteps().getSegmentsList(appId); assertThat("список сегментов содержит только добавленный сегмент", segments, equivalentTo(Collections.singletonList(expectedSegment))); } @After public void teardown() { ownerSteps.onSegmentSteps().deleteSegmentAndIgnoreResult(appId, segmentId); if (grant.getGrant() != null) { ownerSteps.onGrantSteps().deleteGrant(appId, grant.getGrant().getUserLogin()); } ownerSteps.onApplicationSteps().deleteApplicationAndIgnoreResult(appId); } public static Object[] param(User segmentCreator, User segmentViewer, MobmetGrantE grant) { return new Object[]{segmentCreator, segmentViewer, new GrantWrapper(grant)}; } }
import { eventBusService } from "../../../services/event-bus.service.js" import { MailCompose } from "../cmps/mail-compose.jsx" import { MailFolderList } from "../cmps/mail-folder-list.jsx" import { MailList } from "../cmps/mail-list.jsx" import { mailService } from "../services/mail.service.js" import { MailDetail } from "./mail-detail.jsx" const { Route } = ReactRouterDOM export class MailApp extends React.Component { state = { mails: [], criteria: "", compose: false, menu:false } componentDidMount() { this.removeEvent = eventBusService.on('send-search', (criteria) => { this.setState((prevState) => ({ ...prevState, criteria }), () => this.loadMails()) }) this.loadMails() } loadMails = () => { mailService.query(this.state.criteria) .then(mails => this.setState({ mails }, () => this.getFoldersLen())) } onMailClicked = (ev, id, field) => { ev.stopPropagation() mailService.onSetToggle(id, field) if (field === 'isRead') this.props.history.push(`/mail/?id=${id}`) if (field === 'isTrash') this.loadMails() if (field === 'isStarred') this.getFoldersLen() } onSendMail = (sendParams) => { mailService.sendMail(sendParams) this.loadMails() this.toggleCompose(false) } toggleCompose = (compose) => { this.setState({ compose, menu:false }) } clearCriteria = () => { this.setState((prevState) => ({ ...prevState, criteria: '',menu:false }), () => this.loadMails()) } get statusToFilter() { const { mails } = this.state const urlSrcPrm = new URLSearchParams(this.props.location.search) const status = urlSrcPrm.get('status') return mails.filter(mail => { return status === 'inbox' && mail.to === '[email protected]' && !mail.isTrash || status === 'sent' && mail.to !== '[email protected]' && !mail.isTrash || status === 'starred' && mail.isStarred && !mail.isTrash || status === 'trash' && mail.isTrash }) } getFoldersLen = () => { const { mails } = this.state if (!mails.length) return const length = {} const folders = ['inbox', 'sent', 'starred', 'trash'] folders.map(folder => length[folder] = mails.filter(mail => { return folder === 'inbox' && mail.to === '[email protected]' && !mail.isTrash || folder === 'sent' && mail.to !== '[email protected]' && !mail.isTrash || folder === 'starred' && mail.isStarred && !mail.isTrash || folder === 'trash' && mail.isTrash }).length) this.setState((prevState) => ({ ...prevState, length })) } toggleMenu = () => { this.setState((prevState) => ({menu:!prevState.menu})) } render() { const { mails, compose , menu } = this.state const { pathname, search } = this.props.location return <section className="mail-app flex"> <label className="toggle-menu-button" onClick={this.toggleMenu}>☰</label> <input id="chk" type="checkbox" checked={this.state.menu} /> <section className={`interface ${menu && 'slide-right'}`}> <button onClick={() => this.toggleCompose(true)}>Compose</button> <MailFolderList clearCriteria={this.clearCriteria} length={this.state.length} /> <label className={`dark-label ${menu && 'fade-in'}`} onClick={this.toggleMenu}></label> </section> <section className="main-mail"> {!mails.length && <h2 className="search-results">No Results</h2>} <MailList mails={this.statusToFilter} onMailClicked={this.onMailClicked} /> {this.props.location.pathname.includes('/mail/') && <MailDetail />} {compose && <MailCompose onSendMail={this.onSendMail} toggleCompose={this.toggleCompose} />} </section> </section> } }
<?php // Function to update data in the database function updateInDatabase($ID, $Name, $Age, $City) { // Create connection $conn = mysqli_connect('localhost', 'root', '', 'test') or die('Cannot connect to MySQL server'); // Connecting to the database // Prepare SQL statement $stmt = $conn->prepare("UPDATE students SET name=?, age=?, city=? WHERE id=?"); $stmt->bind_param("sisi", $Name, $Age, $City, $ID); // Execute SQL statement if ($stmt->execute() === TRUE) { echo "<h3>Data Updated Successfully in Database</h3>"; } else { echo "<h3>Data Update Failed in Database</h3>"; } // Close connection $stmt->close(); $conn->close(); } // Function to update data in the JSON file function updateInJson($ID, $Name, $Age, $City) { $jsonFile = 'json_data/Student_json_data.json'; // Read the existing JSON data from the file $jsonData = file_get_contents($jsonFile); // Decode the JSON data to an associative array $data = json_decode($jsonData, true); // Loop through the data to find the user with the matching ID foreach ($data as &$person) { if ($person['ID'] == $ID) { // Update the user's data with the new data $person['Name'] = $Name; $person['Age'] = $Age; $person['City'] = $City; break; } } // Encode the updated data back to JSON format $updatedJsonData = json_encode($data, JSON_PRETTY_PRINT); // Write the updated JSON data back to the file if (file_put_contents($jsonFile, $updatedJsonData)) { echo "<h3>Data Updated Successfully in JSON</h3>"; } else { echo "<h3>Data Update Failed in JSON</h3>"; } } // Check if all form fields are submitted if (isset($_POST['ID']) && isset($_POST['Name']) && isset($_POST['Age']) && isset($_POST['City'])) { // Update in database updateInDatabase($_POST['ID'], $_POST['Name'], $_POST['Age'], $_POST['City']); // Update in JSON updateInJson($_POST['ID'], $_POST['Name'], $_POST['Age'], $_POST['City']); } else { echo "<h3>All Form Fields are Required</h3>"; } ?>
import { useEffect, useContext, useState } from 'react'; import { Context } from '../../../utils/Store' import { CircularProgress } from '@material-ui/core'; import { Table } from 'react-bootstrap' import { useHistory } from "react-router-dom"; const dateOptions = {year: 'numeric', month: 'numeric', day: 'numeric'}; const timeOptions = {hour: '2-digit', minute: '2-digit' } // unchanged copy pasted from projectlist.jsx const MyProjectlist = () => { let history = useHistory(); const [state, dispatch] = useContext(Context); const [projectAddresses, setProjectAddresses] = useState(""); const [img, setImg] = useState(""); const [btnDisabled, setBtnDisabled] = useState(true); const [content, setContent] = useState(""); const [data, setData] = useState(""); const getProjectAddresses = async () => { setProjectAddresses(await state.store.methods.getProjectList().call()) } const loadData = async () => { let ldata = []; for (let i = projectAddresses.length; i > 0; i--) { let project = projectAddresses[i-1]; let projectName = await state.project.methods.getName(project).call(); let group = await state.project.methods.getGroup(project).call(); let groupName = await state.group.methods.getName(group).call(); let votes = await state.vote.methods.balanceOf(project).call(); let minVotes = await state.project.methods.getMinVotes(project).call(); let endDate = await state.project.methods.getEndDate(project).call(); let percentage = votes * 100 / minVotes; await ldata.push({ "project": project, "projectName": projectName, "votes": votes, "minVotes": minVotes, "endDate": endDate, "percentage": percentage + "%", "group": group, "groupName": groupName, }) } console.log(ldata) setData(ldata); } const projectClick = (address) => { console.log(address) //onClick={() => { projectClick(c.project) }} history.push('/project/' + address) } const tableOutput = async () => { let tableRows = data.map((c) => ( <tr key={c.project} onClick={() => { projectClick(c.project) }}> <td> <div> {c.projectName} </div> <div> Ersteller: {c.groupName} </div> </td> <td style={{ width: "150px" }}> <div className="progress"> <div className="progress-bar bg-success" role="progressbar" style={{ width: c.percentage }} aria-valuenow={c.votes} aria-valuemin="0" aria-valuemax="100%"></div> </div> <div> <center> {c.votes}/{c.minVotes} </center> </div> </td> <td> <div> <center> {new Date(c.endDate * 1000).toLocaleDateString('de-DE', dateOptions)} </center> </div> <div> <center> {new Date(c.endDate * 1000).toLocaleTimeString('de-DE', timeOptions)} </center> </div> </td> </tr> )); setContent(tableRows); } useEffect(async () => { if (projectAddresses == "") { await getProjectAddresses(); } else { if (data.length == "") { await loadData(); } else { await tableOutput(); } } }, [projectAddresses, data]) if (!content) { return ( <CircularProgress /> ) } return ( <div className='projectList'> <br /> <Table striped hover size="sm"> <thead> <tr> <th scope="col">Projekt</th> <th scope="col">Stimmen</th> <th scope="col"><center>Laufzeit</center></th> </tr> </thead> <tbody> {content} </tbody> </Table> </div> ); } export default MyProjectlist;
import React from 'react'; import { render, fireEvent, waitFor, screen } from '@testing-library/react'; import Home from '../Home'; import axios from 'axios'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import Modal from 'react-modal'; jest.mock('axios'); const mockStore = configureStore(); const store = mockStore({ auth: { currentUser: { data: { username: 'testuser', }, access_token: 'your_access_token', }, }, }); Modal.setAppElement(document.createElement('div')); const alertMock = jest.spyOn(window, 'alert').mockImplementation(() => { }); describe('Home Component', () => { it('displays loading message while fetching tasks', async () => { axios.get.mockResolvedValue({ data: [], }); render( <Provider store={store}> <Home /> </Provider> ); // Loading message should be displayed expect(screen.getByText('Loading...')).toBeInTheDocument(); // Wait for the component to finish loading await waitFor(() => { expect(screen.getByText('User: testuser')).toBeInTheDocument(); }); }); it('can add a task', async () => { axios.post.mockResolvedValue({ data: { id: 1, title: 'New Task Title', description: 'Task Description', due_date: '2023-12-31', status: 'Not Started', tags: 'Tag1,Tag2', }, }); render( <Provider store={store}> <Home /> </Provider> ); // Test Click the "Add Task" button to open the add task modal fireEvent.click(screen.getByText('Add')); // Fill in the form fields fireEvent.change(screen.getByPlaceholderText('Task Title'), { target: { value: 'New Task Title' }, }); fireEvent.change(screen.getByPlaceholderText('Task Description'), { target: { value: 'Task Description' }, }); fireEvent.change(screen.getByPlaceholderText('Not Started, PENDING, COMPLETED'), { target: { value: 'Not Started' }, }); fireEvent.change(screen.getByPlaceholderText('Add tag/Category'), { target: { value: 'Tag1,Tag2' }, }); fireEvent.change(screen.getByPlaceholderText('mm/dd/yyy'), { target: { value: '2023-12-31' }, }); // Click the "Save" button to add the task fireEvent.click(screen.getByText('Save')); await waitFor(() => { expect(alertMock).toHaveBeenCalledWith('Task created successfully'); alertMock.mockRestore() }); }); it('can edit a task', async () => { // Mock the response for editing a task axios.put.mockResolvedValue({ data: { id: 1, title: 'Updated Task Title', description: 'Updated Task Description', due_date: '2023-12-31', status: 'Updated Status', tags: 'Tag1,Tag2', }, }); render( <Provider store={store}> <Home /> </Provider> ); // Check if there are tasks available before trying to edit //So we can have as many edit buttons depending on the number of tasks avaiable in the task array const editButtons = screen.queryAllByText('Edit'); if (editButtons.length > 0) { // Click the "Edit" button to open the edit task modal for the first task fireEvent.click(editButtons[0]); // Fill in the form fields within the edit modal fireEvent.click(screen.getByText('Edit')); fireEvent.change(screen.getByPlaceholderText('Not Started, PENDING, Done'), { target: { value: 'Updated Status' }, }); fireEvent.change(screen.getByPlaceholderText('Due Date'), { target: { value: '2023-12-31' }, }); fireEvent.click(screen.getByText('Save')); await waitFor(() => { expect(alertMock).toHaveBeenCalledWith('Task with updated successfully'); alertMock.mockRestore() }); } else { console.log('No tasks available for editing'); } }); });
from random import randint from OpenGL.GL import * class Stern: def __init__(self): self.helligkeit = randint(0, 1) self.nachbarn = [None] * 8 self.lebende_nachbarn = 0 def __str__(self): return '*' if self.helligkeit == 1 else ' ' def change_nachbarn(self, list): self.nachbarn = list self.update_lebende_nachbarn() def update_lebende_nachbarn(self): anzahl_lebender_nachbarn = 0 for nachbar in self.nachbarn: if nachbar and nachbar.helligkeit == 1: anzahl_lebender_nachbarn += 1 self.lebende_nachbarn = anzahl_lebender_nachbarn return anzahl_lebender_nachbarn def next_gen(self) -> bool: if self.helligkeit == 1: # Live cell rules if self.lebende_nachbarn < 2: return False # Dies by underpopulation elif 2 <= self.lebende_nachbarn <= 3: return True # Lives on to the next generation else: return False # Dies by overpopulation else: # Dead cell rules if self.lebende_nachbarn == 3: return True # Becomes a live cell by reproduction else: return False # Stays dead def update(self, x, y): if self.helligkeit == 1: glColor3f(1.0, 1.0, 1.0) # White color for live cells glBegin(GL_QUADS) glVertex2f(x, y) glVertex2f(x + 1, y) glVertex2f(x + 1, y + 1) glVertex2f(x, y + 1) glEnd() else: glColor3f(1.0, 1.0, 1.0) # White color for the outline glBegin(GL_LINE_LOOP) glVertex2f(x, y) glVertex2f(x + 1, y) glVertex2f(x + 1, y + 1) glVertex2f(x, y + 1) glEnd() def switch_alive(self): if self.helligkeit == 1: self.helligkeit = 0 else: self.helligkeit = 1 if __name__ == "__main__": stern = Stern() print(stern)
//// |metadata| { "name": "webupload-overview", "controlName": ["WebUpload"], "tags": ["Getting Started","Selection"], "guid": "6e05f08c-f39d-4b88-af97-20d20eb35447", "buildFlags": [], "createdOn": "2011-04-01T19:43:46.2598843Z" } |metadata| //// = WebUpload Overview == About WebUpload The Infragistics ASP.NET upload control, or WebUpload, is a control that allows you to upload any types of files, sending them from the client browser to the server. The size of the uploaded files can be restricted only by server limitations, so you can upload large files with size more than default 10MB. The upload control is able to handle single uploads (default) or simultaneous multiple file upload operations. To facilitate multiple uploads, the control uses an HTML _iframe_ element to upload files in the background. When the file is uploaded then _iframe_ is removed as HTML DOM element.There are a number of UI elements that support the upload control as depicted in *Figure 1* . Visual elements include: * Progress bar that shows upload progress of an individual file * Information like total size, uploaded size and file name * Icon that changes according to file type * Cancel button ** Once the file is uploaded the cancel button disappears and in its place a success indicator is revealed to the user ** If the upload is canceled the file information is hidden During multiple uploads visual elements include: * Each file has its own progress bar and cancel button ** When Cancel is clicked, that individual file is removed from the upload queue * A summary progress bar displays the upload progress of all files ** The entire upload may be canceled when the overall cancel button is clicked == Architecture Use of the WebUpload control consists of two required parts - client-side jQuery widget and server-side logic which is responsible for handling and processing each upload request. The server is also responsible for processing the upload itself. The example in this document implements server code using ASP.NET Framework, but the WebUpload control is independent of server technology. The upload control exposes a rich jQuery API, so that the controls can be easily configured on the client-side. Also, developers using the Microsoft® ASP.NET MVC framework can leverage the upload control’s server-ide wrapper to configure the control with their .NET™ language of choice. The WebUpload control may be extensively styled giving you an opportunity to provide a completely different look and feel for the control as opposed to the default style. Styling options include using your own styles as well as styles from jQuery UI’s ThemeRoller. *Figure 1: The WebUpload control as presented to the user* image::images/WebUpload_Overview_01.png[] == Features * Single/Multiple Mode * Upload more than default 10MB’s * Automatic Upload * Multiple Simultaneous Upload * Cancel Uploading process * Set maximum upload files * Client-side and Server-side events * Show/Hide progress information * Client-Side and Server-Side validation * Restrict uploaded types * Theme support * Modify progress information and file upload status * Show appropriate icon according to file extension * Modify the text of the control’s labels == Adding WebUpload to a Web Page This example demonstrates how to include and implement the client-side logic of the control and how to configure the server-side so that it receives and saves the uploaded files. .Note: [NOTE] ==== For more information about the server-side architecture and implementation is available in: link:webupload-http-module-and-handler.html[HTTP Handler and Module] ==== This sample demonstrates a basic upload scenario in Single Mode, which will start the upload automatically. *Figure 2* image::images/WebUpload_Overview_02.png[] link:{SamplesUrl}/web-upload/single-upload[Single WebUpload Sample] [start=1] . To get started, include the required and localized resources for your application. [start=2] . On your ASPX page, reference the required JavaScript files, CSS files. [cols="a"] |==== |*In ASPX:* | [source] ---- <link type="text/css" href="/Styles/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" /> ---- [source] ---- <link type="text/css" href="/Styles/css/structure/infragistics.css" rel="stylesheet" /> ---- [source] ---- <script type="text/javascript" src="/Scripts/jquery.min.js"></script> ---- [source] ---- <script type="text/javascript" src="/Scripts/jquery-ui.min.js"></script> <script type="text/javascript" src="/Scripts/js/infragistics.js"></script> ---- |==== [start=3] . Once the above setup is complete, begin to set options including *ID*, pick:[asp-net="link:{ApiPlatform}web.jquery{ApiVersion}~infragistics.web.ui.editorcontrols.webupload~autostartupload.html[autostartupload]"] and pick:[asp-net="link:{ApiPlatform}web.jquery{ApiVersion}~infragistics.web.ui.editorcontrols.webupload~progressurl.html[progressUrl]"] . The last property defines the URL of the HTTP handler that returns file status progress and file size information and handles cancel upload command. That’s all you need on the client-side widget to connect with server-side and get the upload control to work. The remaining options have their default values. For example for the upload mode is single. [cols="a"] |==== |*In ASPX:* |---- <igjq:WebUpload ID="WebUpload1" runat="server" AutoStartUpload="true" ProgressUrl="/WebUploadStatusHandler.ashx"> </igjq:WebUpload > ---- |==== [start=4] . Next you must configure the server-side HTTP Handler and Module. == Configuring the HTTP Handler and Module The required HTTP handler and Module are part of the Infragistics.Web.UI dll as well as the ASP.NET upload wrapper. Follow the steps below to register them in the Web.config file. [start=1] . To get started, first you must create folder with write permissions, where the uploaded files will be saved. Then you have to register that folder in the Web.config (see the code below), so that the WebUpload knows where to save the files. For the current example the folder is called _Uploads_ . [start=2] . You can restrict the size of the uploaded files by setting the _maxFileSizeLimit_ setting. In this sample this size is about 100 MB. [cols="a"] |==== |*In web.config:* |---- <appSettings> <add key="fileUploadPath" value="~/Uploads" /> <add key="maxFileSizeLimit" value="100000000" /> </appSettings> ---- |==== .Note: [NOTE] ==== The value of maxFileSizeLimit is in bytes. ==== [start=3] . Then you need to register the modules and handlers. Depending on your server you should configure Web.config file. == For IIS6(and Development Environment) [cols="a"] |==== |*In web.config:* |---- <system.web> <httpHandlers> <add verb="GET" type="Infragistics.Web.UI.EditorControls.UploadStatusHandler" path="WebUploadStatusHandler.ashx" /> </httpHandlers> <httpModules> <add name="IGUploadModule" type="Infragistics.Web.UI.EditorControls.UploadModule" /> </httpModules> </system.web> ---- |==== == For IIS7 [cols="a"] |==== |*In web.config:* |---- <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="IGUploadModule" type="Infragistics.Web.UI.EditorControls.UploadModule" preCondition="managedHandler" /> </modules> <handlers> <add name="IGUploadStatusHandler" path="WebUploadStatusHandler.ashx" verb="$$*$$" type="Infragistics.Web.UI.EditorControls.UploadStatusHandler" preCondition="integratedMode" /> </handlers> </system.webServer> ---- |==== [start=4] . Run the web page and you will get the basic WebUpload control. Then you can select a file from the file picker window that your browser displays and monitor the progress information that WebUpload exposes as seen in *Figure 2* . .Note: [NOTE] ==== If you are still not able to run the upload control, please follow this link to explore possible errors link:{SamplesUrl}/web-upload/client-side-events[WebUpload Client-side Events Samples]. The client-side events topic explains how to attach to a client-side event onError and investigate the problem. ==== == Related Links link:{SamplesUrl}/web-upload/single-upload[Single WebUpload Sample] link:{SamplesUrl}/web-upload/client-side-events[WebUpload Client-side Events Samples] link:webupload-http-module-and-handler.html[HTTP Handler and Module] link:webupload-using-client-side-events.html[Using client-side events]
class Spacecraft { // Representa nossa "nave" basica, modelo basico. constructor (public propulsor: string){} jumpIntoHyperspace(){ console.log(`Entering hyperspace with ${this.propulsor}`) } } // criando interface interface Containership{ cargoContainers: number //Podemos atribuir um "?" no final do nome do atributo para tornar ele opcional. } export {Spacecraft, Containership} //Geralmente usamos apenas um tipo/classe/interface em um arquivo, porém podemos encontrar mais tipo/classe/interface em um mesmo arquivo. // Dar preferencia em usar um arquivo para cada tipo
import { Box, Container, Divider, Typography, styled } from '@mui/material' import Checkbox from '@mui/material/Checkbox' import FormControlLabel from '@mui/material/FormControlLabel' import FormGroup from '@mui/material/FormGroup' import { pink } from '@mui/material/colors' import * as React from 'react' import ComponentsLayout from '../../../../layouts/componentsLayout' const label = { inputProps: { 'aria-label': 'Checkbox demo' } } export const StyledDivider = styled(Divider)(({ theme }) => ({ marginBottom: theme.spacing(2), marginTop: theme.spacing(2), color: theme.palette.grey[500], })) // const [checked, setChecked] = React.useState([true, false]); const CheckBoxesPage = (): JSX.Element => { return ( <Container sx={{ py: 2 }}> <Typography variant="h2">Basic Checkboxes</Typography> <Typography variant="h3">Checkboxes</Typography> <Box> <Checkbox {...label} defaultChecked /> <Checkbox {...label} /> <Checkbox {...label} disabled /> <Checkbox {...label} disabled checked /> </Box> <Typography variant="h3">Checkbox with Label</Typography> <FormGroup> <FormControlLabel control={<Checkbox defaultChecked />} label="Label" /> <FormControlLabel control={<Checkbox />} label="Required" /> <FormControlLabel disabled control={<Checkbox />} label="Disabled" /> </FormGroup> <Typography variant="h3">Colored Checkbox</Typography> <Checkbox {...label} defaultChecked /> <Checkbox {...label} defaultChecked color="secondary" /> <Checkbox {...label} defaultChecked color="success" /> <Checkbox {...label} defaultChecked color="default" /> <Checkbox {...label} defaultChecked sx={{ color: pink[800], '&.Mui-checked': { color: pink[600], }, }} /> <StyledDivider /> </Container> ) } CheckBoxesPage.getLayout = (page: React.ReactElement) => <ComponentsLayout>{page}</ComponentsLayout> export default CheckBoxesPage
<h2 mat-dialog-title>{{relation.courseName}}</h2> <mat-dialog-content> <ng-container *ngIf="!editMode; else editView"> <mat-card-header> <mat-card-title> <span>{{relation.teacher}}</span> <span> -> </span> <span>{{relation.student}}</span> </mat-card-title> </mat-card-header> <mat-card-content> <mat-divider></mat-divider> <div style="display: flex; align-items: center; justify-content: center"> </div> <br> <strong>Duration: {{relation.duration}}hr</strong><br> <strong>{{relation.classPerWeek}} Class Per Week</strong><br> <span>Price: {{relation.price}}$</span><br> <span>Teacher Salary: {{relation.salary}}$</span><br> </mat-card-content> </ng-container> <ng-template #editView> <form [formGroup]="formGroup"> <ng-template matStepLabel>Basic Info</ng-template> <p style="margin-top: 10px"> <mat-form-field appearance="outline"> <mat-label>Name</mat-label> <input matInput formControlName="nameCtrl" [(ngModel)]="this.relation.courseName" placeholder="Math" required> <mat-hint>Name of relation</mat-hint> </mat-form-field> </p> <p> <mat-form-field appearance="outline"> <mat-label>Class Per Week</mat-label> <input type="number" matInput [(ngModel)]="this.relation.classPerWeek" placeholder="Slab" formControlName="classPerWeekCtrl"> </mat-form-field> </p> <p> <mat-form-field appearance="outline"> <mat-label>Duration</mat-label> <input type="number" matInput [(ngModel)]="this.relation.duration" placeholder="Slab" formControlName="durationCtrl"> <mat-hint>In hours</mat-hint> </mat-form-field> </p> <p> <mat-form-field appearance="outline"> <mat-label>Price</mat-label> <input type="number" matInput [(ngModel)]="this.relation.price" placeholder="Slab" formControlName="priceCtrl"> <mat-hint>In dollars</mat-hint> </mat-form-field> </p> <p> <mat-form-field appearance="outline"> <mat-label>Salary</mat-label> <input type="number" matInput [(ngModel)]="this.relation.salary" placeholder="Slab" formControlName="salaryCtrl"> <mat-hint>In dollars</mat-hint> </mat-form-field> </p> </form> </ng-template> </mat-dialog-content> <mat-dialog-actions align="end"> <ng-container *ngIf="!editMode; else editOptions"> <button mat-button (click)="toggleEditMode()">Edit</button> <button mat-button color="warn" (click)="deleteRelation()" mat-dialog-close="">Delete</button> </ng-container> <ng-template #editOptions> <button mat-raised-button color="primary" (click)="updateRelation()" [disabled]="this.formGroup.invalid" mat-dialog-close="">Save </button> </ng-template> </mat-dialog-actions>
--- title: "ドメイン取得サービスで取得したサブドメインだけをAmplifyアプリケーションに割り当てる" emoji: "🅰️" type: "tech" topics: ["Amplify", "AWS", "DNS"] published: true --- ## はじめに ドメイン取得サービスで取得したドメインのサブドメインだけをAmplifyアプリケーションに割り当てたいという場合、サブドメインにCNAMEレコードを設定することで実現できます。 今回はムームードメインをドメイン取得サービスとして利用します。 ## 手順 ムームードメインでサブドメインを取得している前提で話を進めます。 ### Amplify Consoleでカスタムドメインを追加 まずはムームードメインで取得したドメインを設定します。 今回はサブドメインだけを割り当てたいので、ルートを除外し、取得したサブドメインを追加します。 ![](/images/amplify-add-subdomain/flow1.png) ## ムームードメインでCNAMEレコードを設定 カスタムドメインを追加すると、SSLの設定が始まります。画面中央に表示されるサブドメインとCNAMEレコードをムームードメイン側で設定します。 ![](/images/amplify-add-subdomain/flow2.png) ![](/images/amplify-add-subdomain/flow3.png) 追加でCNAMEレコードの追加を促されるので、アクション→DNSレコードを表示をクリックします。 ![](/images/amplify-add-subdomain/flow4.png) CloudFrontのCNAMEレコードをムームードメイン側で設定します。 ![](/images/amplify-add-subdomain/flow5.png) ![](/images/amplify-add-subdomain/flow6.png) 以上で設定は完了です。 ドメインがアクティベートされたら、ムームードメインで取得したサブドメインにアクセスし、Amplifyアプリケーションが表示されることを確認しましょう。 ## 最後に 現時点では、デフォルトドメインである`xxx.amplifyapp.com`からもアプリケーションにアクセスできてしまいます。 Amplifyではデフォルトドメインを無効化することはできませんが、デフォルトドメインへのアクセス時にカスタムドメインへリダイレクトさせる設定をしておくと良いと思います。 詳しい手順は以下の記事を参照してみてください。 https://dev.classmethod.jp/articles/tsnote-amplify-how-do-i-disable-the-default-domain-for-amplify-hosting/
import React, { useState, useEffect } from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { navbarActions } from "../Redux/navbarReducer"; import TextField from "@mui/material/TextField"; function ResetPassword() { const dispatch = useDispatch(); const [email, setemail] = useState(""); const history = useNavigate(); useEffect(() => { window.scrollTo(0, 0); }, []); useEffect(() => { dispatch(navbarActions.updatenavbar(false)); }, [dispatch]); const Resetpass = (e) => { e.preventDefault(); axios .get("http://localhost:8000/api/users/" + email) .then((res) => { if (res.data === null) { alert("email not correct !!"); } else { axios .post("http://localhost:8000/account", { email, type: "reset", }) .then((res) => { alert("Check your email to continue !!"); history("/SignIn"); }) .catch((err) => alert("Error Server")); } }) .catch((err) => { alert("Error Server"); }); }; return ( <div className="container-fluid" style={{ backgroundColor: "#E9FBF3" }}> <div className="container"> <div className="row"> <div className="card" style={{ backdropFilter: "blur(30px)", marginTop: "200px", marginBottom: "200px", backgroundColor: "white", }} > <div className="card-body"> <form onSubmit={Resetpass}> <br /> <h3>Find your account </h3> <br /> <TextField type="email" name="email" label="Enter your email" variant="outlined" onChange={(e) => setemail(e.target.value)} fullWidth required /> <br /> <br /> <div className="Search__actions"> <button type="submit"> Next </button> </div> <br /> </form> </div> </div> </div> </div> </div> ); } export default ResetPassword;
package com.example.empresa25; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class UsuarioActivity extends AppCompatActivity implements Response.Listener<JSONObject>,Response.ErrorListener { EditText jetusuario,jetnombre,jetcorreo,jetclave; CheckBox jcbactivo; RequestQueue rq; JsonRequest jrq; String usr, nombre,correo,clave; byte sw; String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_usuario); //ocultar barra, asociar objetos Java con objetos xml, iniciar cola de consultar getSupportActionBar().hide(); jetusuario=findViewById(R.id.etusuario); jetcorreo=findViewById(R.id.etcorreo); jetclave=findViewById(R.id.etclave); jetnombre=findViewById(R.id.etnombre); jcbactivo=findViewById(R.id.cbactivo); rq = Volley.newRequestQueue(this); sw=0; } public void Guardar(View view){ usr=jetusuario.getText().toString(); nombre=jetnombre.getText().toString(); correo=jetcorreo.getText().toString(); clave=jetclave.getText().toString(); if(usr.isEmpty() || nombre.isEmpty() || correo.isEmpty() || clave.isEmpty()){ Toast.makeText(this, "Todos los datos son requeridos.", Toast.LENGTH_SHORT).show(); jetusuario.requestFocus(); } else{ if(sw==0){ url="http://localhost:3306/WebServices/registrocorreo.php"; }else{ url="http://localhost:3306/WebServices/actualiza.php"; sw=0; } StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Limpiar_campos(); Toast.makeText(getApplicationContext(), "Registro de usuario realizado!", Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Registro de usuario incorrecto!", Toast.LENGTH_LONG).show(); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("usr",jetusuario.getText().toString().trim()); params.put("nombre", jetnombre.getText().toString().trim()); params.put("correo",jetcorreo.getText().toString().trim()); params.put("clave",jetclave.getText().toString().trim()); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(postRequest); } } public void Eliminar(View view){ usr=jetusuario.getText().toString(); if(usr.isEmpty()){ Toast.makeText(this, "El usuario es requerido", Toast.LENGTH_SHORT).show(); jetusuario.requestFocus(); } else{ url="http://localhost:3306/WebServices/elimina.php"; StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Limpiar_campos(); Toast.makeText(getApplicationContext(), "Usuario eliminado!", Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Usuario no eliminado!", Toast.LENGTH_LONG).show(); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("usr",jetusuario.getText().toString().trim()); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(postRequest); } } public void Anular(View view){ usr=jetusuario.getText().toString(); if(usr.isEmpty()){ Toast.makeText(this, "El usuario es requerido", Toast.LENGTH_SHORT).show(); jetusuario.requestFocus(); } else{ url="http://localhost:3306/WebServices/anula.php"; StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Limpiar_campos(); Toast.makeText(getApplicationContext(), "Usuario anulado!", Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Usuario no anulado!", Toast.LENGTH_LONG).show(); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("usr",jetusuario.getText().toString().trim()); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(postRequest); } } public void Consultar(View view){ usr=jetusuario.getText().toString(); if(usr.isEmpty()){ Toast.makeText(this, "Usuario es requerido para la búsqueda", Toast.LENGTH_SHORT).show(); jetusuario.requestFocus(); } else{ url = "http://localhost:3306/WebService/consulta.php?usr="+usr; jrq = new JsonObjectRequest(Request.Method.GET,url,null,this,this); rq.add(jrq); } } public void Limpiar(View view){ Limpiar_campos(); } public void Regresar(View view){ Intent intmain=new Intent(this,MainActivity.class); startActivity(intmain); } public void Limpiar_campos(){ sw=0; jetcorreo.setText(""); jetnombre.setText(""); jetusuario.setText(""); jetclave.setText(""); } @Override public void onErrorResponse(VolleyError error) { Toast.makeText(this, "Usuario no registrado", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(JSONObject response) { sw=1; Toast.makeText(this, "Usuario Registrado", Toast.LENGTH_SHORT).show(); JSONArray jsonArray = response.optJSONArray("datos"); JSONObject jsonObject = null; try{ jsonObject = jsonArray.getJSONObject(0);//posición 0 del arreglo porque por acá entra si encuentra un registro, y hay uno solo, entonces es el de la posición 0 jetnombre.setText(jsonObject.optString("nombre")); jetcorreo.setText(jsonObject.optString("correo")); if(jsonObject.optString("activo").equals("si")){ jcbactivo.setChecked(true); }else{ jcbactivo.setChecked(false); } } catch (JSONException e) { e.printStackTrace(); } } }
package switchtwentytwenty.project.dto.outdto; import lombok.Getter; import org.springframework.hateoas.RepresentationModel; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class CategoryTreeOutDTO extends RepresentationModel<CategoryTreeOutDTO>{ @Getter private String designation; @Getter private List<CategoryTreeOutDTO> children; /** * Sole Constructor. * * @param designation of the category */ public CategoryTreeOutDTO(String designation) { this.designation = designation; this.children = new ArrayList<>(); } public void addChildTree(CategoryTreeOutDTO tree){ this.children.add(tree); } @Override public int hashCode(){ return Objects.hash(designation, children); } @Override public boolean equals(Object o){ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CategoryTreeOutDTO that = (CategoryTreeOutDTO) o; return Objects.equals(designation, that.designation) && Objects.equals(children, that.children); } @Override public String toString(){ return designation + children; } }
--- sidebar_position: 3 --- # 📏 Distances & Movement ## Distances Various effects and abilities list the following distances to describe their range. | Distance | Description | In Meters | In Areas | | --- | --- | --- | --- | | Melee | touching or fighting distance | <2 meters | 0 areas | | Close | within a few steps | 2-4 meters | 0 areas | | Short | normal speaking distance | 5-10 meters | 1 area | | Medium | a short sprint | 11-20 meters | 2 areas | | Long | louder shouting distance | 21-40 meters | 3-4 areas | | Very Long | unhindered viewing distance | 41-80 meters | 5-8 areas | | Extreme | barely perceivable if at all | 81+ meters | 9+ areas | ## Movement Movement describes your ability to move between or within areas in combat. Normally, 1 Movement lets you move to one area within short distance. Some areas have the property “difficult terrain” and require 2 Movement to be entered and 1 Movement to move close. This Movement can happen over multiple combat turns, as long as no Movement is spent for any other purpose in between. ### Moving into melee range When you are close to another creature, you can choose to move into melee range of them. Similarly, you can choose to move out of melee range. You can do one of both once on your turns without spending any Movement. Doing it multiple times on the same turn costs 1 Movement each time beyond the first. Being in melee range can be shared between groups of multiple creatures, as makes sense. So, when you move into melee range of a creature that is already in melee range of a second creature, all three of you are now in melee range of each other. Moving out of melee range triggers an Opportunity Attack from all enemies you were in melee range of. You can also move in melee range of specific locations or objects within an area, such as cover. ### Falling Many effects and abilities might leave you without solid ground beneath your feet. You can generally fall in two different ways. - Falling involuntarily by some harmful effect. - Falling voluntarily by your own actions. When you attempt to control your fall, roll Agility + Athletics as an Action. The difficulty is easy for a close distance and is increased by one step for each additional falling distance. If you succeed, you reduce the damage you take to one step lower than normal. Under normal circumstances, you fall up to a very long distance during one encounter turn or until you hit the ground. If you fall over multiple turns, you first fall a very long distance immediately and then the same distance at the end of each of your turns until you hit the ground. - If you fall outside of your turn, you can use an appropriate Quick Action before falling the distance. - If you fall during your turn, you can use an Action or Quick Action before falling the distance. Depending on the distance you have fallen before hitting the ground, you take damage as follows. Falling damage ignores your AV. If you take damage from falling, you also fall prone. | Distance | Close | Short | Medium | Long | Very Long | Extreme | | --- | --- | --- | --- | --- | --- | --- | | Damage | 5 | 10 | 20 | 40 | 60 | 80 | ### Moving Objects You can move heavy objects depending on your Strength: - up to 3 x Strength: move normally. - up to 10 x Strength: move as in difficult terrain. - up to 20 x Strength: move a short distance over one delving turn. > These ranged assume you have move the object without support. For example, dragging an object on the ground instead of carrying it might increase the size and weight of objects you can move. > ### Crawling, Crouching, Climbing, and Swimming With these variants of Movement, you move as if in difficult terrain (2 Movement instead of 1 for a short distance). You might also be required to succeed on a Strength/Agility + Athletics roll to be able to move at all, as when climbing along a crumbling wall or swimming in rushing waters. ### Jumping If you move at least a close distance, you can jump a close distance without rolling. Otherwise, you have to succeed on a Strength + Athletics roll. ### Suffering conditions during Movement If you are swimming or flying and suffer conditions that reduce your Movement to 0 or drop you prone, you lose control of your Movement. You immediately start drowning or falling respectively. You drown for a short distance or fall a very long distance each turn you can‘t move. If you are climbing and are pushed or knocked prone, you also lose control of your Movement and start falling. However, you might be able to stop your fall by succeeding on a Strength/Agility + Athletics roll. If you do, you stop falling after the distance you were pushed or a close distance otherwise. ## Areas Areas are an abstraction of connected spaces during combat. When using a battle map for combat, define enclosed areas for small, connected spaces. Combatants within the same area are close to each other, while those one area apart are within short distance of each other, and so on. > For visualisation, you can use index cards for individual areas. Write down a distinct name for each card and note its area properties. Place your cards next to each other to show how they are connected. You can use any gaming tokens for active combatants and place them onto the cards. Group up tokens that are in a melee. > ### Area Properties Areas are seldom flat, featureless places. Most often they are part of a building or natural environment which proves different properties for all combatants that attempt to move into them or are within them. Examples of area properties include: - **Dim Light.** Any rolls requiring sight in or through this area suffer +1 bane. - **Total Darkness.** Any creature is considered blinded for looking into or through this area. - **Difficult Terrain.** Requires 2 Movement to move into this area (you can spend this Movement over multiple turns). Moving into or out of melee range requires 1 Movement. - **Elevated.** This area is uphill or on a higher elevation. Ranged attacks from this area to an un-elevated area gain +1 boon. Special movements such as climbing or flying might be required to enter this area. - **Tiny.** All creatures in this area are automatically in melee range of each other. - **Special Location.** This area includes a special location that creatures can move into melee range with, to gain certain effects. Examples are a lever for a nearby drawbridge, a magical fountain with healing water, or a pillar that can be climbed or hidden behind. - **Underwater.** Creatures can’t breathe or fire missile weapons. Lightning damage spreads around the source and target, automatically dealing 1/2 of its damage to any creature close to either of them if in contact with the water.
import { applyMiddleware, createStore } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly'; import rootReducer from "../reducers"; function configureStore(preloadedState: any) { const middlewares = [thunk]; const middlewareEnhancer = applyMiddleware(...middlewares); const storeEnhancers = [middlewareEnhancer]; const composedEnhancer = composeWithDevTools(...storeEnhancers); return createStore( rootReducer, preloadedState, composedEnhancer ); } const store = configureStore({}); export default store;
// ignore_for_file: avoid_print import 'dart:developer'; import 'package:app/models/admin/create_groupevent.dart'; import 'package:app/screens/admin/createGroup/create_group.dart'; import 'package:app/screens/admin/group_details.dart'; import 'package:app/screens/admin/admin_side_nav.dart'; import 'package:app/screens/message/group_messages.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class AllGroups extends StatefulWidget { const AllGroups({Key? key}) : super(key: key); @override _AllGroupsState createState() => _AllGroupsState(); } class _AllGroupsState extends State<AllGroups> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); TextEditingController groupNameController = TextEditingController(); bool loading = false; List<CreateGroupEvent> events = []; @override void initState() { super.initState(); getGroups(); } void selectGroup(CreateGroupEvent group) { Navigator.of(context).push(MaterialPageRoute(builder: (_){ return GroupDetails(group); })); } void goToCreateGroup() { Navigator.of(context).push(MaterialPageRoute(builder: (_) { return const CreateGroup(); })); } void getGroups() async { User? user = FirebaseAuth.instance.currentUser; if (user != null) { setState(() { loading = true; }); List<CreateGroupEvent> evs = []; await FirebaseFirestore.instance .collection('adminEvent') .get() .then((value) { for (QueryDocumentSnapshot<Map<String, dynamic>> doc in value.docs) { List<String> interests = []; DateTime startDate = (doc.data()['startDate'] as Timestamp).toDate(); DateTime endDate = (doc.data()['endDate'] as Timestamp).toDate(); String startsAt = (doc.data()['startsAT'] as Timestamp).toDate().hour.toString(); evs.add( CreateGroupEvent( doc.data()['iconURL'], doc.id, doc.data()['groupName'], doc.data()['eventName'], startDate, endDate, startsAt, doc.data()['eventLocation'], doc.data()['ticketPrice'], doc.data()['minAge'].toString(), doc.data()['maxAge'].toString(), doc.data()['country'], doc.data()['gender'], interests, ), ); } setState(() { loading = false; events = evs; }); }).catchError((onError) { log(onError); }); } } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, drawer: const AdminSideNav(), body: loading ? const Center(child: CircularProgressIndicator()) : Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 30), Center( child: Container( height: MediaQuery.of(context).size.height / 16, width: MediaQuery.of(context).size.width / 1.1, decoration: BoxDecoration( // color: Colors.purple, borderRadius: BorderRadius.circular(14)), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ const SizedBox(width: 10), GestureDetector( onTap: () { _scaffoldKey.currentState!.openDrawer(); }, child: const Icon(Icons.menu, color: Colors.deepPurple), ), const SizedBox(width: 10), const Text( 'ALL GROUPS', style: TextStyle( color: Colors.deepPurple, fontWeight: FontWeight.w800), ), ], ), TextButton.icon( onPressed: goToCreateGroup, icon: const Icon( Icons.add, color: Colors.deepPurple, ), label: const Text( 'Create Group', style: TextStyle(color: Colors.deepPurple), )) ], ), ), ), const Padding( padding: EdgeInsets.only(left: 8.0, top: 10), child: Align( alignment: Alignment.centerLeft, child: Text( ' Group For upcoming events:', style: TextStyle( color: Colors.deepPurple, fontWeight: FontWeight.w800), ), ), ), const SizedBox(height: 5,), const GroupMessages(), // Expanded( // child: ListView.builder( // itemCount: events.length, // itemBuilder: (context, index) { // return Card( // child: ListTile( // onTap: () => selectGroup(events[index]), // leading: const Icon(Icons.group_work_rounded), // title: Text(events[index].eventName), // trailing: Text(events[index].startsAt), // ), // ); // }, // ), // ), /* const ListTile( leading: CircleAvatar( backgroundImage: ExactAssetImage('assets/pic.jpg'), ), title: Text( ' Premier League Final', style: TextStyle( color: pinkAccent, fontWeight: FontWeight.w800), ), subtitle: Text( ' Ken I dont like Arsenal lol!', style: TextStyle( color: Colors.grey, ), ), trailing: Text( ' 08:00 PM ', style: TextStyle( color: Colors.grey, ), ), ), const ListTile( leading: CircleAvatar( backgroundImage: ExactAssetImage('assets/pic.jpg'), ), title: Text( ' Drake London Concert', style: TextStyle( color: pinkAccent, fontWeight: FontWeight.w800), ), subtitle: Text( ' Adam I really love the idea', style: TextStyle( color: Colors.grey, ), ), trailing: Text( ' 08:00 PM ', style: TextStyle( color: Colors.grey, ), ), ) */ ], ), ); } }
## From https://arxiv.org/html/2405.12399v1 ## DIAMOND: Diffusion Models for World Modeling DIAMOND (DIffusion As a Model Of eNvironment Dreams) introduces a novel approach using diffusion models for training reinforcement learning (RL) agents. Traditional world models compress environment dynamics into discrete latent variables, which may lose critical visual details. DIAMOND, leveraging high-fidelity image generation via diffusion models, maintains these details and significantly enhances agent performance. It achieved a mean Human Normalized Score (HNS) of 1.46 on the Atari 100k benchmark, the best for agents trained entirely within a world model​. Working Principle and Process 1. Environment Dynamics Modeling DIAMOND uses diffusion models to predict future observations based on past observations and actions. Diffusion models generate high-resolution images, preserving visual fidelity crucial for decision-making. -1. Detailed Process - Use of Diffusion Models DIAMOND predicts the next observation by solving the reverse diffusion stochastic differential equation (SDE). The diffusion model generates future states by incrementally denoising a sampled trajectory segment from the replay dataset. - Diffusion Process The process involves perturbing the current observation with noise and solving the reverse SDE to gradually obtain the next state. This ensures high-quality visual details. - Network Architecture A U-Net 2D structure is used to model the vector field. Past observations and actions are stored in a buffer and concatenated channel-wise with the noisy next observation input. Actions are integrated via adaptive group normalization layers​ 2. Reinforcement Learning Agents are trained within DIAMOND’s simulated environment, reducing the need for extensive real-world interactions. Training involves updating models using collected data and iterating through simulation. -1. Detailed Process - Training Process Agents collect data from the real environment, update the model, and undergo repeated training in the simulated environment. - Policy Training The RL agents use an actor-critic network with a CNN-LSTM structure. Policies are trained using the REINFORCE algorithm and value networks via Bellman error minimization. - Performance and Results DIAMOND demonstrated exceptional performance on the Atari 100k benchmark, achieving a mean HNS of 1.46, surpassing human performance levels in various games 3. Experimentation and Results DIAMOND excels in the Atari 100k benchmark, achieving remarkable scores with only 100,000 interactions, equivalent to about 2 hours of human gameplay. -1. Detailed Process - Mean Human Normalized Score (HNS) DIAMOND achieves an impressive mean HNS of 1.46, setting a new standard for agents trained entirely within a world model. - Individual Game Performance DIAMOND outperformed existing methods in several games where visual details are crucial, such as Breakout, where it scored 132.5 compared to the human score of 30.5​ - Practical and Theoretical Implications ## Practical Implications DIAMOND’s superior visual models enhance agent generalization in real-world environments where visual details are critical. For example, autonomous vehicles can better distinguish pedestrians from trees at a distance, making such systems more robust and reliable. -1. Theoretical Implications The successful application of diffusion models opens new research avenues. Combining image generation techniques with RL addresses long-standing issues like sample inefficiency and emphasizes the importance of visual fidelity in agent performance​ ## Future Research Directions -1. Integration into Continuous Control Domains Testing DIAMOND in environments with continuous actions to further assess its robustness. -2. Enhancing Memory Capabilities Incorporating transformers to handle longer-term dependencies and improve model performance. -3. Unified Reward and Termination Models Combining these with the diffusion process while maintaining model simplicity could significantly boost performance​ (ar5iv)​​ (Emergent Mind Explorer)​. ## Detailed Equations and Processes -1. Diffusion Model Equations DIAMOND uses reverse diffusion SDEs to model environment dynamics. The key equations include: - Forward SDE 𝑑𝑥_𝑡 = 𝑓(𝑥_𝑡,𝑡)𝑑𝑡 + 𝑔(𝑡)𝑑𝑊𝑡 Where 𝑥_𝑡 is the state, 𝑓 is the drift coefficient, 𝑔 is the diffusion coefficient, and 𝑊𝑡 is the Wiener process (noise). - Reverse SDE 𝑑𝑥_𝑡 = [𝑓(𝑥_𝑡,𝑡) − 𝑔(𝑡)^2∇𝑥_𝑡 log 𝑝_𝑡(𝑥_𝑡)]𝑑𝑡 + 𝑔(𝑡)𝑑𝑊ˉ_𝑡 Where ∇_(𝑥_𝑡)log 𝑝_𝑡(𝑥_𝑡) is the score function and 𝑊ˉ𝑡 is the reverse-time Wiener process. - Noise Sampling Initial states are perturbed with noise (𝑥~)𝑡 = 𝑥_𝑡 + 𝜎_𝑡𝜖 , 𝜖 ∼ 𝑁(0,I) - Denoising Process The denoising process gradually refines the perturbed state (𝑥^)𝑡 =(𝑥~)_𝑡 − 𝜎_𝑡∇(𝑥~)_𝑡 log 𝑝((𝑥~)_𝑡) These equations describe how DIAMOND maintains high visual fidelity through the reverse diffusion process, crucial for accurate state representation and effective RL agent training​ (ar5iv)​​ (Emergent Mind Explorer)​. In conclusion, DIAMOND represents an innovative stride in leveraging diffusion models within RL world modeling. It addresses visual fidelity and stability concerns of current latent variable methods, setting a new standard in sample-efficient training and opening promising avenues for future AI and RL research.
<html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> <script src="/static/script.js"></script> <link rel="stylesheet" href="/static/styles.css" /> </head> <body> <div class="main-title"> <div class="overlay"> <div> <h1>당당마켓</h1> <span>가장 가까운 중고거래 플랫폼 {{ request.user.username }}</span> </div> </div> </div> <div class="product-content"> <div> {% if request.user.is_authenticated %} <a href="/logout/">Logout</a> {% else %} <a href="/login/">Login</a> <br/> <a href="/register/">Register</a> {% endif %} </div> <div class="list-group list-group-flush"> {% for product in products %} <button type="button" class="list-group-item list-group-item-action" id="{{ product.id }}" > <div class="d-flex align-items-center"> <div class="flex-shrink-0"> <!--이미지가 있으면 보여주고 없으면 보유주지 않게 해서 예외처리--> {% if product.image %} <img src="{{ product.image.url }}" class="product-image"> {% else %} <img src = "/static/bg.jpg" class="product-image"> {% endif %} </div> <div class="flex-grow-1 ms-3 text-end"> {{ product.title }}<br/> {{ product.price }}<br/> {{ product.location }}<br/> {{ product.user.username }} </div> </div> </button> {% endfor %} </div> {% if request.user.is_authenticated %} <div class = "text-end mt-3"> <a role="button" href="/product/write/" class="btn btn-primary">상품 등록</a> </div> {% endif %} </div> <div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="detailModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="detailModalTitle"></h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div id="detailModalUsername"></div> <img src="{{ product.image.url }}" id="detailModalImage" /> <div id="detailModalLocation"></div> <div id="detailModalPrice"></div> <div id="detailModalContent"></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">확인</button> </div> </div> </div> </div> </body> </html>
@extends('mado.admin.shop.template') @section('title', 'スタッフ管理|LIXIL簡易見積りシステム') @section('main') <main class="common staff"> <h1 class="mainTtl">スタッフ管理</h1> {{-- 通知メッセージ --}} @include ('mado.admin.parts.notice_message') <p class="mb30">スタッフの削除は、クリアボタンを押して登録情報を空にした状態で登録ボタンを押してください</p> <div id="clear-staff"> {!! Form::open([ 'route' => ['admin.shop.staff.edit', 'shop_id' => Request::route('shop_id')], 'enctype' => 'multipart/form-data', ]) !!} @foreach ($staffs as $staff) <div class="staffCnt"> <div class="staffTitle"> <span>{{ $staff->{config('const.db.staffs.RANK')} }}人目</span> {!! Form::button('クリア', [ 'id' => null, 'class' => 'button', 'v-on:click' => 'onClick($event, ' . $staff->{config('const.db.staffs.RANK')} . ')', ]) !!} </div> </div> <table class="formTbl"> <tr> <th>役職</th> <td> <p> {!! Form::text( config('const.db.staffs.POST') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.POST') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.POST')}), [ 'id' => null, 'class' => null, ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.POST') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>名前</th> <td> <p> {!! Form::text( config('const.db.staffs.NAME') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.NAME') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.NAME')}), [ 'id' => null, 'class' => null, ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.NAME') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>メッセージ</th> <td> <p> {!! Form::textarea( config('const.db.staffs.MESSAGE') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.MESSAGE') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.MESSAGE')}), [ 'id' => null, 'class' => null, 'placeholder' => '自己紹介(担当業務内容等)とともに仕事に関する価値観が伝わる内容のメッセージを掲載しましょう!', ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.MESSAGE') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>写真</th> <td> <file-upload name="{{ config('const.form.admin.shop.staff.PICTURE') . '_' . $staff->{config('const.db.staffs.RANK')} }}" image="{{ $staff->imageUrl() }}" ref="{{ $staff->{config('const.db.staffs.RANK')} }}" image-cls="shopImge" image-width="200" image-height="150"></file-upload> <p class="errMsg">{{ $errors->first(config('const.form.admin.shop.staff.PICTURE') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>資格</th> <td> <p> {!! Form::textarea( config('const.db.staffs.CERTIFICATE') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.CERTIFICATE') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.CERTIFICATE')}), [ 'id' => null, 'class' => null, 'placeholder' => '資格情報をご記入ください', ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.CERTIFICATE') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>趣味</th> <td> <p> {!! Form::textarea( config('const.db.staffs.HOBBY') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.HOBBY') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.HOBBY')}), [ 'id' => null, 'class' => null, 'placeholder' => '趣味をご記入ください。お客さまに共感していただけるような表現にしましょう! 例)休日のウッドデッキで楽しむ「おうちカフェ」と「オープンダイニング」', ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.HOBBY') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> <tr> <th>代表施工事例</th> <td> <p> {!! Form::textarea( config('const.db.staffs.CASE') . '_' . $staff->{config('const.db.staffs.RANK')}, old(config('const.db.staffs.CASE') . '_' . $staff->{config('const.db.staffs.RANK')}, $staff->{config('const.db.staffs.CASE')}), [ 'id' => null, 'class' => null, 'placeholder' => '施工した代表的な施工現場の名称をご記入ください。 例)〇〇市役所・〇〇分譲地等', ] ) !!} </p> <p class="errMsg">{{ $errors->first(config('const.db.staffs.CASE') . '_' . $staff->{config('const.db.staffs.RANK')}) }}</p> </td> </tr> </table> @endforeach <div class="btnBlock"> <p>{!! Form::submit('登録', ['class' => 'button _submit']) !!}</p> </div> {!! Form::close() !!} </div> </main> @endsection
//! Validators for status words: [IHW][Ihw], [TDH][Tdh], [TDT][Tdt] & [DDW0][Ddw0]. //! //! Each validator is aggregated by the [StatusWordSanityChecker] struct. use crate::words::its::status_words::{ddw::Ddw0, ihw::Ihw, tdh::Tdh, tdt::Tdt, StatusWord}; use ddw::Ddw0Validator; use ihw::IhwValidator; use tdh::TdhValidator; use tdt::TdtValidator; mod ddw; mod ihw; pub(super) mod tdh; pub(super) mod tdt; pub(super) mod util; /// Aggregates all status word validators. #[derive(Debug, Clone, Copy)] pub struct StatusWordSanityChecker { ihw_validator: IhwValidator, tdh_validator: TdhValidator, tdt_validator: TdtValidator, ddw0_validator: Ddw0Validator, // No checks for CDW } impl StatusWordSanityChecker { /// Creates a new [StatusWordSanityChecker] in a const context. pub const fn new() -> Self { Self { ihw_validator: IhwValidator::new_const(), tdh_validator: TdhValidator::new_const(), tdt_validator: TdtValidator::new_const(), ddw0_validator: Ddw0Validator::new_const(), } } /// Checks if argument is a valid [IHW][Ihw] status word. pub fn check_ihw(&self, ihw: &Ihw) -> Result<(), String> { self.ihw_validator.sanity_check(ihw) } /// Checks if argument is a valid [TDH][Tdh] status word. pub fn check_tdh(&self, tdh: &Tdh) -> Result<(), String> { self.tdh_validator.sanity_check(tdh) } /// Checks if argument is a valid [TDT][Tdt] status word. pub fn check_tdt(&self, tdt: &Tdt) -> Result<(), String> { self.tdt_validator.sanity_check(tdt) } /// Checks if argument is a valid [DDW0][Ddw0] status word. pub fn check_ddw0(&self, ddw0: &Ddw0) -> Result<(), String> { self.ddw0_validator.sanity_check(ddw0) } } trait StatusWordValidator<T: StatusWord> { fn sanity_check(&self, status_word: &T) -> Result<(), String>; } #[cfg(test)] mod tests { use super::*; use crate::words::its::status_words::StatusWord; const STATUS_WORD_SANITY_CHECKER: StatusWordSanityChecker = StatusWordSanityChecker::new(); #[test] #[should_panic] fn test_ddw0_invalid() { let raw_ddw0_bad_index = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xE4]; let ddw0_bad = Ddw0::load(&mut raw_ddw0_bad_index.as_slice()).unwrap(); STATUS_WORD_SANITY_CHECKER.check_ddw0(&ddw0_bad).unwrap(); } #[test] fn test_ddw0_invalid_handled() { let raw_ddw0_bad_index = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xE4]; let ddw0_bad = Ddw0::load(&mut raw_ddw0_bad_index.as_slice()).unwrap(); assert!(STATUS_WORD_SANITY_CHECKER.check_ddw0(&ddw0_bad).is_err()); } #[test] fn test_ddw0_error_msg_bad_index() { let raw_ddw0_bad_index = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xE4]; let ddw0_bad = Ddw0::load(&mut raw_ddw0_bad_index.as_slice()).unwrap(); let err = STATUS_WORD_SANITY_CHECKER.check_ddw0(&ddw0_bad).err(); eprintln!("{:?}", err); assert!(err.unwrap().contains("index is not 0")); } #[test] fn test_ddw0_error_msg_bad_id() { let raw_data_ddw0_bad_id = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14]; let ddw0_bad = Ddw0::load(&mut raw_data_ddw0_bad_id.as_slice()).unwrap(); let err = STATUS_WORD_SANITY_CHECKER.check_ddw0(&ddw0_bad).err(); eprintln!("{:?}", err); assert!(err.unwrap().contains("ID is not 0xE4: 0x")); } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Taiyaki Oriental</title> <link rel="stylesheet" href="./style.css"> <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=Inter:wght@100;200;300;400;500;600&family=Jost:wght@100;200;300;400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://unpkg.com/boxicons@latest/css/boxicons.min.css"> </head> <body> <header> <a href="#" class="logo"><img src="./assets/logo2.png" alt=""></a> <ul class="navmenu"> <li><a href="/restaurant">Home</a></li> <li><a href="/restaurant/pages/about">Sobre</a></li> <li><a href="/restaurant/pages/contact">Contato</a></li> <li><a href="/restaurant/pages/careers">Trabalhe Conosco</a></li> </ul> <div class="nav-icon"> <div class="buscar-box"> <div class="lupa-buscar"> <i class='bx bx-search' onclick="goToProducts()"></i> </div> <div class="input-buscar"> <input id="searchbar" onkeyup="search()" type="text" name="search" placeholder="Pesquisar.."> </div> <div class="btn-fechar"> <i class="bx bx-x"></i> </div> </div> <a href="#"><i class='bx bx-user'></i></a> <a href="#"><i class='bx bx-cart'></i></a> <div class="bx bx-menu" id="menu-icon"></div> </div> </header> <section class="main-home"> <div class="main-text"> <h5>Comidas Japonesas</h5> <h1>Sabores autênticos<br> do Japão</h1> <p>Delícias do oriente a sua mesa.</p> <a href="#trending" class="main-btn">Compre agora <i class='bx bx-right-arrow-alt' ></i></a> </div> <div class="down-arrow"> <a href="#trending" class="down"><i class='bx bx-down-arrow-alt'></i></a> </div> </section> <section class="trending-product" id="trending"> <div class="center-text"> <h2>Nossos<span> produtos</span> em destaque</h2> </div> <div class="products"> <div class="row" onclick="selectProduct(1)"> <img src="./assets/biscuit.jpg" alt=""> <div class="product-text"> <h5>Novo</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> </div> <div class="price"> <h4>Biscoito de Chocolate Miffy</h4> <p>R$10,00</p> </div> </div> <div class="row" onclick="selectProduct(2)"> <img src="./assets/tayaki.jpg" alt=""> <div class="product-text"> <h5>Novo</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Taiyaiki com sorvete de baunilha</h4> <p>R$10,00</p> </div> </div> <div class="row" onclick="selectProduct(3)"> <img src="./assets/coffee.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> </div> <div class="price"> <h4>Café do Totoro</h4> <p>R$4,00</p> </div> </div> <div class="row" onclick="selectProduct(4)"> <img src="./assets/temaki.jpg" alt=""> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> </div> <div class="price"> <h4>Temaki - Salmão com cream cheese</h4> <p>R$25,00</p> </div> </div> <div class="row" onclick="selectProduct(5)"> <img src="./assets/onigiri.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Onigiri</h4> <p>R$5,00</p> </div> </div> <div class="row" onclick="selectProduct(6)"> <img src="./assets/Miso.jpg" alt=""> <div class="product-text"> <h5>Oferta</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Miso</h4> <p>R$30,00</p> </div> </div> <div class="row" onclick="selectProduct(7)"> <img src="./assets/bubble tea.jpg" alt=""> <div class="product-text"> <h5>Oferta</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> </div> <div class="price"> <h4>Bubble tea de nuvem</h4> <p>R$10,00</p> </div> </div> <div class="row" onclick="selectProduct(8)"> <img src="./assets/omorice.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Omorice</h4> <p>R$10,00</p> </div> </div> <div class="row" onclick="selectProduct(9)"> <img src="./assets/mochi.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Mochi</h4> <p>R$5,00</p> </div> </div> <div class="row" onclick="selectProduct(10)"> <img src="./assets/cinnamonroll.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Sorvete temático Cinnamonroll</h4> <p>R$5,00</p> </div> </div> <div class="row" onclick="selectProduct(11)"> <img src="./assets/nikuman.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Nikuman de carne</h4> <p>R$5,00</p> </div> </div> <div class="row" onclick="selectProduct(12)"> <img src="./assets/dango.jpg" alt=""> <div class="product-text"> <h5>Mais vendidos</h5> </div> <div class="heart-icon"> <i class='bx bx-heart' ></i> </div> <div class="ratting"> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star' ></i> <i class='bx bxs-star-half' ></i> </div> <div class="price"> <h4>Dango de três cores</h4> <p>R$5,00</p> </div> </div> </div> </section> <section class="contact"> <div class="contact-info"> <div class="first-info"> <img src="./assets/logo2.png" alt=""> <p>Potato Chips - 123</p> <p>Japan-JP</p> <p>010101010101</p> <p>[email protected]</p> <div class="socials-icon"> <a href="#"><i class='bx bxl-facebook-circle' ></i></a> <a href="#"><i class='bx bxl-twitter' ></i></a> <a href="#"><i class='bx bxl-instagram' ></i></a> <a href="#"><i class='bx bxl-youtube' ></i></a> <a href="#"><i class='bx bxl-linkedin' ></i></a> </div> </div> <div class="second-info"> <h4>Suporte</h4> <p onclick="location.href='/restaurant/pages/contact';">Contato</p> <p>Sobre a página</p> <p>Guia de tamanho</p> <p>Venda e devolução</p> <p>Privacidade</p> <img class="payments" src="./assets/checkout.avif" alt=""> </div> <div class="third-info"> <h4>Shop</h4> <p>Temaki</p> <p>Café</p> <p>Sorvetes</p> <p>Biscoitos</p> </div> <div class="company"> <h4>Company</h4> <p>Sobre</p> <p>Blog</p> <p>Afiliado</p> <p>Login</p> </div> </div> </section> <div class="end-text"> <p>Copyright ©️ @2023. All Rights Reserved. Design By Lana Ramos.</p> </div> <script src="./script.js"></script> <script src="./utils/header.js"></script> </body> </html>
--Evan Plumley --25SEP2022 --Udacity SQL Deforestation Project Appendix /* Steps to Complete Create a View called “forestation” by joining all three tables - forest_area, land_area and regions in the workspace. The forest_area and land_area tables join on both country_code AND year. The regions table joins these based on only country_code. In the forestation View, include the following: All of the columns of the origin tables A new column that provides the percent of the land area that is designated as forest. Keep in mind that the column forest_area_sqkm in the forest_area table and the land_area_sqmi in the land_area table are in different units (square kilometers and square miles, respectively), so an adjustment will need to be made in the calculation you write (1 sq mi = 2.59 sq km). */ CREATE VIEW forestation AS SELECT f.country_code f_country_code, f.country_name f_country_name, r.region r_region, f.year f_year, r.income_group r_income_group, f.forest_area_sqkm f_area_sqkm, (f.forest_area_sqkm / 2.59) AS f_area_sq_mi, l.total_area_sq_mi l_total_area_sq_mi, (l.total_area_sq_mi * 2.59) AS l_total_area_sqkm, (f.forest_area_sqkm / (l.total_area_sq_mi * 2.59)) * 100 AS percent_forest FROM forest_area f JOIN land_area l ON f.country_code = l.country_code AND f.year = l.year JOIN regions r ON f.country_code = r.country_code; /* 1. GLOBAL SITUATION Instructions: Answering these questions will help you add information into the template. Use these questions as guides to write SQL queries. Use the output from the query to answer these questions. */ /* a. What was the total forest area (in sq km) of the world in 1990? Please keep in mind that you can use the country record denoted as “World" in the region table. */ SELECT f_country_name, f_year, f_area_sqkm FROM forestation WHERE f_country_name = 'World' AND f_year = 1990; -- Result: World 1990 41282694.9 /* b. What was the total forest area (in sq km) of the world in 2016? Please keep in mind that you can use the country record in the table is denoted as “World.” */ SELECT f_country_name, f_year, f_area_sqkm FROM forestation WHERE f_country_name = 'World' AND (f_year = 2016 OR f_year = 1990) ORDER BY f_year ASC; --Result: World 2016 39958245.9 /* c. What was the change (in sq km) in the forest area of the world from 1990 to 2016? d. What was the percent change in forest area of the world between 1990 and 2016? Building this query to answer both questions with a window function */ SELECT f_country_name, f_year, f_area_sqkm, percent_forest, f_area_sqkm - LAG(f_area_sqkm) OVER (ORDER BY f_area_sqkm) AS f_area_difference, ((LAG(percent_forest) OVER (ORDER BY percent_forest) - percent_forest) / percent_forest) * 100 AS percent_forest_diff FROM( SELECT f_country_name, f_year, f_area_sqkm, percent_forest FROM forestation WHERE f_country_name = 'World' AND (f_year = 2016 OR f_year = 1990)) sub; --Result: 1324449 -3.22813528513264 -- Fixed to adress the difference in percentage chnage as opposed to straight percentage difference SELECT f_country_name, f_year, f_area_sqkm, percent_forest, f_area_sqkm - LAG(f_area_sqkm) OVER (ORDER BY f_area_sqkm) AS f_area_difference, ((LAG(f_area_sqkm) OVER (ORDER BY f_area_sqkm) - f_area_sqkm) / f_area_sqkm) * 100 AS percent_forest_diff FROM( SELECT f_country_name, f_year, f_area_sqkm, percent_forest FROM forestation WHERE f_country_name = 'World' AND (f_year = 2016 OR f_year = 1990)) sub; /* e. If you compare the amount of forest area lost between 1990 and 2016, to which countrys total area in 2016 is it closest to? */ SELECT f_country_name, l_total_area_sqkm, l_total_area_sq_mi FROM forestation WHERE l_total_area_sqkm <= 1324449 ORDER BY l_total_area_sqkm DESC LIMIT 1; -- Result: Peru 1279999.9891 494208.49
use std::{collections::HashMap, fs}; fn main() { let input = fs::read_to_string("input.txt").expect("Not a valid file"); let result = parse_input(&input); println!("{result}"); } pub fn lcm(nums: &[usize]) -> usize { if nums.len() == 1 { return nums[0]; } let a = nums[0]; let b = lcm(&nums[1..]); a * b / gcd_of_two_numbers(a, b) } fn gcd_of_two_numbers(a: usize, b: usize) -> usize { if b == 0 { return a; } gcd_of_two_numbers(b, a % b) } fn parse_input(input: &str) -> usize { let (mut instructions, mut map) = ("", ""); if let Some((temp1, temp2)) = input.split_once("\n\n") { (instructions, map) = (temp1, temp2); } else if let Some((temp1, temp2)) = input.split_once("\r\n\r\n") { (instructions, map) = (temp1, temp2); } let instructions_vec: Vec<char> = instructions.chars().collect(); let mut hash_map = HashMap::new(); for line in map.lines() { let (waypoint, decision) = line.split_once('=').unwrap(); let (left, right) = decision.split_once(',').unwrap(); let left = left.trim().replace(['(', ')'], ""); let right = right.trim().replace(['(', ')'], ""); hash_map.insert(waypoint.trim(), (left, right)); } let len = instructions_vec.len(); let mut start_vec = Vec::new(); for key in hash_map.clone() { if key.0.ends_with('A') { start_vec.push(key.0) } } let mut iterations_vec = Vec::new(); for start in start_vec { let mut i = 0; let (mut left, mut right) = hash_map.get(start).unwrap().clone(); loop { let current_instruction = instructions_vec[i % len]; match current_instruction { 'L' => { if left.ends_with('Z') { break; } (left, right) = hash_map.get(left.as_str()).unwrap().clone(); } 'R' => { if right.ends_with('Z') { break; } (left, right) = hash_map.get(right.as_str()).unwrap().clone(); } _ => panic!("Unknow instruction"), } i += 1; } iterations_vec.push(i+1) } lcm(&iterations_vec) } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_1() { let input = "LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX)"; assert_eq!(parse_input(input), 6); } }
Intuition: . This question is almost similar to the 3-Sum original question .These are following differences //Time complexity: O(N^2) //Auxiliary Space: O(1) class Solution { public int threeSumSmaller(int[] nums, int target) { Arrays.sort(nums); int countSmaller = 0; int len = nums.length; for(int indx = 0; indx<len; indx++){ countSmaller += findPairSum(nums, target-nums[indx], indx); } return countSmaller; } private int findPairSum(int nums[], int target, int indx){ int right = nums.length - 1, left = indx+1, smallerCount = 0; while(left < right){ int currSum = nums[left]+nums[right]; if(currSum < target){ smallerCount += right - left; left++; }else if(currSum >= target){ right--; } } return smallerCount; } } -------------------------------------------- class Solution { // Time complexity: O(n^2 * log(n)) public int threeSumSmaller(int[] nums, int target) { Arrays.sort(nums); int countSmaller = 0; int len = nums.length; for(int indx = 0; indx<len; indx++){ countSmaller += findPairSum(nums, target-nums[indx], indx+1); } return countSmaller; } // // Time complexity: O(n*logn) private int findPairSum(int nums[], int target, int startIndx){ int smallerCount = 0; // find largest right such that nums[left] + nums[right] < target, left < right // keeping left fixed, from left to right we can form right - left pairs such that // nums[left] + nums[right] < target, left < right for(int left = startIndx; left<nums.length; left++){ int right = binarySearch(nums, left, target-nums[left]); smallerCount += right-left; } return smallerCount; } // Time complexity: O(logn) private int binarySearch(int nums[], int left, int target){ int right = nums.length-1; while(left < right){ //mid is not left + (right - left) /2 nor (right + left)/2 because when only 2 elements are left with //these loop will never terminate. as lower side will i.e. left will be taken mid always int mid = (left+right+1)/2; if(nums[mid] < target){ left = mid; }else{ right = mid-1; } } return left; } }
package com.company.controller; import com.company.model.EntityType; import com.company.model.Feed; import com.company.model.HostHolder; import com.company.service.FeedService; import com.company.service.FollowService; import com.company.util.JedisAdapter; import com.company.util.RedisKeyUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.ArrayList; import java.util.List; /** * Created by John on 2017/7/16. */ @Controller public class FeedController { @Autowired FeedService feedService; @Autowired HostHolder hostHolder; @Autowired FollowService followService; @Autowired JedisAdapter jedisAdapter; @RequestMapping(path = {"/pushfeeds"}, method = {RequestMethod.GET, RequestMethod.POST}) private String getPushFeeds(Model model) { int localUserId = hostHolder.getUser() != null ? hostHolder.getUser().getId() : 0; List<String> feedIds = jedisAdapter.lrange(RedisKeyUtil.getTimelineKey(localUserId), 0, 10); List<Feed> feeds = new ArrayList<Feed>(); for (String feedId : feedIds) { Feed feed = feedService.getById(Integer.parseInt(feedId)); if (feed != null) { feeds.add(feed); } } model.addAttribute("feeds", feeds); return "feeds"; } @RequestMapping(path = {"/pullfeeds"}, method = {RequestMethod.GET, RequestMethod.POST}) private String getPullFeeds(Model model) { int localUserId = hostHolder.getUser() == null ? 0 : hostHolder.getUser().getId(); List<Integer> followees = new ArrayList<Integer>(); if (localUserId != 0) { followees = followService.getFollowees(EntityType.ENTITY_USER, localUserId, Integer.MAX_VALUE); } List<Feed> feeds = feedService.getUserFeeds(Integer.MAX_VALUE, followees, 10); model.addAttribute("feeds", feeds); return "feeds"; } }
package chap_07; public class BlackBox { // 인스턴스 변수 (서로 다른 객체에서 서로 다른 값을 갖는 것) // 블랙박스라는 클레스는 4개의 인스턴스 변수를 갖는다. // 서로다른 인스턴스가 생성되었을 때 이 변수들은 각각 블랙박스 클래스로 부터 // 만들어진 객체들 마다, 서로 다른 값을 갖을 수 있다. String modelname; String resolution; int price; String color; int serialNumber; // static을 붙이게 되면 = 클레스 변수 // static을 붙이게 되면 클레스가 붙는 모든 객체에 동일하게 적용 // 클레스 변수일 경우 -> 클레스명.변수이름 static boolean canAutoReport = false; static int counter = 0; // 시리얼 번호를 생성해주는 역할(0에서 부터 연산을 통해 증가) // 생성자 만드는 법 // 클레스 명 () {} /* 생성자는 객체가 만들어 질때 자동으로 만들어 지는 부분 어떤 기본 적인 동작이 되어야 한다면 생성자에 명시 객체가 생성됨가 동시에 전달하는 값으로 초기화 하고자 할때 생성자 활용 생성자 간에 서로 호출 -> this(); */ BlackBox(){ // System.out.println("기본 생성자 호출"); // this.serialNumber = ++counter; // System.out.println("새로운 시리얼 넘버를 발급 받았습니다:" + this.serialNumber); } BlackBox(String modelname, String resolution, int price, String color){ // this(); // b2에 serialNumber 기능 추가 = (기본 생성자 호출) // // System.out.println("사용자 정의 생성자 호출"); // this.modelname = modelname; // this.resolution = resolution; // this.price = price; // this.color = color; } // 메소드 정의 // 클레스 내에서 어떤 기능을 정의 & 기능을 객체가 사용 할 수 있음 // 전달값과 반환값 없는 메소드 void autoReport() { if (canAutoReport) { System.out.println("충돌이 감지되어 자동으로 신고합니다"); } else { System.out.println("자동 신고 기능이 지원 되지 않습니다"); } } // 전달 값은 있고 반환 값은 없는 메소드 void insertMemoryCard(int capacity) { System.out.println("메모리 카드가 삽입되었습니다"); System.out.println("용량은" + capacity + "GB 입니다"); } // 전달 값 반환 값 있는 메소드 int getVideoFileCount(int type) { if (type == 1) { // 일반영상 return 9; } else if (type == 2) { // 이벤트 영상 return 1; } return 10; // 타입을 알 수 없을 때 } void record(boolean showDataTime, boolean showSpeed, int min) { System.out.println("녹화를 시작합니다"); if (showDataTime) { System.out.println("영상에 날짜 정보가 표기됩니다"); } if (showSpeed) { System.out.println("영상에 속도 정보가 표기됩니다."); } System.out.println("영상은 " + min + "분 단위로 표기 됩니다."); } //+) 매개변수, 파라미터 타입이 다르면 오버로딩이 가능 // 비슷한 동작을 서로 다른 코드로 작성을 하게 된다면 수정을 둘다 해야 한다 void record() { record(true, true, 5); // 위에 record문의 동작을 갖고 결과를 출력 할 수 있다. } static void callServiceCenter() { System.out.println("서비스 센터(1588-0000) 로 연결합니다."); //modelName = "test"; canAutoReport = false; // static으로 선언한 클레스 변수는 static 메소드에서 바로 사용 가능 // 인스턴스 변수는 객체가 만들어 져야 만들어지는 인스턴스 변수 // 직접 접근이 불가 하다. } void appendModelName(String modelname) { // 인스턴스 변수와 파라미터 이름이 동일할때 // this. 을 붙여주면 클레스의 인스턴스 변수에 직접 접근이 가능 // this.modelname -> 클레스 변수의 인스턴스를 의미 // modelname -> 파라미터로 전달 받은 모델 네임이 된다. this.modelname += modelname; } //Getter (값을 가져오는 메소드) & Setter (값을 설정하는 메소드) String getModelname() { return modelname; } void setModelname(String modelname) { this.modelname = modelname; } String getResolution() { if (resolution == null || resolution.isEmpty()){ return "판매자에게 문의하세요"; } return resolution; } void setResolution(String resolution) { this.resolution = resolution; } int getPrice(){ return price; } void setPrice(int price){ if (price < 100000){ this.price = 100000; }else { this.price = price; } } String getColor(){ return color; } void setColor(String color){ this.color=color; } }
import { html, LitElement } from "lit"; import { classMap } from "lit/directives/class-map.js"; import styles from "./list.styles"; /** * Unordered list * @element adc-unordered-list * @slot - Default slot, expecting adc-list-item */ export class UnorderedList extends LitElement { /** * If there is a parent list item, then the list is nested. */ connectedCallback() { if (this.closest((this.constructor as typeof UnorderedList).selectorListItem)) { this.setAttribute("slot", "nested"); } else { this.removeAttribute("slot"); } super.connectedCallback(); } protected render() { const classes = { "adc-list--nested": this.getAttribute("slot") === "nested" }; return html` <ul class="adc-list--unordered ${classMap(classes)}"> <slot></slot> </ul> `; } /** * @private */ static get selectorListItem() { return "adc-list-item"; } /** * @private */ static styles = styles; } try { customElements.define("adc-unordered-list", UnorderedList); } catch (e) { // do nothing } declare global { interface HTMLElementTagNameMap { "adc-unordered-list": UnorderedList; } }
const restaurant = { name: 'Classico Italiano', location: 'Via Angelo Tavanti 23, Firenze, Italy', categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'], starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'], mainMenu: ['Pizza', 'Pasta', 'Risotto'], order: function (starterIndex, mainIndex) { return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; }, // destructure as parameter orderDelivery: function ({ time = '20:00', address, mainIndex = 0, starterIndex = 1, }) { console.log( `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}` ); }, orderPasta: function (ing1, ing2, ing3) { console.log( `Here is your delicious pasta with ${ing1}, ${ing2} and ${ing3}` ); }, openingHours: { thu: { open: 12, close: 22, }, fri: { open: 11, close: 23, }, sat: { open: 0, // Open 24 hours close: 24, }, }, }; // Property NAMES const properties = Object.keys(restaurant.openingHours); // console.log(properties); let openStr = `We are open on ${properties.length} days: `; for (const day of Object.keys(restaurant.openingHours)) { openStr += `${day}, `; } // console.log(openStr) // Property VALUES const values = Object.values(restaurant.openingHours); // console.log(values) // Entire object const entries = Object.entries(restaurant.openingHours); // console.log(entries) // [key, value] for (const [day, { open, close }] of entries) { console.log(`On ${day} we open at ${open} and close at ${close}`); }
# -*- coding: utf-8 -*- import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 100000 class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=15000) self.gamma = 0.9 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.05 self.epsilon_decay = 0.995 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): # Neural Net for Deep-Q learning Model model = Sequential() model.add(Dense(32, input_dim=self.state_size, activation='relu')) model.add(Dense(32, activation='relu', kernel_initializer='uniform')) model.add(Dense(32, activation='relu', kernel_initializer='uniform')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def act(self, state): if np.random.rand() <= self.epsilon: return env.action_space.sample() act_values = self.model.predict(state) return np.argmax(act_values[0]) # returns action def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target = reward + self.gamma * \ np.amax(self.model.predict(next_state)[0]) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if reward > 100: print("NICE WORK MATE: {}".format(reward)) # target = self.model.predict(state) # if done: # target[0][action] = reward # else: # target[0][action] = reward + self.gamma * \ # np.max(self.model.predict(next_state)[0]) # self.model.fit(state, target, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay def load(self, name): self.model.load_weights(name) def save(self, name): self.model.save_weights(name) if __name__ == "__main__": env = gym.make('LunarLander-v2') state_size = env.observation_space.shape[0] action_size = env.action_space.n agent = DQNAgent(state_size, action_size) #agent.load("./save/lunarlander.h5") done = False batch_size = 128 # for e in range(1000): # state = env.reset() # state = np.reshape(state, [1, state_size]) # reward_total = 0 # for time in range(500): # action = env.action_space.sample() # next_state, reward, done, _ = env.step(action) # reward_total += reward # next_state = np.reshape(next_state, [1, state_size]) # agent.remember(state, action, reward, next_state, done) # state = next_state # if done: # break # # if len(agent.memory) > batch_size: # # agent.replay(batch_size) # print("Observation: {}".format(e)) for e in range(EPISODES): state = env.reset() state = np.reshape(state, [1, state_size]) reward_total = 0 for time in range(500): if(e%100 == 0): env.render() action = agent.act(state) next_state, reward, done, _ = env.step(action) reward_total+=reward next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: break print("episode: {}/{}, score: {}, e: {:.2}, memory: {}" .format(e, EPISODES, reward_total, agent.epsilon, len(agent.memory))) if len(agent.memory) > batch_size: agent.replay(batch_size) if e % 10 == 0: agent.save("./save/lunarlander.h5")
declare interface AccessToken { access_token: string, refresh_token: string, token_type: string, expires_in: number, scope: string, refresh_token_expires_in: number } declare interface UserPrincipals { authToken: string, userId: string, userCdDomainId: string, primaryAccountId: string, lastLoginTime: string, tokenExpirationTime: string, loginTime: string, accessLevel: string, stalePassword: boolean, streamerInfo: { streamerBinaryUrl: string, streamerSocketUrl: string, token: string, tokenTimestamp: string, userGroup: string, accessLevel: string, acl: string, appId: string }, professionalStatus: string, quotes: { isNyseDelayed: boolean, isNasdaqDelayed: boolean, isOpraDelayed: boolean, isAmexDelayed: boolean, isCmeDelayed: boolean, isIceDelayed: boolean, isForexDelayed: boolean }, streamerSubscriptionKeys:{ keys:{ [index:number]:{ key:string } } }, accounts:{ [index:number]:{ accountId: string, description: string, displayName: string, accountCdDomainId: string, company: string, segment: string, surrogateIds: object, preferences: { expressTrading: boolean, directOptionsRouting: boolean, directEquityRouting: boolean, defaultEquityOrderLegInstruction: string, defaultEquityOrderType: string, defaultEquityOrderPriceLinkType: string, defaultEquityOrderDuration: string, defaultEquityOrderMarketSession: string, defaultEquityQuantity: number, mutualFundTaxLotMethod: string, optionTaxLotMethod: string, equityTaxLotMethod: string, defaultAdvancedToolLaunch: string, authTokenTimeout: string, }, acl: string, authorizations: { apex: false, levelTwoQuotes: boolean, stockTrading: boolean, marginTrading: boolean, streamingNews: boolean, optionTradingLevel: string, streamerAccess: boolean, advancedMargin: boolean, scottradeAccount: boolean } } } } declare interface Watchlists { [index:number]:{ name: string, watchlistId: string, accountId: string, status: string, watchlistItems:{ [index:number]:watchlistItem } } } declare interface watchlistItem { sequenceId: number, quantity: number, averagePrice: number, commission: number, purchasedDate: Date, instrument: Instrument, status: string } declare interface Instrument{ symbol: string, description: string, assetType: string, cusip: string, putCall: string, underlyingSymbol: string } declare interface SecuritiesAccount{ securitiesAccount:{ type: string, accountId: string, roundTrips: number, isDayTrader: boolean, isClosingOnlyRestricted: boolean, positions: Position[], initialBalances:{ accountValue: number, cashBalance: number } } } declare interface Position{ shortQuantity: number, averagePrice: number, currentDayProfitLoss: number, currentDayProfitLossPercentage: number, longQuantity: number, settledLongQuantity: number, settledShortQuantity: number, instrument: Instrument, marketValue: number }
import dataclasses import pathlib from typing import List # mypy: no_warn_unused_ignores try: from importlib import metadata as import_metadata # type: ignore except ImportError: # metadata is added to importlib in CPython 3.8 # See https://pypi.org/project/importlib-metadata/ import importlib_metadata as import_metadata # type: ignore @dataclasses.dataclass class EntrypointDetails: program_name: str program_version: str cli_command: str class VersionCaller: """Find the version of this package""" def get_version(self) -> str: return import_metadata.version("ilmn-pelops") class CliIntrospection: def __init__(self, version_caller: VersionCaller, cli_args: List[str]): self._version_caller = version_caller self._cli_args = cli_args def get_entrypoint_details(self) -> EntrypointDetails: version = self._version_caller.get_version() command = " ".join(self._cli_args) program_name = pathlib.Path(self._cli_args[0]).name result = EntrypointDetails( program_name=program_name, program_version=version, cli_command=command ) return result
import React from "react"; export type RatingValueType = 0|1|2|3|4|5 type RatingPropsType = { value: RatingValueType onClick: (value: RatingValueType)=>void } export function Rating(props: RatingPropsType) { return ( <div> <Star selected={props.value >= 1} onClick={props.onClick} value={1}/> <Star selected={props.value >= 2} onClick={props.onClick} value={2}/> <Star selected={props.value >= 3} onClick={props.onClick} value={3}/> <Star selected={props.value >= 4} onClick={props.onClick} value={4}/> <Star selected={props.value >= 5} onClick={props.onClick} value={5}/> </div> ) } type StarPropsType = { selected: boolean; onClick: (value: RatingValueType)=> void; value: RatingValueType; } function Star(props: StarPropsType) {return <span onClick={()=>props.onClick(props.value)}>{props.selected ? <b>star </b> : "star "}</span>}
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('empresas', function (Blueprint $table) { $table->id()->comment('Identificador único'); $table->unsignedBigInteger('caso_id')->comment('ID del caso al que esta relacionado'); $table->string('nombre_comercial',500)->nullable()->comment('nombre comercial de la empresa'); $table->string('razon_social',500)->nullable()->comment('razon social de la empresa'); $table->string('correo',500)->nullable()->comment('correo electrónico de la empresa'); $table->string('telefono',50)->nullable()->comment('telefono de la empresa'); $table->timestamps(); $table->softDeletes(); $table->foreign('caso_id') ->references('id') ->on('casos') ->onDelete('cascade') ->onUpdate('cascade'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('empresas'); } };
import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.gridspec as gridspec import seaborn as sns # Load data lag_data = pd.read_csv('sen_avg_lag_prio.csv') throughput_data = pd.read_csv('sen_avg_throughput_topic_priority.csv') overhead_throughput_data = pd.read_csv('sen_avg_overhead_throughput_topic_priority.csv') # Adjust file names and merge datasets lag_data = lag_data.rename(columns={'FileName': 'File'}) lag_data['File'] = lag_data['File'].str.replace('_consumer_count.csv', '_message_throughput.csv') merged_data = pd.merge(lag_data, throughput_data, on='File') overhead_throughput_data['File'] = overhead_throughput_data['File'].str.replace('_overhead_throughput.csv', '_message_throughput.csv') merged_data_3d = pd.merge(merged_data, overhead_throughput_data, on='File', suffixes=('', '_overhead')) # Compute 3D Pareto front def pareto_front_3d(data): data = data.sort_values(by=['avg_lag', 'Average Throughput', 'Average Throughput_overhead'], ascending=[True, False, True]) pareto_data = [] max_throughput = float("-inf") min_overhead = float("inf") for _, row in data.iterrows(): if row['Average Throughput'] >= max_throughput and row['Average Throughput_overhead'] <= min_overhead: pareto_data.append(row) max_throughput = row['Average Throughput'] min_overhead = row['Average Throughput_overhead'] return pd.DataFrame(pareto_data) pareto_data_3d = pareto_front_3d(merged_data_3d) print(pareto_data_3d) dummy_text_data_3d = { "sen_2_message_throughput.csv": "2", "sen_4_message_throughput.csv": "4", "sen_11_message_throughput.csv": "11", "sen_9_message_throughput.csv": "9", "sen_16_message_throughput.csv": "16", } # remove the pareto data from the merged data merged_data_3d = merged_data_3d[~merged_data_3d['File'].isin(pareto_data_3d['File'])] print(merged_data_3d) # 3D visualization sns.set_style('whitegrid') sns.set_context('talk') fig = plt.figure(figsize=(14, 12)) ax = fig.add_subplot(111, projection='3d') # Setting axis limits ax.set_xlim([0.85, 0.95]) ax.set_ylim([0.5, 2.55]) ax.set_zlim([5, 15]) ax.scatter(pareto_data_3d['Average Throughput'], pareto_data_3d['avg_lag'], pareto_data_3d['Average Throughput_overhead'], color='red', s=150, edgecolors='k', depthshade=False, label='Pareto Front', zorder=10) ax.scatter(merged_data_3d['Average Throughput'], merged_data_3d['avg_lag'], merged_data_3d['Average Throughput_overhead'], color='blue', s=50, alpha=0.5, label='All Data Points', zorder=0, marker='o') # Draw lines from Pareto front points to the axes (within the limits) for _, row in pareto_data_3d.iterrows(): ax.plot([row['Average Throughput'], row['Average Throughput']], [row['avg_lag'], row['avg_lag']], [row['Average Throughput_overhead'], ax.get_zlim()[0]], color='grey', linestyle='--', linewidth=0.8) ax.plot([row['Average Throughput'], row['Average Throughput']], [row['avg_lag'], ax.get_ylim()[0]], [ax.get_zlim()[0], ax.get_zlim()[0]], color='grey', linestyle='--', linewidth=0.8) ax.plot([row['Average Throughput'], ax.get_xlim()[1]], [row['avg_lag'], row['avg_lag']], [ax.get_zlim()[0], ax.get_zlim()[0]], color='grey', linestyle='--', linewidth=0.8) ax.plot_trisurf(pareto_data_3d['Average Throughput'], pareto_data_3d['avg_lag'], pareto_data_3d['Average Throughput_overhead'], color='red', alpha=0.3, shade=False, linewidth=0.1, zorder=5) for _, row in pareto_data_3d.iterrows(): ax.text(row['Average Throughput'], row['avg_lag']+0.18, row['Average Throughput_overhead'], dummy_text_data_3d[row['File']], fontsize=12, ha='left', va='top', color='k', fontweight='bold', zorder=10, bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) ax.set_xlabel('Average Throughput (messages/second)', labelpad=14) ax.set_ylabel('Inconsistency (seconds)', labelpad=14) ax.set_zlabel('Average Overhead Throughput (Dyconit messages/second)', labelpad=16) ax.legend(loc='upper left', fontsize=10) ax.view_init(elev=25, azim=-70) plt.tight_layout() # Save figure plt.savefig(f'../e5/pareto3d_priority.png', bbox_inches='tight', pad_inches=0.05, dpi=300)
Redis Cache 1) What is Cache ? 2) Why we need to go for Cache ? 3) What is Redis ? 4) Spring Boot with Redis Integration => Cache is a temporary storage => Cache will represent data in key-value format => By using Cache data, we can reduce no.of db calls from our application. Note: DB call is always costly (it will take more time to execute) => By using Cache data (Cache Memory) we can increase performance of the application. ##### Redis Cache is one of the most famous Cache available in Market ##### => The open source, in-memory data store used by millions of developers as a database, cache, streaming engine, and message broker. => Spring Boot provided below starter to communicate with Redis Server ### springboot-starter-redis ### => We will use below components to communicate with Redis Server 1) JedisConnectionFactory : It represents connection with Redis Server 2) RedisTemplate : It provides methods to perform operations with Redis Server 3) OpsForHash: It is providing methods to peform operations based on Hash key put (...) get(..) entries (.) deleet(..) Spring Boot with Redis Integration 0) Download Redis Server Link : https://www.mediafire.com/file/ul4aeeirc8nrs2a/Redis-x64-3.0.504.rar/file -> Extract rar file and Run Redis-Server.exe and Run Redis-Client.exe 1) Create Spring Boot application with below dependencies <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> 2) Create binding class to represent data @Data public class Country implements Serializable { private Integer sno; private String name; private String countryCode; } 3) Create Redis Config Class @Configuration public class RedisConfig { @Bean public JedisConnectionFactory jedisConn() { JedisConnectionFactory jedis = new JedisConnectionFactory(); // Redis server properties return jedis; } @Bean public RedisTemplate<String, Country> redisTemplate() { RedisTemplate<String, Country> rt = new RedisTemplate<>(); rt.setConnectionFactory(jedisConn()); return rt; } } 4) Create RestController class with Requird methods @RestController public class CountryRestController { private HashOperations<String, Integer, Country> opsForHash = null; public CountryRestController(RedisTemplate<String, Country> rt) { this.opsForHash = rt.opsForHash(); } @PostMapping("/country") public String addCountry(@RequestBody Country country) { opsForHash.put("COUNTRIES", country.getSno(), country); return "Country Added"; } @GetMapping("/countries") public Collection<Country> getCountries() { Map<Integer, Country> entries = opsForHash.entries("COUNTRIES"); Collection<Country> values = entries.values(); return values; } } 5) Run the application and test it using Postman. { "sno": 1, "name": "India", "countryCode": "+91" }
#ifndef WEBLOADOBSERVER_H #define WEBLOADOBSERVER_H #include <QObject> class HistoryManager; class WebWidget; /** * @class WebLoadObserver * @brief Observes a \ref WebWidget , waiting for a loadFinished() signal so it may * notify the \ref HistoryManager of such an event. */ class WebLoadObserver : public QObject { Q_OBJECT public: /// Constructs the load observer given a pointer to the history manager and the observer's parent explicit WebLoadObserver(HistoryManager *historyManager, WebWidget *parent); private Q_SLOTS: /// Handles the load finished event - notifying the history manager if the load was a success void onLoadFinished(bool ok); private: /// Pointer to the application's history manager HistoryManager *m_historyManager; /// Pointer to the web widget that this object is observing WebWidget *m_webWidget; }; #endif // WEBLOADOBSERVER_H
import useUserStore from "@/store/store"; import axios from "axios"; import { useRouter } from "next/navigation"; import React, { useState } from "react"; import { IoClose } from "react-icons/io5"; import { MdLabelImportant } from "react-icons/md"; import Cookies from "js-cookie"; interface Task { _id: any; taskName: string; taskDescription: string; date: string; pending: boolean; important: boolean; } interface TaskInterface { tasks: Task[]; } const TaskBox: React.FC<TaskInterface> = ({ tasks }) => { const [loading, setLoading] = useState(false); const { setRefresh, userId } = useUserStore(); const router = useRouter(); const token = Cookies.get("user"); const handleComplete = async (id: any) => { try { setLoading(true); const res = await axios.patch( `https://halo-task-backend.onrender.com/api/v1/task?id=${id}` ); console.log(res.data); setRefresh(); router.refresh(); } catch (error: any) { console.log(error.message); } finally { setLoading(false); } }; const handleDelete = async (id: any) => { try { // setLoading(true); const res = await axios.delete( `https://halo-task-backend.onrender.com/api/v1/task?id=${id}`, { headers: { Authorization: `Bearer ${token}`, }, } ); console.log(res.data); setRefresh(); } catch (error: any) { console.log(error.message); } finally { // setLoading(false); } }; return ( <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 w-full"> {tasks.map((task, index) => ( <div key={index} className="flex flex-col px-4 py-4 justify-center shadow-sm shadow-slate-300 mb-6 w-full rounded border-l-4 border-l-orange-text relative" > <IoClose size={20} className="absolute top-0 right-0 cursor-pointer font-extrabold text-gray-400" onClick={() => handleDelete(task?._id)} /> <p className="text-halo-green flex items-center justify-between mt-4"> {task.taskName}{" "} {task.important && ( <MdLabelImportant size={20} className="text-orange-text" /> )} </p> <p className="text-base mt-2">{task.taskDescription}</p> <div className="flex flex-row justify-between items-center pt-4 text-sm text-gray-500"> <p>{task.date.split("T")[0]}</p> <button onClick={() => task.pending && handleComplete(task?._id)} disabled={loading} className={`border border-orange-text rounded-full p-2 cursor-pointer text-black disabled:opacity-50 transition-all ${ task.pending ? "visible" : "text-white bg-orange-text" }`} > {loading ? "Hold On..." : !task.pending ? "Completed" : "Mark as Done"} </button> </div> </div> ))} </div> ); }; export default TaskBox;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> @extends('layouts.app') @section('content') <meta name="csrf-token" content="{{ csrf_token() }}"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home </a> </li> <li class="nav-item"> <a href="#" id = "add-course" class="nav-link ">Create Course</a> </li> <li class="nav-item"> <a href="#" id = "add-post" class="nav-link">Create Post</a> </li> <li class="nav-item"> <a href="" id = "export-csv" class="nav-link" >Export CSV</a> </li> </ul> </div> </nav> </div> <div class="card-body"> <form method="POST" action = "/edit" > @csrf <div class="row mb-3"> <label for="search" class="col-md-4 col-form-label text-md-end">{{ __('Search') }}</label> <div class="col-md-6"> <input id="Search" type="text" class="form-control @error('Search') is-invalid @enderror" name="Search" value="{{ old('Search Student') }}" required autocomplete="email" autofocus> @error('Search') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="Search btn btn-primary"> {{ __('Search') }} </button> </div> </div> </form> </div> <div class="card-body results" style = "display: none;"> <div class="row mb-3"> <h4 class="text-center">This is Student results below</h4> <table id="mt" class="table table-hover"> <thead> <tr> <th>#</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> </div> </div> </div> <div class="modal" id = "edit-student-modal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title student-name"> </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row mb-3"> <span class="badge badge-success" style="display: none;">Success</span> <label for="Name" class="col-md-4 col-form-label text-md-end">{{ __('Name') }}</label> <input id="id" type="hidden" > <div class="col-md-6"> <input id="Name" type="text" class="form-control" name="Name"> </div> <label for="Email" class="col-md-4 col-form-label text-md-end">{{ __('Email') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control" name="email"> </div> <label for="MobileNumber" class="col-md-4 col-form-label text-md-end">{{ __('Mobile') }}</label> <div class="col-md-6"> <input id="MobileNumber" type="MobileNumber" class="form-control" name="MobileNumber"> </div> <label for="lectureHandouts" class="col-md-4 col-form-label text-md-end">{{ __('Lecture Hand outs') }}</label> <div class="col-md-6"> <input id="lectureHandouts" type="lectureHandouts" class="form-control" name="lectureHandouts"> </div> <label for="department" class="col-md-4 col-form-label text-md-end">{{ __('Department') }}</label> <div class="col-md-6"> <input id="department" type="department" class="form-control" name="department"> </div> <label for="supplyBooks" class="col-md-4 col-form-label text-md-end">{{ __('Books') }}</label> <div class="col-md-6"> <input id="supplyBooks" type="supplyBooks" class="form-control" name="supplyBooks"> </div> <label for="methodofPayment" class="col-md-4 col-form-label text-md-end">{{ __('Payment Type') }}</label> <div class="col-md-6"> <input id="methodofPayment" type="methodofPayment" class="form-control" name="methodofPayment"> </div> <label for="collegeChoice" class="col-md-4 col-form-label text-md-end">{{ __('College') }}</label> <div class="col-md-6"> <input id="collegeChoice" type="collegeChoice" class="form-control" name="collegeChoice"> </div> <label for="addressLine1" class="col-md-4 col-form-label text-md-end">{{ __('Address Line 1') }}</label> <div class="col-md-6"> <input id="addressLine1" type="addressLine1" class="form-control" name="addressLine1"> </div> <label for="addressLine2" class="col-md-4 col-form-label text-md-end">{{ __('Address Line 2') }}</label> <div class="col-md-6"> <input id="addressLine2" type="addressLine2" class="form-control" name="addressLine2"> </div> <label for="Country" class="col-md-4 col-form-label text-md-end">{{ __('Country') }}</label> <div class="col-md-6"> <input id="Country" type="Country" class="form-control" name="Country"> </div> <label for="eirCode" class="col-md-4 col-form-label text-md-end">{{ __('Eircode') }}</label> <div class="col-md-6"> <input id="eirCode" type="eirCode" class="form-control" name="eirCode"> </div> <label for="module-0" class="col-md-4 col-form-label text-md-end">{{ __('Module 0') }}</label> <div class="col-md-6"> <input id="module-0" type="module-0" class="form-control" name="module-0"> </div> <label for="module-1" class="col-md-4 col-form-label text-md-end">{{ __('Module 1') }}</label> <div class="col-md-6"> <input id="module-1" type="module-1" class="form-control" name="module-1"> </div> <label for="module-2" class="col-md-4 col-form-label text-md-end">{{ __('Module 2') }}</label> <div class="col-md-6"> <input id="module-2" type="module-2" class="form-control" name="module-2"> </div> <label for="module-3" class="col-md-4 col-form-label text-md-end">{{ __('Module 3') }}</label> <div class="col-md-6"> <input id="module-3" type="module-4" class="form-control" name="module-3"> </div> <label for="module-4" class="col-md-4 col-form-label text-md-end">{{ __('Module 4') }}</label> <div class="col-md-6"> <input id="module-4" type="module-0" class="form-control" name="module-4"> </div> </div> </div> <div class="alert alert-success text-center" role="alert" style="display: none;"> Student data saved </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary save-edit">Save changes</button> </div> </div> </div> </div> <div class="modal" id = "send-sms-modal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title send-sms"> </h5> <div class="modal-body"> <div class="row mb-3"> <label for="sms-number" class="col-md-4 col-form-label text-md-end">{{ __('Student Mobile') }}</label> <div class="col-md-6"> <input id="sms-number" type="text" class="form-control" name="sms-number"> </div> <label for="Student-name" class="col-md-4 col-form-label text-md-end">{{ __('Student Name') }}</label> <div class="col-md-6"> <input id="Student-name" type="text" class="form-control" name="Student-name"> </div> <label for="student-subject" class="col-md-4 col-form-label text-md-end">{{ __('Subject') }}</label> <div class="col-md-6"> <input id="student-subject" type="text" class="form-control" name="student-subject"> <input id="student-id-sms" type="text" class="form-control" name="student-id-sms"> </div> <label for="sms-body" class="col-md-4 col-form-label text-md-end">{{ __('Message for Student') }}</label> <div class="col-md-6"> <textarea class="form-control" id="sms-body" name="sms-body" rows="4" cols="50"> </textarea> </div> </div> </div> </div> <div class="alert alert-success sms-alert text-center" role="alert" style="display: none;"> SMS sent </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary save-sms-send">Send SMS</button> </div> </div> </div> </div> <div class="modal" id = "create-course" tabindex="-1" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> </div> <div class="modal-body"> <label for="course-name" class="col-md-4 col-form-label text-md-end">{{ __('Course Name') }}</label> <div class="col-md-6"> <input id="course-name" type="text" class="form-control" name="course-name"> </div> <label for="Subject" class="col-md-4 col-form-label text-md-end">{{ __('Subject') }}</label> <div class="col-md-6"> <input id="subject-course" type="text" class="form-control" name="subject-course"> </div> </div> <div class="alert alert-success course-created text-center" role="alert" style="display: none;"> Course Added </div> <div class="modal-footer"> <button type="button" class="btn btn-primary save-course">Create course</button> <button type="button" class="btn btn-secondary course-close" data-dismiss="modal"aria-label="Close">Close</button> </div> </div> </div> </div> <div class="modal" id = "create-post" tabindex="-1" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Create Post</h5> </div> <div class="modal-body"> <label for="course-name" class="col-md-4 col-form-label text-md-end">{{ __('Post Title') }}</label> <div class="col-md-6"> <input id="post-name" type="text" class="form-control" name="post-name"> </div> <label for="Subject" class="col-md-4 col-form-label text-md-end">{{ __('Subject') }}</label> <div class="col-md-6"> <input id="post-subject" type="text" class="form-control" name="post-subject"> </div> <label for="Subject" class="col-md-4 col-form-label text-md-end">{{ __('Post Content') }}</label> <div class="col-md-6"> <textarea class="form-control" id="post-content" name="post-content" rows="4" cols="50"> </textarea> </div> </div> <div class="alert alert-success post-created text-center" role="alert" style="display: none;"> Post Added </div> <div class="modal-footer"> <button type="button" class="btn btn-primary save-post">Create post</button> <button type="button" class="btn btn-secondary post-close" data-dismiss="modal"aria-label="Close">Close</button> </div> </div> </div> </div> <div class="modal" id = "export-to-csv" tabindex="-1" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Export to CSV</h5> </div> <div class="filter container"> <div class="col-4" class="text-center" > <div class="row"> <label for="course-select-export" >{{ __('Select Course') }}</label> <select class="form-select" id ="course-select-export"name = "course-select-export" > @isset($coursesNames) <option disabled selected value> -- select an option -- </option> @foreach($coursesNames as $course) <option value="{{$course->name}}">{{$course->name}}</option> @endforeach @endisset </select> </div> </div> </div> <div class="card-body export-results" > <div class="row mb-3"> <h4 class="text-center csv-header"></h4> <table id="student-export-table" class="table table-hover"> <thead> <tr> <th>Select All <span class= "st-count"> </span> <input class="form-check-input select-all" type="checkbox"> </th> <th>Name</th> <th>Email</th> <th>Course</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary export">Export</button> </div> </div> </div> </div> </div> </div> </div> @endsection <script> $( document ).ready(function() { $( ".Search" ).click(function(e) { e.preventDefault(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); var search = $('#Search').val(); $.ajax({ type:'POST', url:"/edit", data:{search:search}, success:function(data){ $('.results').fadeIn(); var json = JSON.parse(data); for (let i = 0; i < json.length; i++) { var studentId = '<input type = "hidden" value = "'+json[i]['id']+'" class="get-id"> '; var stundeditIcon = '<img class ="edit-student"src="/Icons/edit.png" style = "max-height:25px;" >'; var sendSMS = '<img class ="send-sms" src="/Icons/sms-icon.svg" style = "max-height:25px;" >'; ; var row = $('<tr><td >'+json[i]['id']+'</td><td>'+json[i]['name']+'</td><td>'+json[i]['email']+'</td><td> '+stundeditIcon+' </td><td> '+sendSMS+' </td><td> '+studentId+' </td></tr>'); $("#mt > tbody").append(row); } } }); }); $(document).on('click','.edit-student',function(){ $('#edit-student-modal').modal('show'); var index = $(".edit-student").index(this)+1; var id = $(this).closest('tr').find('.get-id').val(); $.ajax({ type:'POST', url:"/showStudent", data:{id:id}, success:function(data){ $('#edit-student-modal').modal('show'); var student = $.parseJSON(data); $('.student-name').html('Your are Editing '+student[0].name); $('#Name').val(student[0].name); $('#id').val(student[0].id); $('#email').val(student[0].email); $('#MobileNumber').val(student[0].MobileNumber); $('#lectureHandouts').val(student[0].lectureHandouts); $('#department').val(student[0].department); $('#supplyBooks').val(student[0].supplyBooks); $('#methodofPayment').val(student[0].methodofPayment); $('#collegeChoice').val(student[0].collegeChoice); $('#addressLine1').val(student[0].addressLine1); $('#addressLine2').val(student[0].addressLine2); $('#Country').val(student[0].Country); $('#eirCode').val(student[0].eirCode); $('#module-0').val(student[0].module_0); $('#module-1').val(student[0].module_1); $('#module-2').val(student[0].module_2); $('#module-3').val(student[0].module_3); $('#module-4').val(student[0].module_4); } }); }); $(document).on('click','.save-edit',function(e){ e.preventDefault(); var id = $('#id').val(); var name = $('#Name').val(); var email = $('#email').val(); var mobile = $('#MobileNumber').val(); var department = $('#department').val(); var lectureHandouts = $('#lectureHandouts').val(); var supplyBooks = $('#supplyBooks').val(); var methodofPayment = $('#methodofPayment').val(); var collegeChoice = $('#collegeChoice').val(); var addressLine1 = $('#addressLine1').val(); var addressLine2 = $('#addressLine2').val(); var Country = $('#Country').val(); var eirCode = $('#eirCode').val(); var module0 = $('#module-0').val(); var module1 = $('#module-1').val(); var module2 = $('#module-2').val(); var module3 = $('#module-3').val(); var module4 = $('#module-4').val(); $.ajax({ type:'POST', url:"/update-student", data:{ id:id, name:name, email:email, mobile:mobile, department:department, lectureHandouts:lectureHandouts, supplyBooks:supplyBooks, methodofPayment:methodofPayment, collegeChoice:collegeChoice, addressLine1:addressLine1, addressLine2:addressLine2, Country:Country, eirCode:eirCode, module0:module0, module1:module1, module2:module2, module3:module3, module4:module4, }, success:function(student){ var student = $.parseJSON(student); $('.alert-success').text(student.name+' has been updated'); $('.alert-success').fadeIn().delay(1000).fadeOut(); } }); }); $(document).on('click','.send-sms',function(e){ e.preventDefault(); var index = $(".edit-student").index(this)+1; var id = $(this).closest('tr').find('.get-id').val(); var smsbody = $('#sms-body').val(); var studentsubject = $('#student-subject').val(); $('#send-sms-modal').modal('show'); $.ajax({ type:'POST', url:"/sms-info", data:{ id:id, smsbody:smsbody, studentsubject:studentsubject, }, success:function(studentSms){ var studentSms = $.parseJSON(studentSms); $('#Student-name').val(studentSms.name); $('#sms-number').val(studentSms.MobileNumber); $('#student-id-sms').val(id); } }); }); $(document).on('click','.save-sms-send',function(e){ e.preventDefault(); var id = $('#student-id-sms').val(); var smsbody = $('#sms-body').val(); var studentsubject = $('#student-subject').val(); var mobile = $('#sms-number').val() $('.sms-alert').html('SMS sent to '+mobile); $.ajax({ type:'POST', url:"/send-sms", data:{ id:id, mobile:mobile, smsbody:smsbody, studentsubject:studentsubject, }, success:function(sms){ $('.sms-alert').fadeIn().delay(1000).fadeOut(); } }); }); $(document).on('click','#add-course',function(e){ $('#create-course').modal('show'); }); $(document).on('click','#add-post',function(e){ $('#create-post').modal('show'); }); $(document).on('click','.course-close',function(e){ $('#create-course').modal('hide'); }); $(document).on('click','.post-close',function(e){ $('#create-post').modal('hide'); }); $(document).on('click','.course-close',function(e){ $('#create-course').modal('hide'); }); $(document).on('click','.select-all',function(e){ if ($(this).is(":checked")){ $('.studentInfoExport').prop('checked', true); }else{ $('.studentInfoExport').prop('checked', false); } }); $(document).on('click','.save-course',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); $('#create-course').modal('show'); var courseName = $('#course-name').val(); var subjectCourse = $('#subject-course').val(); $.ajax({ type:'POST', url:"/view-course", data:{ courseName:courseName, subjectCourse:subjectCourse, }, success:function(course){ $('.course-created').fadeIn().delay(1000).fadeOut(); } }); }); $(document).on('click','.save-post',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); $('#create-course').modal('show'); var postName = $('#post-name').val(); var subjectPost = $('#post-subject').val(); var contentPost = $('#post-content').val(); $.ajax({ type:'POST', url:"/createPosts", data:{ postName:postName, subjectPost:subjectPost, contentPost:contentPost, }, success:function(post){ $('.post-created').fadeIn().delay(1000).fadeOut(); } }); }); $(document).on('click','#export-csv',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); $('#export-to-csv').modal('show'); }); $(document).on('change','#course-select-export',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); var options = $(this).val() $.ajax({ type:'POST', url:"/shoeStudentsToExport", data:{ courseSelectName : options, }, success:function(studenttoExport){ $('#export-results').show(); var count = 1; var json = JSON.parse(studenttoExport); $('.csv-header').html('Students on course '+json[0]['courseModule']); for (let i = 0; i < json.length; i++) { var studentId = '<input type = "hidden" value = "'+json[i]['id']+'" class="get-id"> '; var row = $('<tr><td > <input class="form-check-input studentInfoExport" type="checkbox" value="'+json[i]['id']+'" name="studentInfoExport[]" checked> '+json[i]['id']+'</td><td>'+json[i]['name']+'</td><td>'+json[i]['email']+'</td><td>'+json[i]['courseModule']+'</td>'); $('.st-count').html('('+count++ +')'); $("#student-export-table > tbody").append(row); } } }); }); $(document).on('click','#export-csv',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); $('#export-to-csv').modal('show'); }); $(document).on('click','.export',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); var studentToExport = []; $('.studentInfoExport').each(function(){ if($(this).is(":checked")) { studentToExport.push($(this).val()); } }); $.ajax({ type:'POST', url:"/csv-export", data:{ studentToExport : studentToExport, }, success:function(studentToExportData){ // $('.post-created').fadeIn().delay(1000).fadeOut(); } }); }); }); </script>
"""Models for Blogly.""" from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def connect_db(app): """Connect to database""" db.app = app db.init_app(app) class User(db.Model): """User Model""" __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) first_name = db.Column(db.String(15), nullable=False) last_name = db.Column(db.String(15)) image_url = db.Column(db.String(200), default="https://www.kindpng.com/picc/m/451-4517876_default-profile-hd-png-download.png") posts = db.relationship('Post', backref='user', passive_deletes=True) def __repr__(self): """Show user info""" u = self return f"<User {u.id}: {u.first_name} {u.last_name}>" def get_full_name(self): """Show user's full name""" u = self return f"{u.first_name}" if u.last_name == "None" else f"{u.first_name} {u.last_name}" full_name = property(get_full_name) class Post(db.Model): """Post Model""" __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(20), nullable=False) content = db.Column(db.Text, nullable=False) created_at = db.Column(db.DateTime, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey( 'users.id', ondelete='CASCADE'), nullable=False)
import { useSelector } from "react-redux"; import Typography from "@mui/material/Typography"; import { Image } from "mui-image"; import { RootState } from "../../store"; import { AppBar, Box, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableRow, } from "@mui/material"; export const DeviceDetails = () => { const selectedDeviceName = useSelector( (state: RootState) => state.ui.data.name ); const selectedDeviceModel = useSelector( (state: RootState) => state.ui.data.meta.model ); const selectedDevice = useSelector( (state: RootState) => state.dhcp.leases.filter((lease) => { // does the selected mac exist in the lease data? return lease.data.some((device) => { return device.mac === state.ui.selectedMac; }); })[0] ); return ( <Box sx={{ width: 400 }}> <AppBar position="static" color="primary" enableColorOnDark sx={{ padding: 1 }} > <Typography variant="h6" align="center"> {selectedDeviceName} </Typography> </AppBar> <Stack direction="column" justifyContent="center" alignItems="center" spacing={2} padding={2} > <Box sx={{ display: "flex", justifyContent: "center", margin: "20px 0" }} > <Image alt="selectedDeviceName" src={`/icons/devices/${selectedDeviceModel}.png`} width={100} height="auto" /> </Box> {selectedDevice.description && ( <Paper sx={{ width: "100%", padding: 2 }}> <Typography>{selectedDevice.description}</Typography> </Paper> )} {selectedDevice.data.map((value) => ( <TableContainer component={Paper}> <Table aria-label="simple table" key={value.mac}> <TableBody> {Object.entries(value).map(([key, value]) => ( <TableRow key={key} sx={{ "&:last-child td, &:last-child th": { border: 0 } }} > <TableCell component="th" scope="row"> {key} </TableCell> <TableCell align="right">{value}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ))} </Stack> </Box> ); };
import React, { useState } from 'react'; import './LoginScreen.css'; import LoginLogo from '../images/logo1.png' import SignInScreen from './SignInScreen'; const LoginScreen = () => { const [signIn, setSignIn] = useState(false); return ( <div className="loginScreen"> <div className="loginScreen_background"> <img className="loginScreen_logo" src={LoginLogo} alt="" /> <button onClick={() => setSignIn(true)} className="loginScreen_button" > Sign In </button> <div className="loginScreen_gradient" /> </div> <div className="loginScreen_body"> {signIn ? ( <SignInScreen /> ) : ( <> <h1>Unlimited Movies, TV programmes and More.</h1> <h2>Watch anywhere, Cancel at anytime.</h2> <h3>Ready to watch? Enter your email to create or restart your membership.</h3> <div className="loginScreen_input"> <form> <input type="email" placeholder="Email Addresss" /> <button onClick={() => setSignIn(true)} className="loginScreen_getStarted" > GET STARTED </button> </form> </div> </> )} </div> </div> ) } export default LoginScreen
import './Tabela.css'; import React from 'react'; import listaProdutos from '../data/mercadorias' export default props => { function fillTable(){ var bodyRef = document.getElementById('table').getElementsByTagName('tbody')[0]; bodyRef.innerHTML = ''; let tbody = document.getElementById("tbody"); for (let i = 0; i < listaProdutos.length; i++) { let tr = tbody.insertRow(); let td_id = tr.insertCell(); let td_nome = tr.insertCell(); let td_tipo = tr.insertCell(); let td_dataDeFabricacao = tr.insertCell(); let td_dataDeValidade = tr.insertCell(); let td_peso = tr.insertCell(); let td_custoDeFabricacao = tr.insertCell(); let td_precoDeVenda = tr.insertCell(); let td_qtdeProduzida = tr.insertCell(); let td_qtdeVendida = tr.insertCell(); let td_funcionario = tr.insertCell(); let td_lucro = tr.insertCell(); td_id.innerText = i; td_nome.innerText = listaProdutos[i].nome; td_tipo.innerText = listaProdutos[i].tipo; td_dataDeFabricacao.innerText = listaProdutos[i].dataDeFabricacao; td_dataDeValidade.innerText = listaProdutos[i].dataDeValidade; td_peso.innerText = listaProdutos[i].peso; td_custoDeFabricacao.innerText = listaProdutos[i].custoDeFabricacao; td_precoDeVenda.innerText = listaProdutos[i].precoDeVenda; td_qtdeProduzida.innerText = listaProdutos[i].qtdeProduzida; td_qtdeVendida.innerText = listaProdutos[i].qtdeVendida; td_funcionario.innerText = listaProdutos[i].funcionario; td_lucro.innerText = listaProdutos[i].lucro; } } return ( <div className="TabelaProdutos"> <hr /> <button onClick={ function() { fillTable(); } }>Atualizar Tabela</button> <div className="Delete"> <input type="number" id="inputDelete" /> <button id="btnDelete" onClick={ function() { let id = document.getElementById("inputDelete").value; if(id >=0 && id<listaProdutos.length) { listaProdutos.splice(id, 1); } document.getElementById("inputDelete").value=""; fillTable(); } }>Delete</button> </div> <table id="table" border="1"> <thead> <th>ID</th> <th>Nome</th> <th>Tipo</th> <th>Data de Fabricação</th> <th>Data de Validade</th> <th>Peso</th> <th>Custo de Fabricação</th> <th>Preço de Venda</th> <th>Qtde Prduzida/Dia</th> <th>Qtde Vendida/Dia</th> <th>Funcionário</th> <th>Lucro</th> </thead> <tbody id="tbody" /> </table> </div> ); }
import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import CustomButton from "../custom-button/custom-button.component"; import CartItem from "../cart-item/cart-item.component"; import { toggleCartHidden } from "../../redux/cart/cart.actions"; import { selectCartItems, selectCartTotal, } from "../../redux/cart/cart.selectors"; import { CartDropdownContainer, CartItemsContainer, EmptyMessage, TotalAmount, } from "./cart-dropdown.styles"; const CartDropdown = () => { const [cartItems, total] = [ useSelector(selectCartItems), useSelector(selectCartTotal), ]; const navigate = useNavigate(); const dispatch = useDispatch(); const toggleCartHiddenHandler = () => dispatch(toggleCartHidden()); return ( <CartDropdownContainer> <CartItemsContainer> {cartItems.length ? ( cartItems.map((item) => <CartItem key={item.id} item={item} />) ) : ( <EmptyMessage>You cart is empty</EmptyMessage> )} </CartItemsContainer> {cartItems.length ? ( <TotalAmount> <span>Total: $ {total}</span> </TotalAmount> ) : null} <CustomButton onClick={() => { toggleCartHiddenHandler(); navigate("/checkout"); }} > GO TO CHECKOUT </CustomButton> </CartDropdownContainer> ); }; export default CartDropdown;