text
stringlengths
184
4.48M
// HomeScreen.js import React from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome5'; const HomeScreen = ({ navigation }) => { return ( <View style={styles.container}> <Text style={styles.title}>Divine Desserts</Text> <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Recipe')} > <Icon name="utensils" size={20} color="#fff" /> <Text style={styles.buttonText}>Explore Recipes</Text> </TouchableOpacity> <TouchableOpacity style={[styles.button, styles.loginButton]} onPress={() => navigation.navigate('Login')} testID="login-button" > <Icon name="sign-in-alt" size={20} color="#fff" /> <Text style={styles.buttonText}>Login</Text> </TouchableOpacity> <Text style={styles.newUserText}>New to Divine Desserts?</Text> <TouchableOpacity style={[styles.button, styles.registerButton]} onPress={() => navigation.navigate('Register')} testID='register-button' > <Icon name="user-plus" size={20} color="#fff" /> <Text style={styles.buttonText}>Register</Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 16, backgroundColor: '#FFB6C1', }, title: { fontSize: 32, fontWeight: 'bold', marginBottom: 24, color: '#333', }, button: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', backgroundColor: '#4CAF50', padding: 10, borderRadius: 8, marginBottom: 16, width: '100%', }, buttonText: { marginLeft: 10, color: '#fff', fontSize: 18, }, newUserText: { marginTop: 16, marginBottom: 8, color: '#777', }, }); export default HomeScreen;
@rendermode InteractiveAuto @using BlazorCalendar.Client.Pages @using BlazorCalendar.Client.Components @using BlazorCalendar.Shared.DTOs @using BlazorCalendar.Shared.DTOs.Calendar @using BlazorCalendar.Shared.UseCases.Calendar @using System.ComponentModel.DataAnnotations @using BlazorCalendar.Shared.Common @inject ITimeZoneService timeZoneService @inject IAddDayEvent addDayEventUseCase @inject IDeleteDayEvent deleteEventUseCase @inject IUpdateDayEvent updateDayEventUseCase <div class="event-grid"> @{ var now = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day); } @for (var day = 1; day <= _lastMonthDay; day++) { <DayCard Today="now" LastMonthDay="_lastMonthDay" Month="Month" Year="Year" Day="day" TimeZoneOffset="_timeZoneOffset" Events="GetEvents(day)" OnAddOrEventDialogOpen="OnAddOrEventDialogOpen" OnDeleteEvent="DeleteDayEvent" /> } </div> <AddOrEditDayEventDialog @ref="dayEventDialog" DialogContext="AddOrEditEventModel" OnDayEventAddedOrEdited="AddOrEditDayEvent" /> <ConfirmDialog @ref="confirmDialog" /> @code { private int _lastMonthDay; private AddOrEditDayEventDialog dayEventDialog = default!; private ConfirmDialog confirmDialog = default!; private TimeSpan _timeZoneOffset; [Parameter] public string UserId { get; set; } = default!; [Parameter] public IList<DayEvent> Events { get; set; } = new List<DayEvent>(); [Parameter] public int Month { get; set; } [Parameter] public int Year { get; set; } public AddOrEditEventModel AddOrEditEventModel { get; private set; } = default!; private void OnAddOrEventDialogOpen(int day, DayEvent? evt, IEnumerable<DayEvent> dayEvents) { AddOrEditEventModel.Year = Year; AddOrEditEventModel.Day = day; AddOrEditEventModel.Month = Month; AddOrEditEventModel.DayEvents = dayEvents; if (evt is null) { AddOrEditEventModel.Reset(); } else { AddOrEditEventModel.EventId = evt.Id; AddOrEditEventModel.Title = evt.Title; AddOrEditEventModel.Description = evt.Description; var evtTimestamp = evt.Timestamp - _timeZoneOffset; AddOrEditEventModel.SetTime(evtTimestamp.Hour, evtTimestamp.Minute); } dayEventDialog.Open(); StateHasChanged(); } private void DeleteDayEvent(DayEvent dayEvent) { confirmDialog.ConfirmAction( $"Are you sure to delete the event \"{dayEvent.Title}\"?", async () => { await deleteEventUseCase.DeleteEvent(dayEvent.Id); Events.Remove(dayEvent); StateHasChanged(); }); } protected override async Task OnInitializedAsync() { _timeZoneOffset = await timeZoneService.GetClientOffsetAsync(); } private async Task AddOrEditDayEvent() { var vc = new ValidationContext(AddOrEditEventModel); var validationResults = AddOrEditEventModel.Validate(vc); var validationErrors = validationResults.Where(v => !string.IsNullOrEmpty(v.ErrorMessage)).Select(v => v.ErrorMessage!).ToList(); if (validationErrors.Any()) { AddOrEditEventModel.Errors.AddRange(validationErrors); StateHasChanged(); return; } else { AddOrEditEventModel.Errors.RemoveAll(e => true); } bool isNewEvent = string.IsNullOrEmpty(AddOrEditEventModel.EventId); IDayEventProcessor dayEventProcessor = isNewEvent ? addDayEventUseCase : updateDayEventUseCase; var processEventResult = await dayEventProcessor.ProcessAsync(AddOrEditEventModel); if (!processEventResult.IsSuccess) { AddOrEditEventModel.Errors.Add("Unable to create event. Please try again later."); StateHasChanged(); return; } if (isNewEvent) { OnNewDayEventCreated( new DayEvent { Id = processEventResult.EventId!, Timestamp = AddOrEditEventModel.Timestamp.ToUniversalTime(), Title = AddOrEditEventModel.Title!, Description = AddOrEditEventModel.Description! }); } else { OnDayEventUpdated(); } dayEventDialog.Close(); StateHasChanged(); } protected override void OnParametersSet() { base.OnParametersSet(); AddOrEditEventModel = new(UserId); _lastMonthDay = DateTime.DaysInMonth(Year, Month); } private IEnumerable<DayEvent> GetEvents(int day) { var minDate = new DateTime(Year, Month, day).ToUniversalTime(); var maxDate = new DateTime(Year, Month, day, 23, 59, 59).ToUniversalTime(); return Events.Where(e => e.Timestamp >= minDate && e.Timestamp <= maxDate).OrderBy(d => d.Timestamp); } private void OnNewDayEventCreated(DayEvent newEvent) { if (!Events.Any()) { Events.Add(newEvent); } else { var previousEvent = Events.FirstOrDefault(e => e.Timestamp > AddOrEditEventModel.Timestamp); if (previousEvent is null) { Events.Insert(0, newEvent); } else { var idx = Events.IndexOf(previousEvent); Events.Insert(idx >= 1 ? idx - 1 : 0, newEvent); } } } private void OnDayEventUpdated() { var eventToUpdate = Events.First(e => e.Id == AddOrEditEventModel.EventId); eventToUpdate.Timestamp = AddOrEditEventModel.Timestamp.ToUniversalTime(); eventToUpdate.Title = AddOrEditEventModel.Title!; eventToUpdate.Description = AddOrEditEventModel.Description!; } }
# poesIA: a poetry generator in Spanish 📚📚💻 A poetry generator from a scrapped corpus of Spanish poetry. EDA and general NLP tasks are included. ## Poem genetator 📚🤯 Here a visualization of the generator performance with streamlit. Given some words.... it generates a beautiful poem in Spanish✨✨✨✨ ![wordcloud](images/poem_generator.png) ## Exploratory Data Analysis 🔎🔎 We generated an overview of the whole data. We analyze the scope and length of the vocabulary involved, generating some nice visualizations ☁️☁️☁️ ![wordcloud](images/wordcloud.jpg) We decided to make some word counts as well as search for relations between authors and poems in the whole dataset 📈 <img src="images/graph3.png" alt="Author count" width="500"/> We also took into account specific authors and established some comparisons. We detected relations between textual data such as antithesis and polysemy. Awesome isn't it? 🤩 ![graph2](images/graph2.png) An embedding model was build to detect polysemy, similar words, and common word collocations in poetry. So many word relations in poems! ![wordcloud](images/embedding1.png). Also, Voronoi graphs were made...📈📈📈📈 ![wordcloud](images/embedding2.png). ## Relevant codes - [Script for scrapping the data](poetry-scrapper.py): script that generates a .csv files with the poems scraped from the blog entries of a Spanish poetry webpage (link to the webpage [here](https://www.poemas-del-alma.com)). - [Poem generator visualization (Streamlit)](generating_poems.py): poems generator code using streamlit. ### notebooks - [EDA of the poetry dataset](notebooks/data exploration.ipynb): Exploratory Data Analysis of the dataset, including a basic NLP complete task! - [Poem genetator code](notebooks/poetry generator.ipynb): code to generate synthetic poems with a RNN. * **Recommended**: open the notebooks in [Colaboratory](https://colab.research.google.com/github/andreamorgar/poesIA/blob/master/). ## Talks This project has been presented as a talk in the [PyConEs 2020 (Pandemic Edition)](https://2020.es.pycon.org/). You can find the [slides](slides.pdf) in this repo and the [video](https://www.youtube.com/watch?v=0C96vAa9NHY&t) in youtube.
package http import ( "github.com/kamil-s-solecki/haze/testutils" "testing" ) func TestMethod(t *testing.T) { cases := []struct { req []byte method string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "GET"}, {[]byte("POST /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "POST"}, } for _, c := range cases { got := Parse(c.req).Method want := c.method testutils.AssertEquals(t, got, want) } } func TestRequestUri(t *testing.T) { cases := []struct { req []byte requestUri string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "/somepath"}, {[]byte("GET /otherpath?foo=bar HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "/otherpath?foo=bar"}, } for _, c := range cases { got := Parse(c.req).RequestUri want := c.requestUri testutils.AssertEquals(t, got, want) } } func TestProtocolVersion(t *testing.T) { cases := []struct { req []byte pv string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "HTTP/1.1"}, {[]byte("GET /somepath HTTP/2.0\r\nHost:www.example.com\r\n\r\n"), "HTTP/2.0"}, } for _, c := range cases { got := Parse(c.req).ProtocolVersion want := c.pv testutils.AssertEquals(t, got, want) } } func TestHeaders(t *testing.T) { cases := []struct { req []byte hs map[string]string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), map[string]string{"Host": "www.example.com"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost:example.com\r\n\r\n"), map[string]string{"Host": "example.com"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost: example.com\r\n\r\n"), map[string]string{"Host": "example.com"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"), map[string]string{"Host": "example.com", "Connection": "close"}}, } for _, c := range cases { got := Parse(c.req).Headers want := c.hs testutils.AssertMapEquals(t, got, want) } } func TestBody(t *testing.T) { req := []byte("POST /auth HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 7\r\n\r\nfoo=bar") got := Parse(req).Body want := []byte("foo=bar") testutils.AssertByteEquals(t, got, want) } func TestPath(t *testing.T) { cases := []struct { req []byte path string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "/somepath"}, {[]byte("GET /somepath?foo=bar HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "/somepath"}, } for _, c := range cases { got := Parse(c.req).Path want := c.path testutils.AssertEquals(t, got, want) } } func TestQuery(t *testing.T) { cases := []struct { req []byte query string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), ""}, {[]byte("GET /somepath?foo=bar HTTP/1.1\r\nHost:www.example.com\r\n\r\n"), "foo=bar"}, } for _, c := range cases { got := Parse(c.req).Query want := c.query testutils.AssertEquals(t, got, want) } } func TestClone(t *testing.T) { want := Request{ Method: "Foo1", RequestUri: "Foo2", Path: "Foo2", Query: "Foo3", ProtocolVersion: "Foo4", Headers: map[string]string{"Bar": "Baz"}, Body: []byte("Foo5"), } got := want.Clone() testutils.AssertEquals(t, want.Method, got.Method) testutils.AssertEquals(t, want.RequestUri, got.RequestUri) testutils.AssertEquals(t, want.Path, got.Path) testutils.AssertEquals(t, want.Query, got.Query) testutils.AssertEquals(t, want.ProtocolVersion, got.ProtocolVersion) testutils.AssertMapEquals(t, want.Headers, got.Headers) testutils.AssertByteEquals(t, want.Body, got.Body) } func TestCloneHeaders(t *testing.T) { orig := Request{ Method: "Foo1", RequestUri: "Foo2", Path: "Foo2", Query: "Foo3", ProtocolVersion: "Foo4", Headers: map[string]string{"Bar": "Baz"}, Body: []byte("Foo5"), } clone := orig.Clone() clone.Headers["Bar"] = "Edit" testutils.AssertEquals(t, orig.Headers["Bar"], "Baz") } func TestCookies(t *testing.T) { cases := []struct { req []byte cks map[string]string }{ {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\nCookie:foo=bar\r\n\r\n"), map[string]string{"foo": "bar"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\nCookie:foo=bar \r\n\r\n"), map[string]string{"foo": "bar"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\nCookie:foo=[\"bar\"] \r\n\r\n"), map[string]string{"foo": "[%22bar%22]"}}, {[]byte("GET /somepath HTTP/1.1\r\nHost:www.example.com\r\nCookie:foo=bar; baz=quix\r\n\r\n"), map[string]string{"foo": "bar", "baz": "quix"}}, } for _, c := range cases { r := Parse(c.req) got := r.Cookies want := c.cks testutils.AssertMapEquals(t, got, want) testutils.AssertMapHasNoKey(t, r.Headers, "Cookie") } } func TestResponseStringer(t *testing.T) { cases := []struct { res Response str string }{ {Response{Code: 200, Length: 1234}, "[Code: 200, Len: 1234]"}, {Response{Code: 400, Length: 4321}, "[Code: 400, Len: 4321]"}, } for _, c := range cases { res := c.res got := res.String() testutils.AssertEquals(t, got, c.str) } }
import '../CSS-file/page-css/home.css'; import ProductCard from '../component/ProductCard'; import {useEffect, useState} from 'react'; import HomeSidebar from '../component/HomeSidebar'; import { useSearchParams } from 'react-router-dom'; import axios from '../config/Axios'; import NavBar from '../component/NavBar'; import { handleErr } from '../handle-err/HandleErr'; function Home() { // Content const [productData,setProductData] = useState([]); const [allProductType, setAllProductType] = useState(); //searchParams const [searchParams, setSearchParams] = useSearchParams(); const [searchQuery,setSearchQuery] = useState(''); //value from search input const [filterParams,setFilterParams] = useState(); //value from filter box const [priceFilterParams,setPriceFilterParams] = useState({}); //min-max price value const [sideBarParams,setSideBarParams] = useState({}); //value from sidebar const [sort, setSort] = useState(); // get value from sidebar and filter box // --Multi type value from filter box is string // --One type value from sidebar is object function getParams(data) { if(typeof data === 'string') { setFilterParams(data); //Prepare value for set searchParams when mouse leave from filter box } else { if(data.type === 'all') { //Immediately clear and set searchParams when click button on sidebar setSearchParams({type: '', query: searchParams.get('query'), min: searchParams.get('min'), max: searchParams.get('max')}); setSideBarParams(); setFilterParams(); } else { setSearchParams({type: data.type, query: searchParams.get('query'), min: searchParams.get('min'), max: searchParams.get('max')}); setSideBarParams(data); // Prepare value for set searchParams when mouse leave from filter box without clicking any button setFilterParams(); } }; }; //Get min-max price value from filter box function getPrice(data) { setPriceFilterParams(data); }; async function getAllProductData() { await axios.get(`/product/getallproduct`) .then(res => { setAllProductType([...res.data]); setProductData([...res.data]); }).catch(err => { handleErr(err); }); }; useEffect(() => { document.title = 'Home'; getAllProductData(); },[]); //----------------Filter data follow searchParams------------------------ useEffect(() => { if(allProductType) { let type = searchParams.get('type'); let query = searchParams.get('query'); let min = searchParams.get('min'); let max = searchParams.get('max'); if(type && type !== 'undefined') { let newSearchData = allProductType.filter(e => !!type.match(e.productType)); if(query && query !== 'null' && query !== 'undefined') { let newestSearchData = newSearchData.filter(e => e.productName.toLowerCase().includes(query.toLowerCase()) || e.seller.storeName.toLowerCase().includes(query.toLowerCase())); if(max && max !== 'null' && max !== 'undefined'){ let priceMaxFiltered = newestSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price <= max : e.productOptions.sort((a,b) => a.price - b.price)[0].price <= max); setProductData([...priceMaxFiltered]); setSearchParams({type: type, query: query, max: max}); if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = priceMaxFiltered.filter(e => (e.productOptions === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({type: type, query: query, min: min, max: max}); } } else if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = newestSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({type: type, query: query, min: min}); } else { setProductData([...newestSearchData]); setSearchParams({type: type, query: query}); } } else { if(max && max !== 'null' && max !== 'undefined'){ let priceMaxFiltered = newSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price <= max : e.productOptions.sort((a,b) => a.price - b.price)[0].price <= max); setProductData([...priceMaxFiltered]); setSearchParams({type: type, max: max}); if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = priceMaxFiltered.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({type: type, max: max, min: min}); } } else if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = newSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({type: type, min: min}); } else { setProductData([...newSearchData]); setSearchParams({type: type}); } } } else { if(query && query !== 'null' && query !== 'undefined') { let newestSearchData = allProductType.filter(e => e.productName.toLowerCase().includes(query.toLowerCase()) || (e.seller.storeName.toLowerCase().includes(query.toLowerCase()))); if(max && max !== 'null' && max !== 'undefined'){ let priceMaxFiltered = newestSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price <= max : e.productOptions.sort((a,b) => a.price - b.price)[0].price <= max); setProductData([...priceMaxFiltered]); setSearchParams({query: query, max: max}); if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = priceMaxFiltered.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({query: query, max: max, min: min}); } } else if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = newestSearchData.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({query: query, min: min}); } else { setProductData([...newestSearchData]); setSearchParams({query: query}); } } else { if(max && max !== 'null' && max !== 'undefined'){ let priceMaxFiltered = allProductType.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price <= max : e.productOptions.sort((a,b) => a.price - b.price)[0].price <= max); setProductData([...priceMaxFiltered]); setSearchParams({max: max}); if(min && min !== 'null'&& min !== 'undefined') { let priceMinFiltered = priceMaxFiltered.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({max: max, min: min}); } } else if(min && min !== 'null' && min !== 'undefined') { let priceMinFiltered = allProductType.filter(e => (e.productOptions.length === 1)? e.productOptions[0].price >= min : e.productOptions.sort((a,b) => b.price - a.price)[0].price >= min); setProductData([...priceMinFiltered]); setSearchParams({min: min}); } else { setProductData([...allProductType]); setSearchParams(); }; }; }; }; }, [searchParams, allProductType, setSearchParams]); //------------------Sort data-------------------------- useEffect(() => { if(productData.length > 0 && sort) { if(sort === 'Latest') { let data = [...productData]; data.sort((a, b) => b.id - a.id); setProductData([...data]); } else if(sort === 'Price') { let data = [...productData]; data.sort((a, b) => { let aPrice ; let bPrice ; if(a.productOptions.length > 1) { aPrice = a.productOptions.sort((c, d) => c.price - d.price)[0].price; } else { aPrice = a.productOptions[0].price; }; if(b.productOptions.length > 1) { bPrice = b.productOptions.sort((c, d) => c.price - d.price)[0].price; } else { bPrice = b.productOptions[0].price; }; return aPrice - bPrice ; }); console.log(data); setProductData([...data]); } else if(sort === 'Total Sold') { let data = [...productData]; data.sort((a, b) => b.productSellCount - a.productSellCount); setProductData([...data]); } else if(sort === 'Star') { let data = [...productData]; data.sort((a, b) => { let aStar ; let bStar ; if(a.reviews.length > 0) { let review = [...a.reviews]; let totalStar = 0; for(let e of review) { totalStar += e.reviewStar ; }; aStar = totalStar/review.length ; } else { aStar = 0; }; if(b.reviews.length > 0) { let review = [...b.reviews]; let totalStar = 0; for(let e of review) { totalStar += e.reviewStar ; }; bStar = totalStar/review.length ; } else { bStar = 0; }; return bStar - aStar ; }); setProductData([...data]); }; setSort(); }; }, [sort, productData]); return ( <div> <NavBar setSearchParams = {setSearchParams} setSearchQuery = {setSearchQuery} searchQuery = {searchQuery} searchParams = {searchParams} filterParams = {filterParams} setSideBarParams = {setSideBarParams} priceFilterParams = {priceFilterParams} sideBarParams = {sideBarParams} allProductType = {allProductType} getParams = {getParams} getPrice = {getPrice} setSort = {setSort} /> <div className='homePage'> <div className='homeSidebar'> <HomeSidebar productData = {allProductType} sentSideParams = {getParams} searchParams={searchParams} /> </div> <div className='homeContent'> <div className='productCardContainer'> {productData?.map(el => <div key={el.id}><ProductCard data = {el}/></div>)} </div> </div> </div> </div> ) } export default Home;
package services import models.Hero import models.requests.UpsertHeroRequest import org.koin.core.component.KoinComponent import org.koin.core.component.inject import repositories.HeroRepository class HeroService: KoinComponent { private val heroRepository: HeroRepository by inject() suspend fun createHero(request: UpsertHeroRequest): Hero? { return heroRepository.createHeroResponse(request) } suspend fun getAllHeroes(): List<Hero> { return heroRepository.getAllHeroes() } suspend fun getHeroById(id: Int): Hero? { return heroRepository.getHeroById(id) } suspend fun updateHero(id: Int, request: UpsertHeroRequest): Hero? { return heroRepository.updateHero(id, request) } suspend fun deleteHero(id: Int): Any { return heroRepository.deleteHero(id) } }
package com.superMarket.purchase.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.SoftBevelBorder; import com.superMarket.purchase.bean.Purchase; import com.superMarket.purchase.dao.PurchaseDao; import com.superMarket.purchase.dao.PurchaseDaoImpl; import com.superMarket.purchase.model.MyRender; import com.superMarket.purchase.model.PurchaseTableModel; public class PurchasePanel { private JPanel myPanel;//主界面 private JComboBox<String> itemsBox; private JTextField textField_1; //地址输入框 public static JTable table; public static JPanel tablePanel; private PurchaseTableModel model; private PurchaseDao purchaseDao = new PurchaseDaoImpl(); private String SelectItem; public JPanel getPurchasePanel(){ myPanel = new JPanel(); myPanel.setLayout(null); myPanel.setSize(888, 500); JPanel panel = new JPanel(); panel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.WHITE, null, null, null)); panel.setBounds(2, 4, 1000, 46); myPanel.add(panel); panel.setLayout(null); JLabel label = new JLabel("查询条件:"); label.setBounds(10, 21, 78, 15); panel.add(label); itemsBox = new JComboBox<String>(); itemsBox.addItem("请选择..."); itemsBox.addItem("客户名"); itemsBox.addItem("商品名"); itemsBox.setBounds(91, 18, 86, 21); panel.add(itemsBox); itemsBox.addItemListener(new ItemsListener()); /* JLabel label_1 = new JLabel("地址:"); label_1.setBounds(187, 21, 54, 15); panel.add(label_1);*/ textField_1 = new JTextField(); textField_1.setColumns(10); textField_1.setBounds(180, 18, 130, 21); panel.add(textField_1); JButton button_search = new JButton("搜索"); button_search.setBounds(343, 17, 67, 23); panel.add(button_search); button_search.addActionListener(new SearchButtonListener()); JButton button_add = new JButton("添加"); button_add.setBounds(420, 17, 67, 23); panel.add(button_add); button_add.addActionListener(new AddButtonListener()); JButton button_update = new JButton("修改"); button_update.setBounds(501, 17, 67, 23); panel.add(button_update); button_update.addActionListener(new UpdateButtonListener()); JButton button_delete = new JButton("删除"); button_delete.setBounds(583, 17, 67, 23); panel.add(button_delete); button_delete.addActionListener(new DeleteButtonListener()); tablePanel = new JPanel(); tablePanel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); tablePanel.setBounds(2, 60, 1000, 550); myPanel.add(tablePanel); tablePanel.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); tablePanel.add(scrollPane); model= new PurchaseTableModel(); table = new JTable(model); //添加渲染器 table.getColumnModel().getColumn(0).setCellEditor(new MyRender());//设置编辑器 table.getColumnModel().getColumn(0).setCellRenderer(new MyRender()); scrollPane.setViewportView(table); scrollPane.setBorder(BorderFactory.createTitledBorder("订单信息")); return myPanel; } /** * 选择项监听器 * @author administrator * */ public class ItemsListener implements ItemListener{ @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED){ String item = (String)itemsBox.getSelectedItem(); SelectItem = item; } } } /** * 添加按钮监听器 * @author administrator * */ public class AddButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { new AddPurchaseFrame(); } } /** * 删除按钮监听器 * @author administrator * */ public class DeleteButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); String id = null; try{ id = (String) table.getValueAt(row, 1); }catch (ArrayIndexOutOfBoundsException ex){ System.out.println("未选择修改的列!"); } if (id == null){ JOptionPane.showMessageDialog(null, "请选取需要删除订单信息", "警告", JOptionPane.ERROR_MESSAGE); return; } //询问用户是否真的删除该供货商 int isdel = JOptionPane.showConfirmDialog(null, "是否确定删除该订单信息?", "删除订单信息?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if(isdel == 1) return; textField_1.setText(""); purchaseDao.delPurchase(id); //table.removeAll(); table.removeAll(); table.setModel(new PurchaseTableModel()); table.getColumnModel().getColumn(0).setCellEditor(new MyRender());//设置编辑器 table.getColumnModel().getColumn(0).setCellRenderer(new MyRender()); } } /** * 搜索按钮监听器 * @author administrator * */ public class SearchButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { List<Purchase> list = null; String SelectStr = textField_1.getText(); System.out.println(SelectItem); if (SelectItem== null || SelectItem.equals("请选择...")){ JOptionPane.showMessageDialog(null, "请选择查询条件", "警告", JOptionPane.ERROR_MESSAGE); textField_1.setText(""); return; }else if (SelectItem.equals("客户名")){ list = purchaseDao.getPurchaseListBySName(SelectStr); if (list.isEmpty()){ JOptionPane.showMessageDialog(null, "未查询到该关键字,请重试!", "警告", JOptionPane.ERROR_MESSAGE); textField_1.setText(""); return; } table.removeAll(); table.setModel(new PurchaseTableModel(list)); table.getColumnModel().getColumn(0).setCellEditor(new MyRender());//设置编辑器 table.getColumnModel().getColumn(0).setCellRenderer(new MyRender()); }else if (SelectItem.equals("商品名")){ list = purchaseDao.getPurchaseListByGoodsName(SelectStr); if (list.isEmpty()){ JOptionPane.showMessageDialog(null, "未查询到该关键字,请重试!", "警告", JOptionPane.ERROR_MESSAGE); textField_1.setText(""); return; } table.removeAll(); table.setModel(new PurchaseTableModel(list)); table.getColumnModel().getColumn(0).setCellEditor(new MyRender());//设置编辑器 table.getColumnModel().getColumn(0).setCellRenderer(new MyRender()); } } } /** * 更新按钮的监听器 * @author administrator * */ public class UpdateButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //获取选取的行 int row = table.getSelectedRow(); //获取选取的id String id = null; try{ id = (String) table.getValueAt(row, 1); }catch(ArrayIndexOutOfBoundsException ex){ System.out.println("未选取修改的行"); } if (id == null){ JOptionPane.showMessageDialog(null, "请选取需要修改订单!", "警告", JOptionPane.ERROR_MESSAGE); return; } textField_1.setText(""); //获取选取的供货商的信息 Purchase purchase = purchaseDao.getPurchaseById(id); //将信息传入修改页面 new UpdatePurchaseFrame(purchase); table.removeAll(); table.setModel(new PurchaseTableModel()); table.getColumnModel().getColumn(0).setCellEditor(new MyRender());//设置编辑器 table.getColumnModel().getColumn(0).setCellRenderer(new MyRender()); } } }
<template> <div class="filter"> <div class="filter__header filter-header" @click="toggleList(filterItem.id)" > <div class="filter-header__title">{{ filterItem.name }}</div> <div class="filter-header__toggler" :class="{ 'filter-header__toggler--close': filtersIsOpenList.includes( filterItem.id ), }" ></div> </div> <transition name="max-height"> <div class="filter__wrapper" v-if="!filtersIsOpenList.includes(filterItem.id)" > <div class="filter__search filter-search" v-if="filterItem.items.length > 6" > <label class="filter-search__input filter-search-input" :class="{ 'filter-search-input--filled': !!searchValue }" > <div class="filter-search-input__label">Пошук</div> <input ref="searchInput" class="filter-search-input__value" type="text" v-model="searchValue" /> </label> </div> <div class="filter__list filter-list"> <div v-for="listItem in listSearch" :key="listItem.id" > <NuxtLink :title="listItem.name" rel="tag" v-if="!!listItem.cocktailCount" class="filter-list__item filter-list-item" :class="{ 'filter-list-item--active': listItem.active }" :to="listItem.url + query" > <span class="filter-list-item__radio" v-if="filterItem.selectionType === types.single" ></span> <span class="filter-list-item__checkbox" v-else ></span> <span class="filter-list-item__name"> {{ listItem.selectionType }} {{ listItem.name }} </span> <span class="filter-list-item__count" v-if="!listItem.active" > {{ listItem.cocktailCount }} </span> </NuxtLink> <div v-else class="filter-list__item filter-list-item filter-list-item--lock" > <span class="filter-list-item__radio" v-if="filterItem.selectionType === types.single" ></span> <span class="filter-list-item__checkbox" v-else ></span> <div class="filter-list-item__name"> {{ listItem.name }} </div> <div class="filter-list-item__count"> {{ listItem.cocktailCount }} </div> </div> </div> <div class="filter-list__text" v-if="listSearch.length === 0" > нічого не знайдено </div> </div> </div> </transition> </div> </template> <script> import { mapGetters, mapActions } from "vuex"; import { types } from "~~/utils/selectionType"; export default { name: "FilterItem", data: () => ({ isCloseFilter: [], searchValue: "", }), methods: { // toggleList(id) { // this.updateFiltersIsOpenList(id); // }, updateCocktails(payload) { this.$emit("updateCocktails", payload); }, ...mapActions("filter", { toggleList: "updateFiltersIsOpenList", }), }, computed: { ...mapGetters("filter", { filtersIsOpenList: "getFiltersIsOpenList", }), types() { return types; }, filterItemSort() { let arr = [...this.filterItem.items]; return arr.sort((a, b) => (a.cocktailCount > b.cocktailCount ? -1 : 1)); }, query() { let query = "?"; for (let [key, value] of Object.entries(this.$nuxt.$route.query)) { if (key != "page") { query = query + `&${key}=${value}`; } } return query; }, listSearch() { if (!!this.searchValue) { let arr = []; arr = this.filterItemSort.filter((listItem) => { return listItem.name .toLowerCase() .includes(this.searchValue.toLowerCase()); }); return arr; } else { return this.filterItemSort; } }, }, props: { filterItem: { type: Object, required: true, }, }, }; </script> <style lang="scss" scoped> @import "./styles/filter-item"; </style>
//! Utility functions for the parser use super::parser::State; use crate::{ interface::{Decoration, Options, Position}, utils::{ styles::SYMBOLS_STYLES, symbols::{get_category_by_name, Category, Color, SYMBOLS}, }, }; use std::{collections::HashMap, ops::Range}; use typst_syntax::SyntaxNode; use typst_syntax::{ast::AstNode, LinkedNode, Source}; /// Get symbol from it's name pub fn get_symbol(content: String, options: &Options) -> Option<(Category, String)> { // Check if the symbol is defined by the user if let Some(entry) = options.custom_symbols.get(&content) { return Some((get_category_by_name(&entry.category), entry.symbol.clone())); } // Check if the symbol is in the symbols list else if let Some(entry) = SYMBOLS.get_entry(&content.as_str()) { return Some((entry.1.category, format!("{}", entry.1.symbol))); } return None; } /// Get color and text_decoration css style from a symbol category fn get_style_from_category(category: Category) -> (Color, std::string::String) { // Default values let mut color = Color::Number; let mut text_decoration = "".to_string(); if let Some(style) = SYMBOLS_STYLES.get(category as usize) { color = style.0; text_decoration = style.1.to_string(); } return (color, text_decoration); } /// Cast expr to the given AST type. No checks are done, will panick if the given expression is not of the given type. pub fn unchecked_cast_expr<'a, T: AstNode<'a>>(expr: &'a SyntaxNode) -> T { T::from_untyped(expr).unwrap() } /// The number of code units this string would use if it was encoded in /// UTF16. This runs in linear time. fn len_utf16(string: &str) -> usize { string.chars().map(char::len_utf16).sum() } /// Return the index range of the UTF-16 code unit at the byte index range. \ /// Faster than calling `byte_to_utf16` over start and end. fn byte_range_to_utf16(source: &Source, range: &Range<usize>) -> Option<Range<usize>> { let start = source.byte_to_utf16(range.start)?; let head = source.get(range.start..range.end)?; let end = start + len_utf16(head); return Some(start..end); } /// Store the current data of the parsing pub struct InnerParser<'a> { /// Source of the document pub source: &'a typst_syntax::Source, /// Vector containing decorations to render pub result: &'a mut HashMap<String, Decoration>, /// Current state of the parser pub state: &'a mut State, /// User settings pub options: &'a Options, /// Current expression pub expr: &'a LinkedNode<'a>, /// Current uuid applied to sub-decorations pub uuid: &'a str, /// Current css style applied to sub-decorations pub added_text_decoration: &'a str, /// Current offset applied to sub-decorations ranges' pub offset: (usize, usize), } impl<'a> InnerParser<'a> { /// Create a new parser pub fn new( source: &'a typst_syntax::Source, expr: &'a LinkedNode<'a>, result: &'a mut HashMap<String, Decoration>, state: &'a mut State, options: &'a Options, ) -> InnerParser<'a> { InnerParser { source, expr, result, state, uuid: "", added_text_decoration: "", offset: (0, 0), options, } } /// Create a new parser from another pub fn from( parser: &'a mut InnerParser, expr: &'a LinkedNode<'a>, uuid: &'a str, added_text_decoration: &'a str, offset: (usize, usize), ) -> InnerParser<'a> { InnerParser { source: parser.source, expr, result: parser.result, state: parser.state, uuid, added_text_decoration, offset, options: parser.options, } } /// Helper function to insert a new symbol in the symbols hashmap, with a symbol directly from the typst sym module pub fn insert_result_symbol( &mut self, range: Range<usize>, content: String, uuid: String, added_text_decoration: &str, offset: (usize, usize), additional_content: (&str, &str), ) { if let Some((category, symbol)) = get_symbol(content, self.options) { // If we are in a space and we don't want to render them, return if !self.options.render_spaces && category == Category::Space { return; } let (color, text_decoration) = get_style_from_category(category); self.insert_result( range, uuid, format!( "{}{}{}", additional_content.0, symbol.to_string(), additional_content.1, ), color, format!("{text_decoration} {added_text_decoration}"), offset, ); } } /// Helper function to insert a new symbol in the symbols hashmap pub fn insert_result( &mut self, range: Range<usize>, uuid: String, symbol: String, color: Color, text_decoration: String, offset: (usize, usize), ) { // Convert position to UTF-16, because VSCode uses UTF-16 for positions let utf16_range = byte_range_to_utf16(self.source, &range).unwrap(); let position = Position { start: utf16_range.start - offset.0, end: utf16_range.end + offset.1, }; // Check if the symbol is blacklisted if self .options .blacklisted_symbols .contains(&self.source.get(range).unwrap_or("UNREACHABLE").to_string()) { return; } // If the decoration already exists, simply add a new range if let Some(map) = self.result.get_mut(&uuid) { map.positions.push(position); } else { // If not, create the decoration and add this range self.result.insert( uuid.clone(), Decoration { uuid, symbol, color, text_decoration, positions: vec![position], }, ); } } /// Helper function to insert a new invisible symbol in the symbols hashmap to hide a span pub fn insert_void(&mut self, range: Range<usize>, offset: (usize, usize)) { self.insert_result( range, "void".to_string(), "".to_string(), Color::Number, "".to_string(), offset, ) } } #[cfg(test)] mod tests { use typst_syntax::SyntaxNode; use crate::{interface::Options, parser::parser::State}; #[test] fn test_inner_parser() { let source = typst_syntax::Source::detached("α"); let mut result = std::collections::HashMap::new(); let mut state = State::default(); let options = Options::default(); let node = SyntaxNode::leaf(typst_syntax::SyntaxKind::Ident, "alpha"); let expr = typst_syntax::LinkedNode::new(&node); let mut parser = super::InnerParser::new(&source, &expr, &mut result, &mut state, &options); parser.insert_result_symbol( 0..2, "alpha".to_string(), "alpha".to_string(), "", (0, 0), ("", ""), ); let mut parser = super::InnerParser::from(&mut parser, &expr, "alpha", "", (0, 0)); parser.insert_result_symbol( 0..2, "alpha".to_string(), "alpha".to_string(), "", (0, 0), ("", ""), ); assert_eq!(parser.result.len(), 1); assert_eq!(parser.result.get("alpha").unwrap().symbol, "α"); } #[test] fn test_inner_parser_spaces() { let source = typst_syntax::Source::detached("zwnj"); let mut result = std::collections::HashMap::new(); let mut state = State::default(); let mut options = Options::default(); let node = SyntaxNode::leaf(typst_syntax::SyntaxKind::MathIdent, "zwnj"); let expr = typst_syntax::LinkedNode::new(&node); let mut parser = super::InnerParser::new(&source, &expr, &mut result, &mut state, &options); parser.insert_result_symbol( 0..4, "zwnj".to_string(), "zwnj".to_string(), "", (0, 0), ("", ""), ); assert_eq!(parser.result.len(), 0); options.render_spaces = true; let mut parser = super::InnerParser::new(&source, &expr, &mut result, &mut state, &options); parser.insert_result_symbol( 0..4, "zwnj".to_string(), "zwnj".to_string(), "", (0, 0), ("", ""), ); assert_eq!(parser.result.len(), 1); } #[test] fn test_inner_parser_not_found() { let source = typst_syntax::Source::detached(""); let mut result = std::collections::HashMap::new(); let mut state = State::default(); let options = Options::default(); let node = SyntaxNode::leaf(typst_syntax::SyntaxKind::Ident, "alpha"); let expr = typst_syntax::LinkedNode::new(&node); let mut parser = super::InnerParser::new(&source, &expr, &mut result, &mut state, &options); parser.insert_result_symbol( 0..5, "doesn't exist".to_string(), "doesn't exist".to_string(), "", (0, 0), ("", ""), ); } #[test] fn test_inner_parser_blacklist() { let source = typst_syntax::Source::detached("alpha"); let mut result = std::collections::HashMap::new(); let mut state = State::default(); let mut options = Options::default(); options.blacklisted_symbols.push("alpha".to_string()); let node = SyntaxNode::leaf(typst_syntax::SyntaxKind::Ident, "alpha"); let expr = typst_syntax::LinkedNode::new(&node); let mut parser = super::InnerParser::new(&source, &expr, &mut result, &mut state, &options); parser.insert_result_symbol( 0..5, "alpha".to_string(), "alpha".to_string(), "", (0, 0), ("", ""), ); assert_eq!(parser.result.len(), 0); } }
module Euler1 where import Prelude import Data.List (List, range, filter) import Data.Foldable (sum) -- | Multiples of 3 and 5 -- | -- | If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. -- | The sum of these multiples is 23. -- | -- | Find the sum of all the multiples of 3 or 5 below 1000. -- | -- | https://projecteuler.net/problem=1 ns :: List Int ns = range 0 999 multiples :: List Int multiples = filter (\n -> n `mod` 3 == 0 || n `mod` 5 == 0) ns answer :: Unit -> String answer _ = show $ sum multiples
<?php // // navwalker registration for navbar function register_navwalker() { require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php'; } add_action('after_setup_theme', 'register_navwalker'); // support menu add_theme_support('menus'); // style used if (!function_exists('theme_enquee_scripts')) { function theme_enquee_scripts() { //css wp_enqueue_style('css', get_template_directory_uri() . '/style.css'); wp_enqueue_style('css', get_template_directory_uri() . '/css/responsive.css'); wp_enqueue_style('fonts', get_template_directory_uri() . '/fonts/css/all.css'); wp_enqueue_style('fonts', get_template_directory_uri() . '/fonts/css/regular.min.css'); wp_enqueue_style('css', get_template_directory_uri() . '/css/boxicons.min.css'); wp_enqueue_style('css', get_template_directory_uri() . '/css/boxicons.css'); wp_enqueue_style('js', get_template_directory_uri() . '/script.js'); wp_enqueue_style('bootstrap', get_template_directory_uri() .'/css/bootstrap.min.css'); //functions to link booktstrap,JS and jquery wp_enqueue_script('jquery',get_template_directory_uri().'/js/jquery.min.js'); wp_enqueue_script('jquery',get_template_directory_uri().'/js/jquery-min.js'); wp_enqueue_script('jquery',get_template_directory_uri().'/js/bootstrap.bundle.min.js'); wp_enqueue_script('javascript',get_template_directory_uri(). '/js/slim.min.js'); wp_enqueue_script('javascript',get_template_directory_uri(). '/js/popper.min.js'); wp_enqueue_script('javascript', get_template_directory_uri() .'/js/bootstrap.min.js'); } } add_action('wp_enqueue_scripts', 'theme_enquee_scripts'); //Functions for creating menus add_theme_support('menus'); function wp_theme_setup() { register_nav_menus(array( 'primary' => __('Primary Menu', 'primary menu'), )); } add_action('after_setup_theme', 'wp_theme_setup'); //post thumbnail support add_theme_support('post-thumbnails'); //theme logo function themename_custom_logo_setup() { $defaults = array( 'height' => 80, 'width' => 80, 'flex-height' => true, 'flex-width' => true, 'header-text' => array('site-title', 'site-description'), ); add_theme_support('custom-logo', $defaults); } add_action('after_setup_theme', 'themename_custom_logo_setup'); //excerpt function custom_excerpt() { $excerpt = get_the_content(); $excerpt = preg_replace(" ([.*?])", '', $excerpt); $excerpt = strip_shortcodes($excerpt); $excerpt = strip_tags($excerpt); $excerpt = substr($excerpt, 0, 450); $excerpt = substr($excerpt, 0, strripos($excerpt, " ")); $excerpt = trim(preg_replace('/\s+/', ' ', $excerpt)); $excerpt = $excerpt . '... <a href="' . get_the_permalink() . '"></a>'; return $excerpt; } add_filter( 'jetpack_offline_mode', '__return_true' ); function my_widgets() { //Register Sidebar #1 register_sidebar( array( 'name' => __('Footer menu', 'textdomain'), 'id' => 'footer-1', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); register_sidebar( array( 'name' => __('Header Banner Ads', 'textdomain'), 'id' => 'banner', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); // category page ads register_sidebar( array( 'name' => __('Category page Ads', 'textdomain'), 'id' => 'cat-ads', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); //Register Sidebar #2 register_sidebar( array( 'name' => __('Single page Banner Ads top', 'textdomain'), 'id' => 'banner-1', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); //single page ads after contact form register_sidebar( array( 'name' => __('Single Page Ads after comment form ', 'textdomain'), 'id' => 'ads-banner', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); //Register Sidebar #3 register_sidebar( array( 'name' => __('Single Page Banner Ads Center ', 'textdomain'), 'id' => 'banner-2', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); register_sidebar( array( 'name' => __('Single page Banner Ads Bottom', 'textdomain'), 'id' => 'banner-3', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); //front page ads register_sidebar( array( 'name' => __('Front Page ads after news', 'textdomain'), 'id' => 'front-page-ads', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); register_sidebar( array( 'name' => __('Front Page Banner Ads 1', 'textdomain'), 'id' => 'front-1', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); register_sidebar( array( 'name' => __('Front Page Banner Ads 2', 'textdomain'), 'id' => 'front-2', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); register_sidebar( array( 'name' => __('Front Page Banner Ads 3', 'textdomain'), 'id' => 'front-3', 'description' => __('Add widgets here to appear Advertisement', 'textdomain'), ) ); } add_action('widgets_init', 'my_widgets');
<template> <Layout> <Tabs class-prefix="recordType" :data-source="recordTypeList" :value.sync="recordType"/> <!-- <Tabs class-prefix="interval" :data-source="intervalList" :value.sync="interval" height="48px"/>--> <div> <div v-if="result.length === 0" class="message" >当前没有任何记录,快来记一笔吧</div> <ol v-else class="records-wrapper"> <li v-for="([title,group],index) in result" :key="index"> <div class="title"> <h3>{{beautyDate(title)}}</h3> <h3>¥{{addUpAmount(group)}}</h3> </div> <ol> <li class="record" v-for="(item,index) in group" :key="index"> <span class="tags">{{beautyTag(item.selectedTags) || '无'}}</span> <span class="notes">{{item.notes}}</span> <span class="amount">¥{{item.amount}}</span> </li> </ol> </li> </ol> </div> </Layout> </template> <script lang="ts"> import Vue from 'vue'; import Tabs from '@/components/Tabs.vue'; import {Component} from 'vue-property-decorator'; import recordTypeList from '@/constants/recordTypeList'; import intervalList from '@/constants/intervalList'; import dayjs from 'dayjs'; import storeHelper from '@/store/storeHelper.ts'; const oneDay = 86400 * 1000; //一天等于86400秒,86400*1000毫秒 @Component({ components: {Tabs} }) export default class Statistics extends Vue { recordTypeList = recordTypeList; recordType = '-'; intervalList = intervalList; interval = 'day'; created() { this.$store.commit('fetchRecords'); this.$store.commit('fetchTags'); } get tagList() { return this.$store.state.tagList; } get recordList() { return (this.$store.state as RootState).recordList; } addUpAmount(records: RecordItem[]) { // let total = 0; // records.forEach(record => { // total += record.amount; // }); return records.reduce((total: number, {amount}) => { return total + amount; }, 0); } get result() { // 或者先把recordList日期排序,然后在进行桶归类 // 但是不能在原数组上修改(最好) // 先桶归类,然后再按日期排序 const {recordList} = this; const hashTable: { [key: string]: RecordItem[] } = {}; recordList.forEach(record => { if (this.recordType === record.type) { const [date] = record.createAt.split('T'); hashTable[date] = hashTable[date] || []; hashTable[date].push(record); } }); //大于0 就要互换位置,小于或等于0不变 return Object.entries(hashTable).sort(([a], [b]) => { return dayjs(b).valueOf() - dayjs(a).valueOf(); }); } beautyTag(idList: string[]) { const nameList: string[] = []; idList.forEach(id => { const name = storeHelper.findTag(this.tagList, id)?.name || '无'; nameList.push(name); }); return nameList.join(','); } beautyDate(date: string) { // const now = new Date(); // const day = dayjs(date); // if (day.isSame(now, 'day')) { // return '今天'; // } else if (day.isSame(now.valueOf() - oneDay, 'day')) { // return '昨天'; // } else if (day.isSame(now.valueOf() - oneDay * 2, 'day')) { // return '前天'; // } else { // return day.format('YYYY年MM月DD日') // } const now = dayjs(); const day = dayjs(date); if (day.isSame(now, 'day')) { return '今天'; } else if (day.isSame(now.subtract(1, 'day'), 'day')) { return '昨天'; } else if (day.isSame(now.subtract(2, 'day'), 'day')) { return '前天'; } else if (day.isSame(now, 'year')) { return day.format('M月DD日'); } else { return day.format('YYYY年M月D日'); } } } </script> <style lang="scss" scoped> @import "~@/assets/style/helper.scss"; ::v-deep { .recordType-tabs { .recordType-tabs-item { background: #fff; &.selected { background-color: #c4c4c4; box-shadow: none; } } } .interval-tabs { .interval-tabs-item { line-height: 48px; &.selected { } } } } .message{ text-align: center; padding: 24px; } .records-wrapper { /*background-color: #fff;*/ .record { background-color: #fff; .notes { @extend %oneLine; margin-right: auto; margin-left: 16px; color: #999; } } .record, .title { padding: 0 16px; display: flex; justify-content: space-between; align-items: center; line-height: 40px; } } </style>
package ch.zli.m223.model; import javax.persistence.Column; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @NamedQueries({ @NamedQuery(name = "ApplicationUser.findByEmail", query = "SELECT u FROM ApplicationUser u WHERE u.email = :email") }) public class ApplicationUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Schema(readOnly = true) private Long id; @Column(nullable = false, unique = true) private String email; @Column(nullable = false) private String password; @Column private String FirstName; @Column private String LastName; @Column private String Role; @OneToMany(mappedBy = "applicationUser") @JsonIgnoreProperties("user") @Fetch(FetchMode.JOIN) private Set<Buchung> buchungen = new HashSet<>(); public String getRole() { return Role; } public void setRole(String role) { Role = role; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return FirstName; } public void setFirstName(String firstname) { this.FirstName = firstname; } public Set<Buchung> getBuchungen() { return buchungen; } public void setBuchungen(Set<Buchung> buchungen) { this.buchungen = buchungen; } public void addBuchung(Buchung buchung) { buchungen.add(buchung); buchung.setUser(this); } public void removeBuchung(Buchung buchung) { buchungen.remove(buchung); buchung.setUser(null); } }
clear clc %Whale Optimization Algorithm created by A. Lewis and S. Mirjalili (2016) %is used to find the most optimum design for a bridge girder. %This for loop is created to compute the algorithm ten times, if the user %do not want to do this. running time can be entered as 1. NumberOfRunnings=10; %the number of runnings conducted for algorithm %boundries are defined LB=[1 0.25 0.01 0.01]; UB=[5 2.5 0.1 0.1]; %parameters are defined Max_iter=100; search_agent=100; %penalty value is defined r_pen=10^5; r_pen_increase=1.2; %paremeter for the shape of the spiral b=1; %number of variables numberofvariables=4; for z=1:NumberOfRunnings %initialization x_star=zeros(1,numberofvariables); f_star=inf; collect(1)=f_star; %whale population is initialized for i=1:numberofvariables x(:,i)=rand(search_agent,1).*(UB(i)-LB(i))+LB(i); end %collection array was defined collect=zeros(1,Max_iter); %iteration counter was defined t=1; while t <= Max_iter % loop is conducted for every search agent for i=1:search_agent %fitness is computed; fitness=FuncValue(x(i,:),r_pen); if fitness<f_star f_star=fitness; x_star=x(i,:); end %a and a2 was defined in terms of max_iter and iteration counter; a=2-2*t/Max_iter; a2=-1+t*((-1)/Max_iter); %variables such as r2 r1 p b A C l are defined; r2=rand; r1=rand; p=rand; A=2*a*r1-a; C=2*r2; l=(a2-1)*rand+1; for j=1:numberofvariables if p< 0.5 if abs(A)<1 D=abs(C*x_star(j)-x(i,j)); x(i,j)=x_star(j)-A*D; elseif abs(A)>=1 x_rand(j) = LB(j) + (UB(j)-LB(j)).*rand; D=abs(C*x_rand(j)-x(i,j)); x(i,j)=x_rand(j)-A*D; end elseif p>=0.5 D_prime=abs(x_star(j)-x(i,j)); x(i,j)=D_prime*exp(b.*l)*cos(l.*2*pi)+x_star(j); end %Upper and lowers bounds of the variables are checked, and they are %corrected if they went beyond boundries while (x(i,j)>UB(j))||(x(i,j)<LB(j)) x_rand(1,j) = LB(j) + (UB(j)-LB(j)).*rand; x(i,j)=x_rand(1,j); end end end r_pen=r_pen*r_pen_increase; t=t+1; collect(t)=f_star; end %the values in the collect array are rounded by 4 decimals to find when its %converges RoundedCollect=round(collect,4); LastResult=round(collect(length(collect)),4); %printing the optimum values and points x_opt=x_star(1,:); fprintf(['\n','optimum point is ' num2str(x_opt)]); f_opt=FuncValue(x_opt,r_pen); %optimum for each running is stored optimum4eachrun(z,1)=f_opt; %index of the collect where convergence occurred are found index=find(RoundedCollect==LastResult); %using this index convergence time for each running is stored convergenceTime4eachrun(z,1)=index(1); %the values computed are printed out fprintf(['\n','optimum value is ' num2str(f_opt) ]); f_wop = (x_opt(1)*x_opt(4)+2*x_opt(2)*x_opt(3))*35; fprintf(['\n','optimum value without penalty is ' num2str(f_wop) ]); if round(f_opt,4)==round(f_wop,4) fprintf(['\n','all constraints are satisfied ']); %the result is stored in satisfaction array. satisfaction(z,1)="Satisfied"; else fprintf(['\n','some constraints are not satisfied increase penalty value ']); %the result is stored in satisfaction array. satisfaction(z,1)="Not Satisfied"; end end %objective function function fi = FuncValue(x,r) G = ConstraintVal(x); h=x(1); b=x(2); tf=x(3); tw=x(4); L=35; penalty=r*(max(0,G(1,1))^2+max(0,G(2,1))^2+max(0,G(3,1))^2+max(0,G(4,1))^2+max(0,G(5,1))^2+max(0,G(6,1))^2+max(0,G(7,1))^2+max(0,G(8,1))^2+max(0,G(9,1))^2+max(0,G(10,1))^2+max(0,G(11,1))^2+max(0,G(12,1))^2+max(0,G(13,1))^2+max(0,G(14,1))^2); fi = (h*tw+2*b*tf)*L+penalty; %normalized constraints function G = ConstraintVal(x) h=x(1); b=x(2); tf=x(3); tw=x(4); L=35; Pm=104; Ps=155; E=200; A=h*tw+2*b*tf; I=1/12*tw*h^3+2/3*b*tf^3+1/2*b*tf*h*(h+2*tf); w=19+77*A; M=L/8*(2*Pm+w*L); sigma=M/(1000*I)*(0.5*h+tf); sigma_f=72845*(tf/b)^2; sigma_w=3648276*(tw/h)^2; S=0.5*(Ps+w*L); D=(L^3/(384*10^6*E*I))*(8*Pm+5*w*L); tao=S/(1000*h*tw); %limitations sigma_y=250; sigma_a=0.55*sigma_y; tao_a=0.33*sigma_y; sigma_t=243; D_a=L/800; G(1,1) = sigma/sigma_a-1; G(2,1) = sigma/sigma_f-1; G(3,1) = sigma/sigma_w-1; G(4,1)= tao/tao_a-1; G(5,1) = D/D_a-1; G(6,1)= sigma/(0.5*sigma_t)-1; G(7,1)= h/5-1; G(8,1)= 1-h/1; G(9,1)= b/2.5-1; G(10,1)= 1-b/0.25; G(11,1)= tf/0.10-1; G(12,1)=1-tf/0.01; G(13,1)= tw/0.10-1; G(14,1)=1-tw/0.01; end end
package com.example.javafxproject.DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class PedidoDAO { public Pedido criar(int idCliente, String dataPedido) { Pedido pedido = null; String sql = "INSERT INTO pedidos (id_cliente, data_pedido) VALUES (?, ?);"; try ( Connection connection = Conexao.getConnection(); PreparedStatement statement = connection .prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); ) { statement.setInt(1, idCliente); statement.setString(2, dataPedido); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { pedido = new Pedido(rs.getInt(1), idCliente, dataPedido); } rs.close(); return pedido; } catch (SQLException e) { e.printStackTrace(); return null; } } public List<Pedido> listarTodos() { String sql = "SELECT * FROM pedidos;"; List<Pedido> pedidos = new ArrayList<>(); try ( Connection connection = Conexao.getConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); ) { while (rs.next()) { pedidos.add( new Pedido( rs.getInt("id"), rs.getInt("id_cliente"), rs.getString("data_pedido") ) ); } } catch (SQLException e) { e.printStackTrace(); return pedidos; } return pedidos; } public Pedido buscarPorId(Integer id) { String sql = "SELECT * FROM pedidos WHERE id = ?;"; try ( Connection connection = Conexao.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); ) { statement.setInt(1, id); ResultSet rs = statement.executeQuery(); if (rs.next()) { return new Pedido( rs.getInt("id"), rs.getInt("id_cliente"), rs.getString("data_pedido") ); } rs.close(); } catch (SQLException e) { e.printStackTrace(); return null; } return null; } }
package com.olsoftware.inventario.factory; import static com.olsoftware.inventario.constant.StatusConstant.*; import org.springframework.stereotype.Component; import com.olsoftware.inventario.factory.base.BaseFactory; import com.olsoftware.inventario.factory.base.BaseFactoryImpl; import com.olsoftware.inventario.model.status.StatusDto; import com.olsoftware.inventario.model.status.StatusRequest; import com.olsoftware.inventario.service.status.StatusService; @Component public class StatusFactory extends BaseFactoryImpl<StatusRequest, StatusDto, String, StatusService> implements BaseFactory<StatusRequest, StatusDto>{ protected StatusFactory(StatusService _service) { super(_service); } @Override public StatusDto create() { return super.create(request()); } public StatusDto create(StatusRequest request) { return super.create(request); } @Override public StatusRequest request() { return new StatusRequest( faker.lorem().characters(MAX_STATUS_ID_LENGTH), faker.lorem().characters(MAX_STATUS_NAME_LENGTH) ); } }
const { google } = require("googleapis"); const getPosts = async (req, res) => { const auth = new google.auth.GoogleAuth({ keyFile: "credentials.json", scopes: "https://www.googleapis.com/auth/spreadsheets", }); // Create client instance for auth const client = await auth.getClient(); // Instance of Google Sheets API const googleSheets = google.sheets({ version: "v4", auth: client }); const spreadsheetId = "1oyv6JmL1S4UL0JJ8ttEh932n54J4qqNXS3Tid4kbZ_4"; try { // Read rows from spreadsheet const getRows = await googleSheets.spreadsheets.values.get({ auth, spreadsheetId, range: "Sheet1!A:E", }); res.status(200).json(getRows.data.values); } catch (error) { res.status(404).json({ messitem: error.messitem }); console.log("error" + error.messitem); } }; const createPosts = async (req, res) => { const { date, item, income, expense,accounttype } = req.body; const auth = new google.auth.GoogleAuth({ keyFile: "credentials.json", scopes: "https://www.googleapis.com/auth/spreadsheets", }); // Create client instance for auth const client = await auth.getClient(); // Instance of Google Sheets API const googleSheets = google.sheets({ version: "v4", auth: client }); const spreadsheetId = "1oyv6JmL1S4UL0JJ8ttEh932n54J4qqNXS3Tid4kbZ_4"; // Get metadata about spreadsheet const metaData = await googleSheets.spreadsheets.get({ auth, spreadsheetId, }); // Write row(s) to spreadsheet await googleSheets.spreadsheets.values.append({ auth, spreadsheetId, range: "Sheet1!A:B", valueInputOption: "USER_ENTERED", resource: { values: [[date, item, income, expense,accounttype]], }, }); res.send("Successfully submitted! Thank you!"); }; const UpdatePosts = async (req, res) => { const { date, item, income, expense,accounttype } = req.body; console.log("req.body", req.body); const { range } = req.params; console.log("range", range); const auth = new google.auth.GoogleAuth({ keyFile: "credentials.json", scopes: "https://www.googleapis.com/auth/spreadsheets", }); // Create client instance for auth const client = await auth.getClient(); // Instance of Google Sheets API const googleSheets = google.sheets({ version: "v4", auth: client }); const spreadsheetId = "1oyv6JmL1S4UL0JJ8ttEh932n54J4qqNXS3Tid4kbZ_4"; // Get metadata about spreadsheet const metaData = await googleSheets.spreadsheets.get({ auth, spreadsheetId, }); // Write row(s) to spreadsheet await googleSheets.spreadsheets.values.update({ auth, spreadsheetId, range: range, valueInputOption: "USER_ENTERED", resource: { majorDimension: "ROWS", values: [[date, item, income, expense,accounttype]], }, }); res.send("Successfully submitted! Thank you!"); }; const clearPosts = async (req, res) => { const { range } = req.params; console.log("range", range); const auth = new google.auth.GoogleAuth({ keyFile: "credentials.json", scopes: "https://www.googleapis.com/auth/spreadsheets", }); // Create client instance for auth const client = await auth.getClient(); // Instance of Google Sheets API const googleSheets = google.sheets({ version: "v4", auth: client }); const spreadsheetId = "1oyv6JmL1S4UL0JJ8ttEh932n54J4qqNXS3Tid4kbZ_4"; // Write row(s) to spreadsheet await googleSheets.spreadsheets.values.clear({ auth, spreadsheetId, range: range, }); res.send("Successfully submitted! Thank you!"); }; module.exports = { getPosts, createPosts, clearPosts, UpdatePosts };
import { useEffect, useState } from "react"; import protobuf from "protobufjs"; import { Buffer } from "buffer"; import { Table, TableHeader, TableColumn, TableBody, TableRow, TableCell, } from "@nextui-org/react"; function App() { const API_ENDPOINT = "https://query1.finance.yahoo.com/v8/finance/chart/"; const SymbolList = ["SBIN.NS"]; // Add your list of symbols here const fetchDataForSymbol = async (symbol) => { try { const response = await fetch(`${API_ENDPOINT}${symbol}`); const data = await response.json(); // Process the data as needed console.log(`Data for ${symbol}:`, data); } catch (error) { console.error(`Error fetching data for ${symbol}:`, error); } }; // const [stockdetail, setStockdetail] = useState(); // const [direction, setDirection] = useState(""); // useEffect(() => { // const ws = new WebSocket("wss://streamer.finance.yahoo.com"); // const root = protobuf.load("../YPricingData.proto", (error, root) => { // if (error) { // return console.log(error); // } // const Yaticker = root.lookupType("yaticker"); // ws.onopen = function open() { // console.log("connected"); // ws.send( // JSON.stringify({ // subscribe: ["SBIN.NS"], // }) // ); // }; // ws.onclose = function close() { // console.log("disconnected"); // }; // ws.onmessage = function incoming(message) { // const next = Yaticker.decode(new Buffer(message.data, "base64")); // if (stockdetail) { // const nextdirection = // stockdetail.price < next ? "up" : stockdetail.price ? "down" : ""; // if (nextdirection) { // setDirection(nextdirection); // } // } // setStockdetail(next); // }; // }); // }, []); useEffect(() => { const fetchData = () => { SymbolList.forEach((symbol) => { fetchDataForSymbol(symbol); }); }; // Fetch data initially fetchData(); // Set up interval to fetch data every 3 seconds const intervalId = setInterval(fetchData, 3000); // Clean up the interval when the component is unmounted return () => clearInterval(intervalId); }, []); // Empty dependency array means this effect runs once when the component mounts return ( <div className="App"> <h1>stockology</h1> <div></div> <Table> <TableHeader> <TableColumn>Display Name</TableColumn> <TableColumn>Price</TableColumn> <TableColumn>% Change</TableColumn> <TableColumn>OL</TableColumn> <TableColumn>OH</TableColumn> </TableHeader> <TableBody> <TableRow key="1"> <TableCell>ADANI PORTS AND SPECIAL ECONOMIC ZONE LTD</TableCell> <TableCell>878.7</TableCell> <TableCell>%2.0</TableCell> <TableCell>860</TableCell> <TableCell>872</TableCell> </TableRow> <TableRow key="2"> <TableCell>ASIAN PAINTS LTD.</TableCell> <TableCell>3196</TableCell> <TableCell>%2.0</TableCell> <TableCell>860</TableCell> <TableCell>872</TableCell> </TableRow> <TableRow key="3"> <TableCell>AXIS BANK LTD.</TableCell> <TableCell>878.7</TableCell> <TableCell>%2.0</TableCell> <TableCell>860</TableCell> <TableCell>872</TableCell> </TableRow> <TableRow key="4"> <TableCell>BAJAJ AUTO LTD.</TableCell> <TableCell>878.7</TableCell> <TableCell>%2.0</TableCell> <TableCell>860</TableCell> <TableCell>872</TableCell> </TableRow> <TableRow key="5"> <TableCell>Bajaj Finance Limited</TableCell> <TableCell>878.7</TableCell> <TableCell>%2.0</TableCell> <TableCell>860</TableCell> <TableCell>872</TableCell> </TableRow> </TableBody> </Table> {/* <div className="stonk"> <marquee direction="left"> {stockdetail && ( <h2 className=" digi_text text-4xl"> {stockdetail.id} {stockdetail.price.toFixed(2)} INR </h2> )} </marquee> </div> */} </div> ); } export default App;
<template> <div class="edit-data"> <div class="edit-data-list"> <Form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="formRef" > <FormItem label="代理商ID:" nameID="nameID"> <Input disabled v-model:value="formState.nameID" /> </FormItem> <FormItem label="手机号:" phone="phone"> <Input disabled v-model:value="formState.phone" /> </FormItem> <FormItem label="代理商名称:" name="name"> <Input v-model:value="formState.name" /> </FormItem> <FormItem label="所属地区:" name="region"> <AgentRegion /> </FormItem> <FormItem label="详细地址:" name="desc"> <Input v-model:value="formState.desc" type="textarea" /> </FormItem> <FormItem label="负责人:" name="charge"> <Input v-model:value="formState.charge" type="textarea" /> </FormItem> <FormItem label="客户运营:" name="operate"> <Select class="form-select" v-model:value="formState.operate" :options="options" /> </FormItem> <FormItem label="业务代表:" name="merchant"> <Select class="form-select" v-model:value="formState.merchant" :options="options" /> </FormItem> <br /> <br /> <FormItem :wrapper-col="{ offset: 6 }"> <Button @click="onSubmit" style=" width: 242px; height: 35px; background-color: rgba(26, 188, 156, 1); color: #ffffff; " >提交</Button > </FormItem> </Form> </div> </div> </template> <script lang="ts"> import AgentRegion from '/@/modules/CustomerModule/AgentPages/component/AgentRegion.vue' import { Dayjs } from 'dayjs' import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface' import { Button, Form, Input, Select, message } from 'ant-design-vue' import { defineComponent, reactive, toRaw, UnwrapRef, ref } from 'vue' import { SelectTypes } from 'ant-design-vue/es/select' interface FormState { nameID: string phone: string name: string region: string | undefined date1: Dayjs | undefined delivery: boolean type: string[] resource: string desc: string charge: string operate: string merchant: string } export default defineComponent({ components: { Button, Form, FormItem: Form.Item, Input, Select, AgentRegion }, // props: { // childVisible: Boolean, // }, emits: { click: null }, setup() { // console.log(props) const formState: UnwrapRef<FormState> = reactive({ nameID: '864522', phone: '18888888888', name: '长葛姜天龙', region: undefined, date1: undefined, delivery: false, type: [], resource: '', desc: '正商木华广场3号楼A座7层', charge: '张三', operate: '', merchant: '', }) const onSubmit = () => { formRef.value .validate() .then(() => { console.log('values', formState, toRaw(formState)) message.success('编辑成功') // emit('click', false) }) .catch((error: ValidateErrorEntity<FormState>) => { console.log('error', error) }) } const formRef = ref() const rules = { name: [ { required: true, message: '请输入代理商名称', trigger: 'blur' }, // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' }, options: ['张三', '李四', '王五', '赵六'], ], region: [{ required: false, message: '请输入地区', trigger: 'change' }], desc: [{ required: true, message: '请输入地址', trigger: 'blur' }], charge: [{ required: true, message: '请输入负责人', trigger: 'blur' }], operate: [{ required: true, message: '请输入客户运营', trigger: 'blur' }], merchant: [{ required: true, message: '请输入业务代表', trigger: 'blur' }], } const options = ref<SelectTypes['options']>([ { value: '张三', label: '张三' }, { value: '李四', label: '李四' }, { value: '王五', label: '王五' }, ]) return { formRef, labelCol: { span: 8 }, wrapperCol: { span: 14 }, formState, onSubmit, rules, value1: ref('张三'), options, } }, }) </script> <style lang="less" scoped> .edit-data { width: 1100px; height: 723px; .edit-data-list { position: absolute; width: 400px; height: 600px; left: 50%; top: 120px; transform: translate(-50%, 0); .form-select { width: 235px; } } } </style>
const { changeEndTimePromotion } = require("../utils"); function timer(id, deadline) { const endTimePromotion = document.querySelector(".promotion__end"); changeEndTimePromotion(deadline, endTimePromotion); function getTimeRemaining(endtime) { let days, hours, minutes, seconds; const t = Date.parse(endtime) - Date.parse(new Date()); if (t <= 0) { days = 0; hours = 0; minutes = 0; seconds = 0; } else { days = Math.floor(t / (24 * 3600 * 1000)); hours = Math.floor((t / (3600 * 1000)) % 24); minutes = Math.floor((t / 60 / 1000) % 60); seconds = Math.floor((t / 1000) % 60); } return { total: t, days, hours, minutes, seconds, }; } function setZero(num) { if (num >= 0 && num < 10) { return `0${num}`; } else { return num; } } function setClock(selector, endtime) { const timer = document.querySelector(selector); const days = timer.querySelector("#days"); const hours = timer.querySelector("#hours"); const minutes = timer.querySelector("#minutes"); const seconds = timer.querySelector("#seconds"); const timeInterval = setInterval(updateClock, 1000); updateClock(); function updateClock() { const time = getTimeRemaining(endtime); days.innerHTML = setZero(time.days); hours.innerHTML = setZero(time.hours); minutes.innerHTML = setZero(time.minutes); seconds.innerHTML = setZero(time.seconds); if (time.total <= 0) { clearInterval(timeInterval); } } } setClock(id, deadline); } export default timer;
import { createCatchphrase } from "./createCatchphrase"; describe("createCatchphrase", () => { type LanguageCode = "de" | "en"; type TranslationType = { Greeting: (name: string) => string; }; it("should set the default language", () => { const { getLanguage } = createCatchphrase<LanguageCode>({ languageSelector: () => "de", }); expect(getLanguage()).toStrictEqual<LanguageCode>("de"); }); it("should translate a string using the defaultLanguage", () => { const { createTranslation } = createCatchphrase<LanguageCode>({ languageSelector: () => "de", }); const { getTranslations } = createTranslation<TranslationType>(() => ({ de: { Greeting: name => `Hallo ${name}`, }, en: { Greeting: name => `Hello ${name}`, }, })); const { Greeting } = getTranslations(); expect(Greeting("André")).toStrictEqual("Hallo André"); }); });
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Create Product</title> </head> <body> <h1> <a href="/products">List Product</a> </h1> <br> <h1>Create Product</h1> <h3> <c:if test='${message != null}'> <span style="color: green">${message}</span> </c:if> </h3> <form method="post"> <table> <tr> <td> <label>Name</label> </td> <td> <input type="text" name = "name" id="name"> </td> </tr> <tr> <td> <label>Price</label> </td> <td> <input type="number" name="price" id="price"> </td> </tr> <tr> <td> <label>Quantity</label> </td> <td> <input type="number" name="quantity" id="quantity"> </td> </tr> <tr> <td> <label>Color</label> </td> <td> <input type="text" name="color" id="color"> </td> </tr> <tr> <td> <label>Description</label> </td> <td> <input type="text" name="description" id="description"> </td> </tr> <tr> <td> <label>Category</label> </td> <td> <select name="category" id="category"> <c:forEach items='${requestScope["categoryList"]}' var="category"> <option value="${category.getNameCategory()}">${category.getNameCategory()}</option> </c:forEach> </select> </td> </tr> <tr> <td> <button type="submit"> Create </button> </td> <td> <button type="button" onclick="window.location.href ='${pageContext.request.contextPath}/products'"> Back </button> </td> </tr> </table> </form> </body> </html>
import React, { useState } from "react"; import { useNavigate } from "react-router-dom"; import { AppData } from "../constants/Data"; import { questions } from "../constants/question"; function CollegeInput() { const [option1, setOption1] = useState(""); const [option2, setOption2] = useState(""); const [inputValue, setInputValue] = useState(""); const [isWeb, setIsWeb] = useState(false); const [isApp, setIsApp] = useState(false); const [answers, setAnswers] = useState({}); const [result, setresult] = useState(0); const navigate = useNavigate(); const filteredIdea = AppData.filter((college) => college.toLowerCase().startsWith(inputValue.toLowerCase()) ); const handleCheckboxChange = (e) => { const { id, value, checked } = e.target; setAnswers({ ...answers, [id]: checked ? value : undefined }); }; const formatTargetValue = (data) =>{ let value=data; if(value=="short(1-5)"){ return "short" } else if(value=="Medium (5-8)"){ return "medium" }else if(value=="long(more than 8 months)"){ return "long" }else if(value=="Very small (1-5)"){ return "very small" }else if(value=="Small (5-10)"){ return "small" }else if(value=="Medium (10-50)"){ return "medium" }else if(value=="Large (More than 50)"){ return "large" } } function handleOption1Change(event) { const value= formatTargetValue(event.target.value); setOption1(value); } function handleOption2Change(event) { const value= formatTargetValue(event.target.value); setOption2(value); } function handleWebCheckboxChange() { setIsWeb(!isWeb); setIsApp(false); } function handleAppCheckboxChange() { setIsApp(!isApp); setIsWeb(false); } const add = () => { const sum = Object.values(answers).reduce((total, value) => { return total + Number(value); // add value to total, converting to a number }, 0); setresult(sum); return sum; }; function handlecheck() { //check for desgin if (result >= 6) { return "advanced"; } else if (result < 6 && result > 3) { return "intermediate"; } else { return "basic"; } } function handleSubmit(event) { event.preventDefault(); const res = handlecheck(); if (projectype === "app") { navigate("/app", { replace: true, state: { option1, option2, inputValue, projectype, res }, }); } else if (projectype === "web") { navigate("/web", { replace: true, state: { option1, option2, inputValue, projectype, res }, }); } else { navigate("/secondpage", { replace: true, state: { option1, option2, inputValue, projectype, res }, }); } } let projectype = ""; if (isApp) { projectype = "app"; } else if (isWeb) { projectype = "web"; } return ( <form onSubmit={handleSubmit}> <label> Time Duration: in months <select value={option1} onChange={handleOption1Change}> <option>Select an month</option> <option value="short(1-5)">short(1-5)</option> <option value="Medium (5-8)"> Medium (5-8)</option> <option value="long(more than 8 months)"> long(more than 8 months) </option> </select> </label> <br /> <label> Team Size: <select value={option2} onChange={handleOption2Change}> <option>Select an team size</option> <option value="Very small (1-5)"> Very small (1-5)</option> <option value="Small (5-10)"> Small (5-10)</option> <option value="Medium (10-50)"> Medium (10-50)</option> <option value="Large (More than 50)"> Large (More than 50)</option> </select> </label> <br /> <div> <label> App Idea: <input type="text" list="colleges" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <datalist id="colleges"> {filteredIdea.map((college) => ( <option value={college} key={college} /> ))} </datalist> </label> </div> <p>Designing skills</p> <div> {questions.map((q) => ( <div key={q.id}> <p>{q.question}</p> {q.options.map((option) => ( <div key={option.value}> <label> <input type="checkbox" id={q.id} value={option.value} checked={answers[q.id] === option.value} onChange={handleCheckboxChange} /> {option.text} </label> </div> ))} </div> ))} </div> <div> <label>Project Type:</label> <label> <input type="checkbox" checked={isWeb} value="Web" onChange={handleWebCheckboxChange} /> Web </label> <label> <input type="checkbox" checked={isApp} value="App" onChange={handleAppCheckboxChange} /> App </label> </div> <button onClick={() => add()} type="submit"> Next </button> </form> ); } export default CollegeInput;
import React from 'react'; import {Route, Routes } from 'react-router-dom'; import { Home,ProductsList,ProductDetail,Cart, Wishlist } from '../pages'; import Header from './Header'; import Footer from './Footer'; import { ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const App = () => { return ( <div className="App"> <ToastContainer // for notifications position="top-center" autoClose={1000} hideProgressBar={false} newestOnTop closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover theme="dark" /> <Header /> <Routes> <Route path="/" element={<Home />} /> <Route path="/products/:category" element={<ProductsList />} /> <Route path="/products/details/:productId" element={<ProductDetail />} /> <Route path="/cart" element={<Cart />} /> <Route path="/wishlist" element={<Wishlist />} /> </Routes> <Footer /> </div> ); }; export default App;
<!DOCTYPE html> <html lang="fr"> <head> {# ######################################## meta ######################################## #} <meta charset="UTF-8"> <meta name="author" content="Grégoire CONSTANT"> <meta http-equiv="X-UA-Compatible" content="IE=7"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="{% block description %}{% endblock %}"> {# ######################################## title ######################################## #} <title>Portfolio - {% block title %}{% endblock %}</title> {# ######################################## Bootstrap ######################################## #} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"> {# ######################################## Google ######################################## #} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Amatic+SC&family=Open+Sans:wght@300&display=swap"> {# ######################################## favicon ######################################## #} <link rel="apple-touch-icon" sizes="180x180" href="{{ asset('img/favicon/apple-touch-icon.png') }}"> <link rel="icon" type="image/png" sizes="32x32" href="{{ asset('img/favicon/favicon.png') }}"> <link rel="icon" type="image/png" sizes="16x16" href="{{ asset('img/favicon/favicon.png') }}"> <link rel="manifest" href="{{ asset('img/favicon/site.webmanifest') }}"> {# ######################################## custom CSS ######################################## #} <link rel="stylesheet" href="{{ asset('css/base.css') }}"> <link rel="stylesheet" href="{{ asset('css/admin.css') }}"> <link rel="stylesheet" href="{{ asset('css/app.css') }}"> {% block stylesheets %}{% endblock %} </head> <body> <header> {% include "_partials/header.html.twig" %} </header> <main> {% block body %}{% endblock %} {% include "_partials/project.html.twig" %} {% include "_partials/skill.html.twig" %} {% include "_partials/about.html.twig" %} {% include "_partials/form.html.twig" %} </main> <footer> {% include "_partials/footer.html.twig" %} </footer> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <script src="{{ asset('js/base.js') }}"></script> {% block javascripts %}{% endblock %} </body> </html>
package antifraud.data; import antifraud.entity.Transaction; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.time.LocalDateTime; @Repository public interface TransactionRepository extends JpaRepository<Transaction, Long> { @Query(value = "SELECT count(distinct(ip)) FROM TRANSACTION where number = :number and date between :start and :end ;", nativeQuery = true) int countIpAddressesInLastHour( @Param("number") String number, @Param("start") LocalDateTime start, @Param("end") LocalDateTime end); @Query(value = "SELECT distinct(ip) FROM TRANSACTION where number = :number and date between :start and :end ;", nativeQuery = true) Iterable<String> getIpAddressesInLastHour( @Param("number") String number, @Param("start") LocalDateTime start, @Param("end") LocalDateTime end); @Query(value = "SELECT count(distinct(region)) FROM TRANSACTION where number = :number and date between :start and :end ;", nativeQuery = true) int countRegionsInLastHour( @Param("number") String number, @Param("start") LocalDateTime start, @Param("end") LocalDateTime end); @Query(value = "SELECT distinct(region) FROM TRANSACTION where number = :number and date between :start and :end ;", nativeQuery = true) Iterable<String> getRegionsInLastHour( @Param("number") String number, @Param("start") LocalDateTime start, @Param("end") LocalDateTime end); Iterable<Transaction> findAllByNumber(String number); }
@extends('layouts.app') @section('content') <section class="mt-5 px-1 px-lg-5"> <div class="d-flex align-items-center gap-2"> <a class="btn btn-tool" href="{{ route('servers.keys.index', $server->id) }}"> <x-svg.arrow-left width="20" height="20" /> </a> <h2>{{ __('Editing :key', ['key' => $key->name]) }}</h2> </div> <form action="{{ route('servers.keys.update', [$server->id, $key->id]) }}" method="post"> @csrf @method('PATCH') <section class="d-grid gap-3 my-3"> <section> <label for="name" class="ps-1 mb-1">{{ __('Name') }}</label> <input class="d-block" id="name" name="name" required value="{{ old('name', $key->name) }}" autofocus> @error('name')<small class="ps-1 error-message">{{ $message }}</small>@enderror </section> <section> <label for="data_limit" class="ps-1 mb-1">{{ __('Data limit') }}</label> <input class="d-block" id="data_limit" type="number" name="data_limit" value="{{ old('data_limit', $key->data_limit) }}" placeholder="Data limit in bytes"> @error('data_limit')<small class="ps-1 error-message">{{ $message }}</small>@enderror </section> <section> <label for="expires_at" class="ps-1 mb-1">{{ __('Expiration date') }}</label> <input class="d-block" id="expires_at" type="datetime-local" name="expires_at" value="{{ old('expires_at', $key->expires_at?->format('Y-m-d\TH:i')) }}" min="{{ now()->format('Y-m-d\TH:i') }}"> @error('expires_at')<small class="ps-1 error-message">{{ $message }}</small>@enderror </section> </section> <button class="btn btn-primary">{{ __('Update') }}</button> </form> </section> @endsection
#include <iostream> #include <string> #include <vector> #include <stack> using namespace std; class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; int length = tokens.size(); for (int i = 0; i < length; i++) { string token = tokens[i]; if (isNumber(token)) { stk.push(stoi(token)); } else { int num2 = stk.top(); stk.pop(); int num1 = stk.top(); stk.pop(); switch (token[0]) { case '+': stk.push(num1 + num2); break; case '-': stk.push(num1 - num2); break; case '*': stk.push(num1 * num2); break; case '/': stk.push(num1 / num2); break; default: break; } } } return stk.top(); } bool isNumber(string token) { return !(token == "+" || token == "-" || token == "*" || token == "/"); } }; int main() { vector<string> tokens = {"2","1","+","3","*"}; Solution sol; int result = sol.evalRPN(tokens); cout << "result = " << result << endl; system("pause"); return 0; }
package com.codeforinca.bytsoftcore.core.abstractions.repository; import com.codeforinca.bytsoftcore.core.implemantations.entity.IEntity; import com.codeforinca.bytsoftcore.core.implemantations.repository.IBaseRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; public abstract class ABaseRepo<T extends IEntity,ID extends Long> implements IBaseRepo<T,ID> { @Autowired private EntityManager entityManager; private Class<T> entityClass; public ABaseRepo( Class<T> entity ){ entityClass = entity; } protected Class<T> getEntityClass(){ return entityClass; } public EntityManager getEntityManager() { return entityManager; } public void setEntityManager( EntityManager entityManager ){ this.entityManager = entityManager; } @Transactional @Override public T save( T entity ){ entityManager.persist(entity); return entity; } @Transactional @Override public T update( T entity ){ return entityManager.merge(entity); } @Transactional @Override public void delete( ID id ){ T entity = findById(id); entityManager.remove(entity); } @Transactional @Override public T findById( ID id ){ return entityManager.createQuery("from "+getEntityClass().getName()+" where id = :id",getEntityClass()) .setParameter("id",id) .getSingleResult(); } @Transactional @Override public List<T> findAll( ){ return entityManager.createQuery("from "+getEntityClass().getName()).getResultList(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Net; namespace System.Text.RuntimeRegexCopy.Symbolic { /// <summary>Captures a state explored during matching.</summary> public sealed class MatchingState<TSet> where TSet : IComparable<TSet>, IEquatable<TSet> { internal MatchingState(SymbolicRegexNode<TSet> node, uint prevCharKind) { Node = node; PrevCharKind = prevCharKind; } /// <summary>The regular expression that labels this state and gives it its semantics.</summary> public SymbolicRegexNode<TSet> Node { get; } /// <summary> /// The kind of the previous character in the input. The <see cref = "SymbolicRegexMatcher{TSet}"/> is responsible /// for ensuring that in all uses of this state this invariant holds by both selecting initial states accordingly /// and transitioning on each character to states that match that character's kind. /// </summary> /// <remarks> /// Tracking this information is an optimization that allows each transition taken in the matcher to only depend /// on the next character (and its kind). In general, the transitions from a state with anchors in its pattern /// depend on both the previous and the next character. Creating distinct states for each kind of the previous /// character embeds the necessary information about the previous character into the state space of the automaton. /// However, this does incur a memory overhead due to the duplication of states. For patterns with no anchors /// this will always be set to <see cref = "CharKind.General"/>, which can reduce the number of states created. /// /// The performance effect of this optimization has not been investigated. If this optimization were removed, the /// transition logic would in turn have to become more complicated for derivatives that depend on the nullability /// of anchors. Care should be taken to not slow down transitions without anchors involved. /// </remarks> public uint PrevCharKind { get; } /// <summary> /// A unique identifier for this state, which is used in <see cref = "SymbolicRegexMatcher{TSet}"/> to index into /// state information and transition arrays. Valid IDs are always >= 1. /// </summary> public int Id { get; set; } /// <summary>Whether this state is known to be a dead end, i.e. no nullable states are reachable from here.</summary> public bool IsDeadend(ISolver<TSet> solver) => Node.IsNothing(solver); /// <summary> /// Returns the fixed length that any match ending with this state must have, or -1 if there is no such /// fixed length, <see cref = "SymbolicRegexNode{TSet}.ResolveFixedLength(uint)"/>. The context is defined /// by <see cref = "PrevCharKind"/> of this state and the given nextCharKind. The node must be nullable here. /// </summary> public int FixedLength(uint nextCharKind) { Debug.Assert(IsNullableFor(nextCharKind)); Debug.Assert(CharKind.IsValidCharKind(nextCharKind)); uint context = CharKind.Context(PrevCharKind, nextCharKind); return Node.ResolveFixedLength(context); } /// <summary>If true then state starts with a ^ or $ or \Z</summary> public bool StartsWithLineAnchor => Node._info.StartsWithLineAnchor; /// <summary> /// Compute the target state for the given input minterm. /// If <paramref name = "minterm"/> is False this means that this is \n and it is the last character of the input. /// </summary> /// <param name = "builder">the builder that owns <see cref = "Node"/></param> /// <param name = "minterm">minterm corresponding to some input character or False corresponding to last \n</param> /// <param name = "nextCharKind"></param> public SymbolicRegexNode<TSet> Next(SymbolicRegexBuilder<TSet> builder, TSet minterm, uint nextCharKind) { // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the derivative of the node for the given context return Node.CreateDerivativeWithoutEffects(builder, minterm, context); } /// <summary> /// Compute a set of transitions for the given minterm. /// </summary> /// <param name = "builder">the builder that owns <see cref = "Node"/></param> /// <param name = "minterm">minterm corresponding to some input character or False corresponding to last \n</param> /// <param name = "nextCharKind"></param> /// <returns>an enumeration of the transitions as pairs of the target state and a list of effects to be applied</returns> public List<(SymbolicRegexNode<TSet> Node, DerivativeEffect[] Effects)> NfaNextWithEffects(SymbolicRegexBuilder<TSet> builder, TSet minterm, uint nextCharKind) { // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the transitions for the given context return Node.CreateNfaDerivativeWithEffects(builder, minterm, context); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsNullableFor(uint nextCharKind) { Debug.Assert(CharKind.IsValidCharKind(nextCharKind)); uint context = CharKind.Context(PrevCharKind, nextCharKind); return Node.IsNullableFor(context); } /// <summary> /// Builds a <see cref = "StateFlags"/> with the relevant flags set. /// </summary> /// <param name = "solver">a solver for <typeparamref name = "TSet"/></param> /// <param name = "isInitial">whether this state is an initial state</param> /// <returns>the flags for this matching state</returns> public StateFlags BuildStateFlags(ISolver<TSet> solver, bool isInitial) { StateFlags info = 0; if (isInitial) { info |= StateFlags.IsInitialFlag; } if (IsDeadend(solver)) { info |= StateFlags.IsDeadendFlag; } if (Node.CanBeNullable) { info |= StateFlags.CanBeNullableFlag; if (Node.IsNullable) { info |= StateFlags.IsNullableFlag; } } if (Node.Kind != SymbolicRegexNodeKind.DisableBacktrackingSimulation) { info |= StateFlags.SimulatesBacktrackingFlag; } return info; } public override bool Equals(object? obj) => obj is MatchingState<TSet> s && PrevCharKind == s.PrevCharKind && Node.Equals(s.Node); public override int GetHashCode() => HashCode.Combine(PrevCharKind, Node); #if DEBUG public override string ToString() => PrevCharKind == 0 ? Node.ToString() : $"({CharKind.DescribePrev(PrevCharKind)},{Node})"; #endif } }
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const User_1 = __importDefault(global[Symbol.for('ioc.use')]("App/Models/User")); const CrudController_1 = __importDefault(require("./CrudController")); const Validator_1 = global[Symbol.for('ioc.use')]("Adonis/Core/Validator"); class UsersController extends CrudController_1.default { constructor() { super(...arguments); this.model = User_1.default; this.relationships = ['profile']; } async store({ request, response }) { const validatedSchema = Validator_1.schema.create({ firstName: Validator_1.schema.string(), lastName: Validator_1.schema.string(), email: Validator_1.schema.string([Validator_1.rules.email()]), password: Validator_1.schema.string([Validator_1.rules.minLength(6)]), }); const payload = await request.validate({ schema: validatedSchema }); const model = this.model; const result = await model.create({ email: payload.email, isAdmin: false, password: payload.password, }); await result.related('profile').create({ firstName: payload.firstName.trim(), lastName: payload.lastName.trim(), }); return response.status(201).json(result); } async update({ request, response }) { const validatedSchema = Validator_1.schema.create({ firstName: Validator_1.schema.string(), lastName: Validator_1.schema.string(), email: Validator_1.schema.string([Validator_1.rules.email()]), }); const payload = await request.validate({ schema: validatedSchema }); const model = this.model; const data = await model.findOrFail(request.param('id')); data.merge({ email: payload.email, }); const result = await data.save(); const profile = await data.related('profile').firstOrCreate({}); profile.firstName = payload.firstName; profile.lastName = payload.lastName; await profile.save(); return response.status(200).json(result); } } exports.default = UsersController; //# sourceMappingURL=UsersController.js.map
const Cart = require('../models/cartModel'); const addCart = async (req, res) => { const userId = req.session.user._id; // '65ca49d62e48dc4ba71cd022'; const item = req.body.item; if (!item.quantity) { item.quantity = 1; } try { let cart = await Cart.findOne({ userId }); if (cart) { const itemIndex = cart.items.findIndex((el) => item._id === el._id); if (itemIndex !== -1) { cart.items.splice(itemIndex, 1, item); } else { cart.items.push(item); } } else { cart = new Cart(); cart.userId = userId; cart.items = [item]; cart.save; } await cart.save(); return res.status(200).json({ message: 'Item added to the cart', data: cart }); } catch (error) { console.error('Error while adding item to the cart: ', error); return res.status(500).json({ message: error.message }); } }; const getCart = async (req, res) => { try { const userId = req.session.user._id; // '65ca49d62e48dc4ba71cd022'; const cart = await Cart.findOne({ userId }); return res.status(200).json({ totalCart: cart?.length || 0, data: cart ? cart : { userId, items: [] } // items: cart }); } catch (error) { console.log('Error while fetching the products: ', error); return res.status(500).json({ message: error.message }); } }; const deleteCart = async (req, res) => { try { const userId = req.session.user._id; // '65ca49d62e48dc4ba71cd022'; const itemId = req.params.id; let cart = await Cart.findOne({ userId }); if (itemId && cart) { const itemIndex = cart.items.findIndex((el) => itemId == el._id); cart.items.splice(itemIndex, 1); cart = await cart.save(); } return res.status(200).json({ totalCart: cart.length, data: cart ? cart : { userId, items: [] } }); } catch (error) { console.log('Error while fetching the products: ', error); return res.status(500).json({ message: error.message }); } }; const clearCart = async (req, res) => { try { const userId = req.session.user._id; // '65ca49d62e48dc4ba71cd022'; const cart = await Cart.findOne({ userId }); cart.items = []; await cart.save(); return res.status(200).json({ message: 'Cart cleared', data: cart }); } catch (error) { return res.status(500).json({ message: error.message }); } }; module.exports = { addCart, getCart, deleteCart, clearCart };
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace LibraryOrganizer.Models { public class Author { public int AuthorId { get; set; } // PK [Display(Name = "First Name")] [StringLength(100, ErrorMessage = "First name may not exceed 100 characters.")] [Required(ErrorMessage = "Please enter a first name.")] public string FirstName { get; set; } [Display(Name = "Last Name")] [StringLength(100, ErrorMessage = "Last name may not exceed 100 characters.")] [Required(ErrorMessage = "Please enter a last name.")] public string LastName { get; set; } public ICollection<Title> Titles { get; set; } // Navigation property // read-only display property public string FullName => $"{FirstName} {LastName}"; } }
import { Cell, grid, Point, SnapTo } from '@davidsev/owlbear-utils'; import { PathCommand } from '@owlbear-rodeo/sdk'; import { BaseShape, cached } from './BaseShape'; import { getDiagonalDirection4 } from '../Utils/Geometry/getDirection'; export class CubeSimpleShape extends BaseShape { @cached() private get roundedStart (): Point { return grid.snapTo(this.start, SnapTo.CORNER); } @cached() public get roundedDistance (): number { const vector = this.end.sub(this.start); const dist = Math.max(Math.abs(vector.x), Math.abs(vector.y)); return Math.round(dist / grid.dpi) * grid.dpi; } @cached() private get roundedEnd (): Point { const vector = this.end.sub(this.start); const direction = getDiagonalDirection4(vector); if (!direction) return this.roundedStart; const move = new Point(this.roundedDistance * direction.x, this.roundedDistance * direction.y); return this.roundedStart.add(move); } @cached() public get labelPosition (): Point { return new Point( (this.roundedStart.x + this.roundedEnd.x) / 2, (this.roundedStart.y + this.roundedEnd.y) / 2, ); } public get outline (): PathCommand[] { return []; } @cached() public get cells (): Cell[] { const direction = getDiagonalDirection4(this.end.sub(this.start)); if (!direction) return []; const squares = Math.round(this.roundedDistance / grid.dpi); const start = this.roundedStart.add(direction); const cells: Cell[] = []; for (let x = 0; x < squares; x++) { for (let y = 0; y < squares; y++) { cells.push(grid.getCell(start.add({ x: x * grid.dpi * direction.x, y: y * grid.dpi * direction.y, }))); } } return cells; } }
import { gameMap } from "./roomlist.ts"; import { DEATH_POS, Directions } from "./constants.ts"; import { player } from "./player.ts"; import { show } from "./display.ts"; export const setRoom = (pos: [number, number], keepHistory = true) => { if (pos[0] < 0 || pos[1] < 0) { show("There is no path in that direction."); return; } const room = gameMap.at(pos[0])?.at(pos[1]); if (!room) { show("There is no path in that direction."); return; } if (keepHistory) { player.prevPos.push([...player.position]); } player.position = pos; player.currentRoom = room; room.printDescription(); }; export function getDir(input: string) { const inputToDir = [ { inputs: ["forwards", "forward", "f", "north", "n"], dir: Directions.Forward }, { inputs: ["left", "l", "west", "w"], dir: Directions.Left }, { inputs: ["backwards", "backward", "b", "south", "s"], dir: Directions.Backward }, { inputs: ["right", "r", "east", "e"], dir: Directions.Right }, ]; return inputToDir.find(({ inputs }) => inputs.includes(input))?.dir; } export function moveDir(dir: Directions) { const dirMap = new Map<Directions, [number, number]>([ [Directions.Forward, [-1, 0]], [Directions.Backward, [1, 0]], [Directions.Left, [0, -1]], [Directions.Right, [0, 1]], ]); // biome-ignore lint/style/noNonNullAssertion: All directions are initialized. const delta = dirMap.get(dir)!; const newPosition: [number, number] = [player.position[0] + delta[0], player.position[1] + delta[1]]; setRoom(newPosition); } export function die() { setRoom(DEATH_POS); } export function goBack() { const lastPos = player.prevPos.pop(); if (lastPos) { setRoom(lastPos, false); } else { show("No previous room to go back to."); } }
package database import ( "encoding/json" "errors" "log" "os" "sync" ) type DB struct { path string mux *sync.RWMutex } type DBStructure struct { Chirps map[int]Chirp `json:"chirps"` Users map[int]User `json:"users"` RefreshTokens map[string]RefreshToken `json:"refresh_tokens"` } var ErrNotExist = errors.New("resource does not exist") func NewDB(path string) (*DB, error) { db := &DB{ path: path, mux: &sync.RWMutex{}, } err := db.ensureDB() if err != nil { return db, err } log.Printf("Created new DB: %s", db.path) return db, nil } // ensureDB creates a new database file if it doesn't exist func (db *DB) ensureDB() error { _, err := os.ReadFile(db.path) if errors.Is(err, os.ErrNotExist) { log.Printf("%s does not exist, creating new...", db.path) emptyDb := DBStructure{ Chirps: map[int]Chirp{}, Users: map[int]User{}, RefreshTokens: map[string]RefreshToken{}, } contents, err := json.Marshal(emptyDb) if err != nil { return err } err = os.WriteFile(db.path, contents, 0666) if err != nil { return errors.New("Failed to create database file.") } } return nil } // loadDB reads the database file into memory func (db *DB) loadDB() (DBStructure, error) { contents, err := os.ReadFile(db.path) if err != nil { return DBStructure{}, err } dbStructure := DBStructure{} err = json.Unmarshal(contents, &dbStructure) if err != nil { return DBStructure{}, err } return dbStructure, nil } // writeDB writes the database file to disk func (db *DB) writeDB(dbStructure DBStructure) error { contents, err := json.Marshal(dbStructure) if err != nil { return err } err = os.WriteFile(db.path, contents, 0666) return err }
// Play.hpp - Header for the "play" command. // Jun 30, 2021 // Chris M. // https://github.com/RealTimeChris #pragma once #include "../HelperFunctions.hpp" namespace DiscordCoreAPI { MoveThroughMessagePagesData recurseThroughOptions(MoveThroughMessagePagesData returnData, int32_t currentPageIndex, InputEventData newEvent, std::vector<EmbedData> embedsFromSearch, BaseFunctionArguments& argsNew, std::vector<int32_t> arrayOfIndices, GuildMemberCacheData guildMember, std::vector<Song> searchResults) { if (returnData.buttonId == "exit") { DiscordGuild discordGuild{ managerAgent, argsNew.getGuildData() }; discordGuild.getDataFromDB(managerAgent); size_t songSize = discordGuild.data.playlist.songQueue.size(); UserCacheData user = Users::getCachedUser({ .userId = guildMember.user.id }); arrayOfIndices.erase(arrayOfIndices.end() - 1, arrayOfIndices.end()); for (auto& value: arrayOfIndices) { if (value != -1) { searchResults[value].addedByUserName = user.userName; searchResults[value].addedByUserId = guildMember.user.id; discordGuild.data.playlist.songQueue.emplace_back(searchResults[value]); } } UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; std::string descriptionString{}; if (arrayOfIndices.size() > 0) { discordGuild.writeDataToDB(managerAgent); descriptionString = "------\n__**Added the following songs to the queue:\n"; for (int32_t x = 0; x < arrayOfIndices.size(); x += 1) { descriptionString += "[" + searchResults[arrayOfIndices[x]].songTitle + "](" + searchResults[arrayOfIndices[x]].viewUrl + ")\n" + "Position: " + std::to_string(songSize + x + 1) + "\n"; } descriptionString += "**__\n------"; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription(descriptionString); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing New Songs:**__"); newEmbed->setColor("fefefe"); RespondToInputEventData dataPackage{ newEvent }; dataPackage.setResponseType(InputEventResponseType::Edit_Interaction_Response); dataPackage.addMessageEmbed(*newEmbed); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackage).get(); returnData.currentPageIndex -= 1; } return returnData; } else if (returnData.buttonId == "empty") { returnData.currentPageIndex -= 1; return returnData; } else { returnData = moveThroughMessagePages(argsNew.getUserData().id, InputEventData(newEvent), currentPageIndex, embedsFromSearch, false, 120000, true); arrayOfIndices.push_back(returnData.currentPageIndex); return recurseThroughOptions(returnData, returnData.currentPageIndex, returnData.inputEventData, embedsFromSearch, argsNew, arrayOfIndices, guildMember, searchResults); } } class Play : public BaseFunction { public: static std::unordered_map<int64_t, uint64_t> timeOfLastPlay; Play() { this->commandName = "play"; this->helpDescription = "Add a song to the queue and play it if nothing is playing."; EmbedData newEmbed; newEmbed.setDescription("------\nSimply enter /play SONGNAME OR Url.\n------"); newEmbed.setTitle("__**Play Usage:**__"); newEmbed.setTimeStamp(getTimeAndDate()); newEmbed.setColor("FeFeFe"); this->helpEmbed = newEmbed; } UniquePtr<BaseFunction> create() { return makeUnique<Play>(); } void execute(BaseFunctionArguments& argsNew) { try { ChannelCacheData channel{ argsNew.getChannelData() }; GuildCacheData guild{ argsNew.getGuildData() }; DiscordGuild discordGuild{ managerAgent, guild }; bool areWeAllowed{ checkIfAllowedPlayingInChannel(argsNew.getInputEventData(), discordGuild) }; if (!areWeAllowed) { return; } GuildMemberCacheData guildMember{ argsNew.getGuildMemberData() }; bool doWeHaveControl = checkIfWeHaveControl(argsNew.getInputEventData(), discordGuild, guildMember); if (!doWeHaveControl) { return; } InputEventData newEvent = argsNew.getInputEventData(); int64_t currentTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); int64_t previousPlayedTime{ 0 }; if (Play::timeOfLastPlay.contains(argsNew.getGuildData().id.operator const uint64_t&())) { previousPlayedTime = Play::timeOfLastPlay.at(argsNew.getGuildData().id.operator const uint64_t&()); } if (currentTime - previousPlayedTime < 5000) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but please wait a total of 5 seconds in between plays!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Timing Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackage(argsNew.getInputEventData()); dataPackage.setResponseType(InputEventResponseType::Ephemeral_Interaction_Response); dataPackage.addMessageEmbed(*newEmbed); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackage).get(); InputEvents::deleteInputEventResponseAsync(newEvent).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } if (argsNew.getCommandArguments().values.size() == 0 && DiscordCoreClient::getSongAPI(guild.id).areWeCurrentlyPlaying()) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but there's already something playing!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackage{ newEvent }; dataPackage.setResponseType(InputEventResponseType::Ephemeral_Interaction_Response); dataPackage.addMessageEmbed(*newEmbed); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackage).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } RespondToInputEventData dataPackage(argsNew.getInputEventData()); dataPackage.setResponseType(InputEventResponseType::Ephemeral_Deferred_Response); newEvent = InputEvents::respondToInputEventAsync(dataPackage).get(); previousPlayedTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); Play::timeOfLastPlay.insert_or_assign(argsNew.getGuildData().id.operator const uint64_t&(), previousPlayedTime); Snowflake voiceChannelId{}; if (guildMember.getVoiceStateData().channelId != 0) { voiceChannelId = guildMember.getVoiceStateData().channelId; } else { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but you need to be in a correct voice channel to issue those commands!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackageNew{ newEvent }; dataPackageNew.addMessageEmbed(*newEmbed); dataPackageNew.setResponseType(InputEventResponseType::Ephemeral_Follow_Up_Message); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackageNew).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } VoiceConnection& voiceConnection = guild.connectToVoice(guildMember.user.id); if (!voiceConnection.areWeConnected()) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but there is no voice connection that is currently held by me!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Connection Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackageNew{ newEvent }; dataPackageNew.addMessageEmbed(*newEmbed); dataPackageNew.setResponseType(InputEventResponseType::Ephemeral_Follow_Up_Message); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackageNew).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } if (guildMember.getVoiceStateData().channelId == 0 || guildMember.getVoiceStateData().channelId != voiceConnection.getChannelId()) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but you need to be in a correct voice channel to issue those commands!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackageNew{ newEvent }; dataPackageNew.addMessageEmbed(*newEmbed); dataPackageNew.setResponseType(InputEventResponseType::Ephemeral_Follow_Up_Message); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackageNew).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } std::vector<Song> searchResults{}; if (argsNew.getCommandArguments().values.size() > 0) { searchResults = DiscordCoreClient::getSongAPI(guild.id).searchForSong(argsNew.getCommandArguments().values["songname"].value); } if (searchResults.size() <= 0 && argsNew.getCommandArguments().values.size() > 0) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**No songs could be found as a result of your search!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Search Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); RespondToInputEventData dataPackageNew{ newEvent }; dataPackageNew.addMessageEmbed(*newEmbed); dataPackageNew.setResponseType(InputEventResponseType::Ephemeral_Follow_Up_Message); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackageNew).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); return; } std::vector<EmbedData> embedsFromSearch; int32_t x = 0; for (Song& value: searchResults) { x += 1; UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("__**Title:**__ [" + value.songTitle + "](" + value.viewUrl + ")" + "\n__**Description:**__ " + value.description + "\n__**Duration:**__ " + value.duration); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**" + std::to_string(x) + " of " + std::to_string(searchResults.size()) + "**__"); newEmbed->setImage(value.thumbnailUrl); newEmbed->setColor(discordGuild.data.borderColor); embedsFromSearch.push_back(*newEmbed); } int32_t currentPageIndex = 0; MoveThroughMessagePagesData returnData{}; std::vector<int32_t> arrayOfIndices{}; if (embedsFromSearch.size() > 0) { RespondToInputEventData dataPackage0(newEvent); dataPackage0.setResponseType(InputEventResponseType::Follow_Up_Message); dataPackage0.addMessageEmbed(embedsFromSearch[0]); newEvent = InputEvents::respondToInputEventAsync(dataPackage0).get(); returnData = recurseThroughOptions(returnData, currentPageIndex, newEvent, embedsFromSearch, argsNew, arrayOfIndices, guildMember, searchResults); } auto channelId = argsNew.getInputEventData().getChannelData().id; auto theTask = [=](SongCompletionEventData eventData) mutable -> CoRoutine<void, false> { auto argsNewer = std::move(argsNew); co_await NewThreadAwaitable<void, false>(); UserCacheData userNew = Users::getCachedUser({ eventData.guildMember.user.id }); std::this_thread::sleep_for(150ms); discordGuild.getDataFromDB(managerAgent); if (discordGuild.data.playlist.areThereAnySongs()) { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; if (!eventData.wasItAFail) { discordGuild.getDataFromDB(managerAgent); discordGuild.data.playlist.sendNextSong(); DiscordCoreClient::getSongAPI(guild.id).play(discordGuild.data.playlist.currentSong, guildMember); discordGuild.writeDataToDB(managerAgent); newEmbed->setAuthor(userNew.userName, userNew.getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("__**Title:**__ [" + discordGuild.data.playlist.currentSong.songTitle + "](" + discordGuild.data.playlist.currentSong.viewUrl + ")" + "\n__**Description:**__ " + discordGuild.data.playlist.currentSong.description + "\n__**Duration:**__ " + discordGuild.data.playlist.currentSong.duration + "\n__**Added By:**__ <@!" + discordGuild.data.playlist.currentSong.addedByUserId + "> (" + discordGuild.data.playlist.currentSong.addedByUserName + ")"); newEmbed->setImage(discordGuild.data.playlist.currentSong.thumbnailUrl); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Now Playing:**__"); newEmbed->setColor(discordGuild.data.borderColor); if (discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ✅ Loop-Song"); } if (!discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ✅ Loop-Song"); } if (discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ❌ Loop-Song"); } if (!discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ❌ Loop-Song"); } CreateMessageData dataPackage02(channelId); dataPackage02.addMessageEmbed(*newEmbed); Messages::createMessageAsync(dataPackage02).get(); } else { GuildMemberCacheData guildMemberNew{ eventData.guildMember }; discordGuild.getDataFromDB(managerAgent); discordGuild.data.playlist.sendNextSong(); discordGuild.writeDataToDB(managerAgent); DiscordCoreClient::getSongAPI(guild.id).play(discordGuild.data.playlist.currentSong, guildMember); newEmbed->setAuthor(userNew.userName, userNew.getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("__**It appears as though there was an error when trying to play the previous track!**__"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing Error:**__"); newEmbed->setColor("fe0000"); if (discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ✅ Loop-Song"); } if (!discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ✅ Loop-Song"); } if (discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ❌ Loop-Song"); } if (!discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ❌ Loop-Song"); } CreateMessageData dataPackage02(channelId); dataPackage02.addMessageEmbed(*newEmbed); Messages::createMessageAsync(dataPackage02).get(); } discordGuild.writeDataToDB(managerAgent); } else { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(userNew.userName, userNew.getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but there's nothing left to play here!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Now Playing:**__"); newEmbed->setColor(discordGuild.data.borderColor); if (discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ✅ Loop-Song"); } else if (!discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ✅ Loop-Song"); } else if (discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ❌ Loop-Song"); } else if (!discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ❌ Loop-Song"); } CreateMessageData dataPackage02(channelId); dataPackage02.addMessageEmbed(*newEmbed); Messages::createMessageAsync(dataPackage02).get(); DiscordCoreClient::getSongAPI(guild.id).stop(); } co_return; }; DiscordCoreClient::getSongAPI(guild.id).onSongCompletion(theTask); if (DiscordCoreClient::getSongAPI(guild.id).areWeCurrentlyPlaying()) { return; } discordGuild.getDataFromDB(managerAgent); if (discordGuild.data.playlist.areThereAnySongs()) { discordGuild.getDataFromDB(managerAgent); discordGuild.data.playlist.sendNextSong(); discordGuild.writeDataToDB(managerAgent); DiscordCoreClient::getSongAPI(guild.id).play(discordGuild.data.playlist.currentSong, guildMember); UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("__**Title:**__ [" + discordGuild.data.playlist.currentSong.songTitle + "](" + discordGuild.data.playlist.currentSong.viewUrl + ")" + "\n__**Description:**__ " + discordGuild.data.playlist.currentSong.description + "\n__**Duration:**__ " + discordGuild.data.playlist.currentSong.duration + "\n__**Added By:**__ <@!" + discordGuild.data.playlist.currentSong.addedByUserId + "> (" + discordGuild.data.playlist.currentSong.addedByUserName + ")"); newEmbed->setImage(discordGuild.data.playlist.currentSong.thumbnailUrl); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Now Playing:**__"); newEmbed->setColor(discordGuild.data.borderColor); if (discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ✅ Loop-Song"); } else if (!discordGuild.data.playlist.isLoopAllEnabled && discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ✅ Loop-Song"); } else if (discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("✅ Loop-All, ❌ Loop-Song"); } else if (!discordGuild.data.playlist.isLoopAllEnabled && !discordGuild.data.playlist.isLoopSongEnabled) { newEmbed->setFooter("❌ Loop-All, ❌ Loop-Song"); } RespondToInputEventData dataPackage02(newEvent); dataPackage02.setResponseType(InputEventResponseType::Follow_Up_Message); dataPackage02.addMessageEmbed(*newEmbed); newEvent = InputEvents::respondToInputEventAsync(dataPackage02).get(); } else { UniquePtr<EmbedData> newEmbed{ makeUnique<EmbedData>() }; newEmbed->setAuthor(argsNew.getUserData().userName, argsNew.getUserData().getUserImageUrl(UserImageTypes::Avatar)); newEmbed->setDescription("------\n__**Sorry, but there's nothing to play!**__\n------"); newEmbed->setTimeStamp(getTimeAndDate()); newEmbed->setTitle("__**Playing Issue:**__"); newEmbed->setColor(discordGuild.data.borderColor); embedsFromSearch.push_back(*newEmbed); RespondToInputEventData dataPackageNew{ newEvent }; dataPackageNew.setResponseType(InputEventResponseType::Ephemeral_Follow_Up_Message); dataPackageNew.addMessageEmbed(*newEmbed); auto newerEvent = InputEvents::respondToInputEventAsync(dataPackageNew).get(); InputEvents::deleteInputEventResponseAsync(newerEvent, 20000); } } catch (const std::runtime_error& error) { std::cout << "Play::execute()" << error.what() << std::endl; } }; ~Play(){}; }; std::unordered_map<int64_t, uint64_t> Play::timeOfLastPlay; };
#include "Game.h" #include <SPIFFS.h> #include <FS.h> // Macro for limiting max FPS at 25 (1000/40) #define FRAMETIME 40 // Macros for heandling game state #define STATE_MENU 1 #define STATE_RUNNING 2 #define STATE_GAMEOVER 3 // Macros for calling renew functions #define RENEW_CACTUS 4 #define RENEW_BIRD 5 // Static private pointer initialization Game *Game::game = NULL; // Private constructor Game::Game() { graphics = GraphicsManager::getInstance(); collision = CollisionManager::getInstance(); Serial.begin(9600); // Get maxScore saved SPIFFS.begin(); fs::File file = SPIFFS.open("/pontos.txt", "r"); if (!file) Serial.println("Couldn't open score file for reading"); else maxScore = file.readString().toInt(); file.close(); // Create entities dino = new Dino; bird = new Bird; cactus = new Cactus; state = STATE_MENU; start = end = right_prev_state = left_prev_state = score = px = 0; firstFrame = true; // Starts menu graphics->clear(); graphics->render(0, 0, ASSET_MENU); graphics->present(); } // Destructor Game::~Game() { GraphicsManager::deleteInstance(); CollisionManager::deleteInstance(); delete dino; delete bird; delete cactus; } // Singleton method Game *Game::getInstance() { if (!game) game = new Game(); return game; } // Singleton method void Game::deleteInstance() { if (game) delete game; } // Main function inside Game, checks states, calls update, render and renew void Game::run() { start = millis(); graphics->clear(); handleEvents(); if (state == STATE_RUNNING) { int dx = scrollBackground(); px += dx; px %= 320; graphics->render(-px, 110, ASSET_BACKGROUND); dino->update(); cactus->update(-dx); bird->update(-dx); dino->render(); cactus->render(); bird->render(); graphics->renderText(10, 10, String(score)); graphics->renderText(250, 10, "HI:"); graphics->renderText(290, 10, String(maxScore)); if (collision->outOfBounds(cactus)) renew(RENEW_CACTUS); if (collision->outOfBounds(bird)) renew(RENEW_BIRD); if (collision->collide(dino, cactus) || collision->collide(dino, bird)) reset(); } graphics->present(); // Sets max FPS end = millis(); if ((end - start) < FRAMETIME) delay(FRAMETIME - (end - start)); firstFrame = false; } // Handle inputs depending on state void Game::handleEvents() { if (state == STATE_RUNNING) { if (!digitalRead(LEFT_PIN)) dino->crouch(); if (!digitalRead(RIGHT_PIN) && digitalRead(RIGHT_PIN) != right_prev_state) dino->jump(); if (digitalRead(LEFT_PIN) && digitalRead(LEFT_PIN) != left_prev_state) dino->stand(); left_prev_state = digitalRead(LEFT_PIN); right_prev_state = digitalRead(RIGHT_PIN); } else { // STATE_GAMEOVER OR STATE_MENU bool onMenu = true; while (onMenu) { if (!digitalRead(RIGHT_PIN) && digitalRead(RIGHT_PIN) != right_prev_state) { state = STATE_RUNNING; onMenu = false; gameStart = millis(); } right_prev_state = digitalRead(RIGHT_PIN); } score = 0; firstFrame = true; } } // Reuse obstacles when they go out of bounds void Game::renew(int entity) { score++; unsigned long t = millis() - gameStart; // min distance between obstacles is roughly 1/3 the distance traveled by the player in one jump int minDX = (0.6 + 0.000008 * t) * (10 * FRAMETIME); // try new position int px = SCREEN_WIDTH + rand() % 100; int model; if (entity == RENEW_CACTUS) { if (px - bird->getCollider().x < minDX) px = bird->getCollider().x + minDX; // cactus models 3 and 4 are bigger, spawn only after score 35 if (score > 35) model = rand() % 4; else model = rand() % 2; cactus->renew(model, px); } else if (entity == RENEW_BIRD) { if (px - cactus->getCollider().x < minDX) px = cactus->getCollider().x + minDX; bird->renew(0, px); } } // Reset entities and change state to STATE_GAMEOVER void Game::reset() { delete dino; dino = new Dino; delete bird; bird = new Bird; delete cactus; cactus = new Cactus; state = STATE_GAMEOVER; graphics->clear(); graphics->render(0, 0, ASSET_GAMEOVER); graphics->renderText(125, 10, "score"); graphics->renderText(150, 35, String(score)); tone(BUZZER_PIN, 1000, 500); delay(500); noTone(BUZZER_PIN); checkScore(); } // Check current score and save if necessary void Game::checkScore() { fs::File file; if (score > maxScore) { maxScore = score; file = SPIFFS.open("/pontos.txt", "w"); if (!file) { Serial.println("Couldn't open score file for writing"); return; } file.println(std::to_string(score).c_str()); file.close(); } } // Return distance traveled based on time and basic physics int Game::scrollBackground() { unsigned long long t = 0; t = millis() - gameStart; double x = 0, vx = 0, dx = 0; // x = v0t + at²/2 x = 0.8 * t + 0.000004 * (t * t); // v = dx/dt = v0 + at vx = 0.8 + 0.000008 * t; dx = vx * deltaTime(); return dx; } // Return deltaTime between current and last frame unsigned long Game::deltaTime() { return (firstFrame) ? 0 : millis() - end; }
+-------------------+ | | User Request --> www.foobar.com +------> Nginx Web Server (8.8.8.8) | | +-------------------+ | | | | HTTP/HTTPS | | +------v-----v-----+ | | | Application | | Server | | | +------|-----|-----+ | | | | Connects to MySQL database server | | +------v-----v-----+ | | | MySQL | | Database Server | | | +-------------------+ Here are some specifics about this infrastructure: A server is a computer program that provides a specific kind of service to another computer program or client. In this case, we are using a physical or virtual machine as a server to host our website. The role of a domain name is to provide a human-readable name that is easy to remember and use in place of an IP address. Users can simply type www.foobar.com into their web browser, and the DNS (Domain Name System) will resolve this domain name to the IP address of our server (8.8.8.8). The www record in www.foobar.com is a subdomain that is used to distinguish a specific service or resource hosted on our domain. In this case, it is used to indicate that our website is hosted on this subdomain. The role of the web server (Nginx) is to receive incoming HTTP/HTTPS requests from clients (e.g., web browsers) and route them to the appropriate application server. It also serves static files (e.g., images, CSS, JavaScript) directly to clients to reduce the load on the application server. The role of the application server is to run our code base (e.g., PHP, Python, Ruby) and generate dynamic content based on the incoming requests. It communicates with the web server using a specific protocol (e.g., FastCGI) to receive requests and send responses. The role of the database (MySQL) is to store and manage the data used by our application. It provides a structured and efficient way to store, retrieve, and manipulate data. The application server communicates with the database using SQL (Structured Query Language) commands. The server uses the HTTP/HTTPS protocol to communicate with the computer of the user requesting the website. When a user types www.foobar.com into their web browser, the browser sends an HTTP/HTTPS request to the IP address of our server (8.8.8.8), and the server responds with the appropriate content. However, there are some issues with this infrastructure: It is a SPOF (Single Point of Failure) because all components are hosted on a single server. If this server fails, the website will be unavailable until the issue is resolved. There will be downtime when maintenance is needed (e.g., deploying new code, updating software) because the web server needs to be restarted. During this time, the website will be unavailable. It cannot scale if there is too much incoming traffic because all components are hosted on a single server. To handle more traffic, we would need to add more servers and use a load balancer to distribute the incoming requests among them.
import React from 'react' import { makeStyles } from "@mui/styles"; import { CallinModifierTooltipContent } from "./CallinModifierTooltipContent"; import { CallinModifierTooltip } from "./CallinModifierTooltip"; import { Box } from "@mui/material"; import SpeedIcon from "@mui/icons-material/Speed"; import { nanoid } from "@reduxjs/toolkit"; const useStyles = makeStyles(() => ({ placementBox: { display: 'flex', flexDirection: 'row' } })) // Check RequiredUnitIds // If not empty, then must have one of the requiredUnitIds in the unitIds const validateRequired = (requiredUnitIds, unitIds) => { if (requiredUnitIds.length > 0) { return !_.isNil(unitIds.find(unitId => requiredUnitIds.includes(unitId))) } else { return true } } // Check allowedUnitIds // If empty, skip verifying unitIds as any unit is allowed // If not empty, every element of unitIds must be in allowedUnitIds const validateAllowed = (allowedUnitIds, unitIds) => { if (allowedUnitIds.length > 0) { return unitIds.every(unitId => allowedUnitIds.includes(unitId)) } else { return true } } export const CallinModifierIcon = ({callinModifiers, unitIds}) => { const classes = useStyles() if (callinModifiers.length === 0 || unitIds.length === 0) { return null } const uniqueUnitIds = [...new Set(unitIds)] let tooltips = [] // Have callin modifiers and unit ids to check against them for (const cm of callinModifiers) { // Validate required units and allowed units conditions if (!validateRequired(cm.requiredUnitIds, uniqueUnitIds) || !validateAllowed(cm.allowedUnitIds, uniqueUnitIds)) { continue } // At this point, this callin modifier is active tooltips.push(<CallinModifierTooltipContent callinModifier={cm} key={cm.id} />) } if (tooltips.length === 0) { // No callin modifiers active return null } else { return ( <CallinModifierTooltip key={nanoid()} title={<Box className={classes.placementBox}>{tooltips}</Box>} followCursor={true} placement="bottom-start" arrow > <Box> <SpeedIcon /> </Box> </CallinModifierTooltip> ) } }
import React, { createContext, ReactNode, useState, useEffect } from "react"; import api from "../services/api"; import AsyncStorage from "@react-native-async-storage/async-storage"; interface AuthProviderProps { children: ReactNode | undefined; } interface UserProps { id: string; name: string; email: string; token: string; } export interface NotesProps { id?: string; text?: string; isCheck?: boolean; user_id?: string; } interface AuthContexDataProps { signed: boolean; user: UserProps; authLoading: boolean; loading: boolean; signIn: (email: string, password: string) => void; signUp: (name: string, email: string, password: string) => void; signOut: () => void; notes: NotesProps[]; notesCount: number; notesCheckCount: number; getNotes: () => void; deleteNote: (data: NotesProps) => void; addNote: (note: string) => void; toggleCheckNote: (id: string, check: boolean) => Promise<boolean>; editNote: (id: string, text: string) => void; } export const AuthContext = createContext({} as AuthContexDataProps); export function AuthContextProvider({ children }: AuthProviderProps) { const [user, setUser] = useState<UserProps>(null); const [authLoading, setAuthLoading] = useState(false); const [loading, setLoading] = useState(true); const [notes, setNotes] = useState<NotesProps[]>(); const [notesCount, setNotesCount] = useState(0); const [notesCheckCount, setNotesCheckCount] = useState(0); useEffect(() => { async function loadStorage() { const storageUser = await AsyncStorage.getItem("@myNotesUser"); if (storageUser) { setUser(JSON.parse(storageUser)); setLoading(false); } setLoading(false); } loadStorage(); }, []); async function getNotes() { try { const response = await api.get("/note", { headers: { Authorization: `Bearer ${user.token}` }, }); if (response.data) { let data = response.data; let notesCheckCount = data.filter((item: NotesProps) => { return item.isCheck === true; }); setNotes(data); setNotesCheckCount(notesCheckCount.length); setNotesCount(data.length - notesCheckCount.length); } } catch (err) { console.log(err); } } async function deleteNote(data: NotesProps) { try { const response = await api.delete(`/note/${data.id}`, { headers: { Authorization: `Bearer ${user.token}` }, }); if (response.data) { const newListNotes = notes.filter((item: NotesProps) => { return item.id !== data.id; }); if (data.isCheck === true) { setNotesCheckCount((value) => value - 1); } else { setNotesCount((value) => value - 1); } setNotes(newListNotes); } } catch (err) { console.log(err); } } async function addNote(note: string) { try { const response = await api.post( "/note", { text: note, }, { headers: { Authorization: `Bearer ${user.token}` } } ); if (response.data) { setNotes((oldValue) => [...oldValue, response.data]); setNotesCount((value) => value + 1); } } catch (error) { console.log(error); } } async function toggleCheckNote(id: string, check: boolean): Promise<boolean> { try { const response = await api.put( `/note/${id}`, { isCheck: !check, }, { headers: { Authorization: `Bearer ${user.token}` } } ); if (response.data) { if (response.data.isCheck === true) { setNotesCheckCount((value) => value + 1); setNotesCount((value) => value - 1); } else { setNotesCheckCount((value) => value - 1); setNotesCount((value) => value + 1); } const updatedNotes = notes.map((note) => { if (note.id === id) { return { ...note, isCheck: !check }; } return note; }); setNotes(updatedNotes); return response.data.isCheck; } } catch (err) { console.log(err); return check; } } async function editNote(id: string, text: string) { try { console.log(text); const response = await api.put( `/note/${id}`, { text: text, }, { headers: { Authorization: `Bearer ${user.token}` } } ); if (response.data) { const updatedNotes = notes.map((note) => { if (note.id === id) { return { ...note, text: text }; } return note; }); setNotes(updatedNotes); } } catch (err) { console.log(err); } } async function signIn(email: string, password: string) { setAuthLoading(true); await api .post("/session", { email, password, }) .then((response) => { const user = response.data; let data = { id: user.id, email: user.email, name: user.name, token: user.token, }; storageUser(data); setUser(data); }) .catch((err) => console.log(err)) .finally(() => setAuthLoading(false)); } async function signUp(name: string, email: string, password: string) { setAuthLoading(true); await api .post("/users", { name, email, password, }) .then((response) => { const user = response.data; let data = { id: user.id, email: user.email, name: user.name, token: user.token, }; storageUser(data); setUser(data); }) .catch((err) => console.log(err)) .finally(() => setAuthLoading(false)); } async function signOut() { await AsyncStorage.clear().then(() => setUser(null)); } async function storageUser(data: UserProps) { await AsyncStorage.setItem("@myNotesUser", JSON.stringify(data)); } return ( <AuthContext.Provider value={{ signed: !!user, user, authLoading, loading, signIn, signUp, signOut, notes, notesCount, notesCheckCount, getNotes, deleteNote, addNote, toggleCheckNote, editNote, }} > {children} </AuthContext.Provider> ); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Converter.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mvomiero <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/12 16:31:15 by mvomiero #+# #+# */ /* Updated: 2023/10/09 14:37:03 by mvomiero ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CONVERTER_HPP # define CONVERTER_HPP #include <iostream> #include <cstdlib> #include <cerrno> #include <climits> //#include <fstream> //#include <limits> enum e_type { NONE, INT, FLOAT, CHAR, DOUBLE }; class Converter { private: char _char; int _int; float _float; double _double; bool _impossible; std::string _str; // input string e_type _type; // input type - result of setType() public: Converter( void ); Converter( const Converter& src ); ~Converter( void ); Converter& operator=( const Converter& rhs ); void convert( void ); // function to convert void setStr( std::string str ); // input string void setType( void ); // to determine the type /* CHECK */ bool isChar( void ) const; bool isInt( void ) const; bool isFloat( void ) const; bool isDouble( void ) const; bool isImpossible( void ); /* PRINT */ void printChar( void ) const ; void printInt( void ) const ; void printFloat( void ) const ; void printDouble( void ) const ; /* EXCEPTIONS */ class ConverterException : public std::exception { virtual const char* what() const throw() { return "Unknown type"; } }; }; /* Operator overload */ std::ostream& operator<<( std::ostream& out, const Converter& rhs ); #endif
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:hive_flutter/adapters.dart'; import 'package:search_recipe_app_getx/presentation/screens/search_screen.dart'; import 'package:search_recipe_app_getx/utils/app_context.dart'; import 'data/models/hive_adapters.dart'; Future<void> main() async { await Hive.initFlutter(); Hive.registerAdapter(RecipeModelAdapter()); Hive.registerAdapter(ResultsAdapter()); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( navigatorKey: GlobalContext.navigatorKey, title: 'Food Recipes App', debugShowCheckedModeBanner: false, theme: ThemeData( fontFamily: "IBM Plex Sans Thai", primarySwatch: Colors.blue, ), home: SearchScreen(), ); } }
/* !!!IMPORTANT!!! THIS IS A REUSEABLE WIDGET ANY CHANGE WILL BE INCLUDED IN ALL VIEW */ import 'package:bionic/app/components/custom_text.dart'; import 'package:bionic/app/utils/utility.dart'; import 'package:flutter/material.dart'; /* Report card for showing detail income or prduk available how to use : When class called width are set infinity there you musrt call it using expanded or you can set width manually by using reportCardWidth variable for border color is set for 4 type of color you can get that by using setReportBorderColor() */ class CustomReportCard extends StatelessWidget { final String reportTitle; final int reportDetail; final double? reportCardWidth; final Color reportBorderColor; const CustomReportCard({ super.key, required this.reportTitle, required this.reportDetail, this.reportCardWidth, required this.reportBorderColor, }); @override Widget build(BuildContext context) { return Card( elevation: 8, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), border: Border( top: BorderSide( color: reportBorderColor, width: 15.0, ), ), color: Colors.white, ), width: reportCardWidth ?? double.infinity, child: Padding( padding: const EdgeInsets.symmetric( vertical: paddingMedium, horizontal: paddingMedium, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomText( text: reportTitle, textSize: textMedium, textColor: Colors.black, textWeight: FontWeight.w500, ), const SizedBox(width: spaceMedium), CustomText( text: '$reportDetail', textSize: textLarge, textColor: Colors.black, textWeight: FontWeight.w600, ), ], ), ), ), ); } }
import React, { useEffect } from "react"; const items = ["teams", "products", "workflows", "skills", "processes"]; let i = 0; function Hero() { const [name, setName] = React.useState(items[i]); useEffect(() => { const timer = setInterval(() => { console.log(`timer`); if (i < items.length - 1) { i++; setName(items[i]); } else { i = 0; setName(items[i]); } }, 2800); return () => clearInterval(timer); }, [name]); return ( <div className="hero"> <div className="hero__content"> <h1 className=""> Build better{" "} <div className="text-fader"> {items.map((item, index) => { return <h1 className={index === i ? "fadeupin" : ""}>{item}</h1>; })} </div> </h1> <p> Face the future with confidence-and with the skills and tools to thrive. </p> <div className="btn-group"> <div className="cta-btn lg decorated">view Plans</div> <div className="cta-btn lg">try for free</div> </div> <div className="organizations"> <p> HELPING THOUSANDS OF ORGANIZATIONS BUILD TECH SKILLS AT SCALE ADP </p> <div className="icons"> <div> <img src="./images/asset 14.png" alt="adp" /> </div> <div> <img src="./images/asset 15.png" alt="adobe" /> </div> <div> <img src="./images/asset 16.png" alt="vmware" /> </div> <div> <img src="./images/asset 17.png" alt="fujistu" /> </div> <div> <img src="./images/asset 18.png" alt="nasdaq" /> </div> </div> </div> </div> </div> ); } function animateUp(name) { return ( <h1 className={`fadeupin ${name}`} data-name={name}> {name} </h1> ); } export default Hero;
import { createContext, ReactNode, useState, useEffect } from 'react'; import { api } from '../services/apiClient'; import { destroyCookie, setCookie, parseCookies } from 'nookies'; import Router from 'next/router'; import { toast } from 'react-toastify'; type AuthContextData = { user: UserProps; isAuthenticated: boolean; signIn: (credentials: SignInProps) => Promise<void>; signOut: () => void; signUp: (credentials: SignUpProps) => Promise<void> } type UserProps = { id: string; name: string; email: string } type SignInProps = { email: string; password: string; } type SignUpProps = { name: string; email: string; password: string } type AuthProviderProps = { children: ReactNode; } export const AuthContext = createContext({} as AuthContextData) export function signOut() { try { destroyCookie(undefined, '@nextauth.token') Router.push('/') } catch{ console.log('erro ao deslogar') } } export function AuthProvider({ children }: AuthProviderProps) { const [user, setUser] = useState<UserProps>() const isAuthenticated = !!user; useEffect(() => { // pegar algo no token const { '@nextauth.token': token } = parseCookies(); if (token) { api.get('/me').then(response => { const {id , name, email} = response.data; setUser({ id, name, email }) }) .catch(() => { // se deu erro, deslogar user. signOut(); }) } }, []) async function signIn({email, password}: SignInProps) { try { const response = await api.post('/session', { email, password }) //console.log(response.data) const { id, name, token } = response.data; setCookie(undefined, '@nextauth.token', token, { maxAge: 60 * 60 * 24 * 30, // Expirar em 1 mês path: "/" // quais caminhos terao acesso }) setUser({ id, name, email, }) // Passar para proximas requisicoes nosso token api.defaults.headers['Authorization'] = `Bearer ${token}` toast.success('Logado com sucesso!') // Redirecionar o user para /dashboard Router.push('/dashboard') } catch (err) { toast.error("Erro ao acessar") console.log("erro ao acessar", err) } } async function signUp({name,email,password}: SignUpProps) { try { const response = await api.post('/users', { name, email, password }) toast.success("Conta criada com sucesso!") Router.push('/') } catch (err) { toast.error("Erro ao cadastrar") console.log("erro ao cadastrar", err) } } return( <AuthContext.Provider value={{user, isAuthenticated, signIn, signOut, signUp}}> {children} </AuthContext.Provider> ) }
import React, { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import './Style.css'; import axios from '../../../services/axios'; import Header from '../../../components/Header'; import { vinculosPendentesSidebar as Sidebar } from '../../../components/vinculos/sidebar'; import Vinculo from '../../../components/vinculos/vinculo_cnes'; import history from '../../../services/history'; import useRedirect from '../../../services/redirect'; import * as perms from '../../../services/permissions'; export default function VinculosPendentesCNES() { useRedirect(perms.VINCULOS_PENDENTES); const [vinculosPendentes, setVinculosPendentes] = useState([]); const accessToken = useSelector((state) => state.reducer.accessToken); axios.defaults.headers.Authorization = `Bearer ${accessToken}`; useEffect(() => { async function fetchVinculosPendentes() { try { const response = await axios.get('vinculos/api/vinculos-cnes/'); const responseData = response.data; setVinculosPendentes(responseData); } catch (error) { if (error.response.status === 401) { history.push('/login/'); history.go(); } } } // Configura o intervalo apenas uma vez fetchVinculosPendentes(); const intervalId = setInterval(fetchVinculosPendentes, 1000); // Limpa o intervalo quando o componente for desmontado return () => clearInterval(intervalId); }, []); return ( <> <Header /> <main> <Sidebar /> <div id="direita-vinculos"> {vinculosPendentes.map((vinculo) => ( <Vinculo key={vinculo.id} tipoVinculo={vinculo.tipo_vinculo} vinculoID={vinculo.id} nome={vinculo.nome} local={vinculo.local} criacao={vinculo.data_criacao} inicio={vinculo.data_entrada} tipo={vinculo.tipo} cpf={vinculo.cpf} rg={vinculo.rg} expedicaoRG={vinculo.emissao_rg} email={vinculo.email} nomeMae={vinculo.nome_mae} nomePai={vinculo.nome_pai} cns={vinculo.cns} crm={vinculo.crm} funcao={vinculo.funcao} sexo={vinculo.sexo} dataNascimento={vinculo.data_nascimento} /> ))} </div> </main> </> ); }
//Interface Examples //Program to define Person class class Person2 { private String name; private String city; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Person2(String name, String city) { super(); this.name = name; this.city = city; } public Person2() { super(); } } //Program to define Bank interface interface Bank { static final float MINBAL=5000; static final float DEPOSIT_LIMIT=25000; public void deposit(float amount); public void withdraw(float amount); } //Program to implement interface //Person class SavingAccount extends Person2 implements Bank { private int accNo; private float balance; public SavingAccount(String name, String city, int accNo, float balance) { super(name, city); this.accNo = accNo; this.balance = balance; } public int getAccNo() { return accNo; } public void setAccNo(int accNo) { this.accNo = accNo; } public float getBalance() { return balance; } public void setBalance(float balance) { this.balance = balance; } //implements Bank method @Override public void deposit(float amount) { if (amount > DEPOSIT_LIMIT) System.out.println("Daily limit exceeds..."); else { balance += amount; System.out.println("Rs. "+amount+" deposited successfully..." ); } } //implements Bank method @Override public void withdraw(float amount) { if (amount <= balance - MINBAL) { balance -= amount; System.out.println("Rs. "+amount+" withdraw successfully.."); } else System.out.println("Insufficient Balance...can't withdraw"); } @Override public String toString() { return "SavingAccount [Name =" + getName() + "\tCity = " + getCity() + "\taccNo=" + accNo + ", balance=" + balance + "]"; } } //Program to demonstrate interface public class Day8_interface { public static void main(String[] args) { SavingAccount sa=new SavingAccount("Amit", "Pune", 101, 45000); System.out.println(sa); sa.deposit(12000); System.out.println(sa); sa.withdraw(5000); System.out.println(sa); sa.withdraw(70000); System.out.println(sa); sa.deposit(120000); System.out.println(sa); } }
<!DOCTYPE html> <html> <head> <title>UI Sortable Method</title> <link rel="stylesheet" type="text/css" href="./libs/jquery-ui-1.13.1/jquery-ui.min.css"> <style type="text/css"> body{ height: 100vh; display: flex; justify-content: center; align-items: center; } .container,.containertwo{ width: 600px; background-color: #f4f4f4; padding: 20px; margin: 0 5px; box-shadow: 5px 0px 10px #888; } td,th{ border: 1px solid #000; padding: 5px; } tr{ cursor: pointer; } .spacing{ background-color: skyblue; } </style> </head> <body> <div class="container"> <h1>Closing Inventory</h1> <table id="mydata"> <thead> <th>ID</th> <th>Product Name</th> <th>Unit Price</th> <th>Qty</th> <th>Category</th> </thead> <tbody> <tr class="mov"> <td>1001</td> <td>Redbull</td> <td>700</td> <td>10</td> <td>Food</td> </tr> <tr class="mov"> <td>1002</td> <td>Sponsor</td> <td>500</td> <td>30</td> <td>Food</td> </tr> <tr class="stop"> <td>1003</td> <td>Food Masks</td> <td>50</td> <td>20</td> <td>Non Food</td> </tr> <tr class="stop"> <td>1004</td> <td>Sanitizer</td> <td>200</td> <td>50</td> <td>Non Food</td> </tr> <tr class="stop"> <td>1005</td> <td>Shower Gel</td> <td>200</td> <td>50</td> <td>Non Food</td> </tr> <tr class="stop"> <td>1006</td> <td>Shampoo</td> <td>100</td> <td>300</td> <td>Non Food</td> </tr> <tr class="mov"> <td>1007</td> <td>Drinking Water</td> <td>300</td> <td>70</td> <td>Food</td> </tr> <tr class="mov"> <td>1008</td> <td>Cheese</td> <td>120</td> <td>500</td> <td>Food</td> </tr> </tbody> </table> </div> <div class="containertwo"> <h1>Food Products Inventory</h1> <table id="mydata2"> <thead> <th>ID</th> <th>Product Name</th> <th>Unit Price</th> <th>Qty</th> <th>Category</th> </thead> <tbody> <tr class="mov"> <td>1009</td> <td>Jelly</td> <td>100</td> <td>300</td> <td>Food</td> </tr> <tr class="mov"> <td>1010</td> <td>Cake</td> <td>300</td> <td>100</td> <td>Food</td> </tr> </tbody> </table> </div> <script src="./libs/jquery-3.6.0.min.js" type="text/javascript"></script> <script src="./libs/jquery-ui-1.13.1/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ // console.log('hi'); $('#mydata tbody').sortable({ // axis:'x', // axis:'y', // containment:'.container', // don't need (.) in class name here placeholder:'spacing', connectWith:'#mydata2 tbody', cancel:'.stop', items:'.mov', // cursor:'grab', // cursor:'move', cursor:'crosshair' }); $('#mydata2 tbody').sortable({ placeholder:'spacing', connectWith:'#mydata tbody' }); }); </script> </body> </html>
class WorkoutsController < ApplicationController def create # need to add a check for sets. Is it an appropriate number? blueprint = Blueprint.find(params[:blueprint_id]) workout = Workout.create!(name: blueprint.name, user_id: session[:user_id]) Exercise.create_exercise blueprint[:id], workout[:id], params[:sets], session[:user_id] render json: workout, include: %w[exercises exercises.exercise_sets] end def index workout = Workout .where(user_id: session[:user_id]) .where.not(completed_at: nil) .order(:completed_at) render json: workout, include: %w[exercises exercises.exercise_sets] end def current workout = Workout .where(user_id: session[:user_id], completed_at: nil) .order(:created_at) .last if workout render json: workout, include: %w[exercises exercises.exercise_sets] else head :permanent_redirect end end def update workout = Workout.find(params[:id]) workout.update(workout_params) render json: workout, include: %w[exercise_sets exercise_sets.exercise] end def destroy Workout.find(params[:id]).destroy head :no_content end private def workout_params params.permit(:name, :completed_at, :user_id) end end
// <copyright file="ProductServicesImplementation.cs" company="Transilvania University of Brasov"> // Matei Adrian // </copyright> namespace ServiceLayer.Implementation { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using DataMapper.Interfaces; using DomainModel.Models; using log4net; using ServiceLayer.Interfaces; /// <summary> /// The product services. /// </summary> public class ProductServicesImplementation : IProductServices { /// <summary>The logger.</summary> private ILog logger; /// <summary>The product data services.</summary> private IProductDataServices productDataServices; /// <summary>The user score and limits data services.</summary> private IUserScoreAndLimitsDataServices userScoreAndLimitsDataServices; /// <summary>Initializes a new instance of the <see cref="ProductServicesImplementation" /> class.</summary> /// <param name="productDataServices">The product data services.</param> /// <param name="userScoreAndLimitsDataServices">The user score and limits data services.</param> /// <param name="logger">The logger.</param> public ProductServicesImplementation(IProductDataServices productDataServices, IUserScoreAndLimitsDataServices userScoreAndLimitsDataServices, ILog logger) { this.productDataServices = productDataServices; this.userScoreAndLimitsDataServices = userScoreAndLimitsDataServices; this.logger = logger; } /// <inheritdoc/> public bool AddProduct(Product product) { if (product != null) { var context = new ValidationContext(product, serviceProvider: null, items: null); var results = new List<ValidationResult>(); if (Validator.TryValidateObject(product, context, results, true)) { if (this.userScoreAndLimitsDataServices.GetUserLimitByUserId(product.Seller.Id) - this.productDataServices.GetNoOfActiveAndFutureAuctionsByUserId(product.Seller.Id) > 0) { if (this.productDataServices.GetNoOfActiveAuctionsOfUserInInterval(product.Seller.Id, product.StartDate, product.TerminationDate) < this.userScoreAndLimitsDataServices.GetConditionalValueByName("K")) { if (this.productDataServices.GetNoOfActiveAuctionsOfUserInCategory(product.Seller.Id, product.Category, product.StartDate, product.TerminationDate) < this.userScoreAndLimitsDataServices.GetConditionalValueByName("M")) { if (!this.IsTooSimilarToOtherProductDescriptions(product.Description)) { return this.productDataServices.AddProduct(product); } else { this.logger.Warn("Attempted to create a product with a description too similar to existing product descriptions."); return false; } } else { this.logger.Warn("Attempted to create too many active auctions at the same time in the same category."); return false; } } else { this.logger.Warn("Attempted to create too many active auctions at the same time."); return false; } } else { this.logger.Warn("Attempted to create too many auctions."); return false; } } else { this.logger.Warn("Attempted to add an invalid product. " + string.Join(' ', results)); return false; } } else { this.logger.Warn("Attempted to add a null product."); return false; } } /// <inheritdoc/> public IList<Product> GetAllProducts() { return this.productDataServices.GetAllProducts(); } /// <inheritdoc/> public Product GetProductById(int id) { return this.productDataServices.GetProductById(id); } /// <inheritdoc/> public bool IsTooSimilarToOtherProductDescriptions(string newProductDescription) { List<string> productDescriptions = this.productDataServices.GetAllProductDescriptions(); int l = this.userScoreAndLimitsDataServices.GetConditionalValueByName("L"); foreach (string productDescription in productDescriptions) { int n = newProductDescription.Length; int m = productDescription.Length; int[,] d = new int[n + 1, m + 1]; // if (n == 0 && m < l) // { // return true; // } // if (m == 0 && n < l) // { // return true; // } // if (n != 0 && m != 0) // { for (int i = 0; i <= n; d[i, 0] = i++) { } for (int j = 0; j <= m; d[0, j] = j++) { } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int cost = (productDescription[j - 1] == newProductDescription[i - 1]) ? 0 : 1; d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } if (d[n, m] < l) { return true; } // } } return false; } /// <inheritdoc/> public bool UpdateProduct(Product product) { if (product != null) { var context = new ValidationContext(product, serviceProvider: null, items: null); var results = new List<ValidationResult>(); if (Validator.TryValidateObject(product, context, results, true)) { if (this.productDataServices.GetProductById(product.Id) != null) { if (!this.IsTooSimilarToOtherProductDescriptions(product.Description)) { return this.productDataServices.UpdateProduct(product); } else { this.logger.Warn("Attempted to update a product with a description too similar to existing product descriptions."); return false; } } else { this.logger.Warn("Attempted to update a nonexisting product."); return false; } } else { this.logger.Warn("Attempted to update an invalid product. " + string.Join(' ', results)); return false; } } else { this.logger.Warn("Attempted to update a null product."); return false; } } /// <inheritdoc/> public bool DeleteProduct(Product product) { if (product != null) { if (this.productDataServices.GetProductById(product.Id) != null) { return this.productDataServices.DeleteProduct(product); } else { this.logger.Warn("Attempted to delete a nonexisting product."); return false; } } else { this.logger.Warn("Attempted to delete a null product."); return false; } } } }
import { Form, Input, Select, FormInstance, Modal } from 'antd'; import React from 'react'; import { Classes, Ranks } from '../../../shared/root.enums'; import { Account } from '../../../models/account.models'; import { Character } from '../../../models/character.model'; import { Spinner } from '../../../components/Spinner'; import DatePicker from '../../../components/DatePicker'; export interface AddEditCharacterModalProps { isOpen: boolean; onOk?: () => void; onCancel?: () => void; form: FormInstance; accounts: Account[]; selectedCharacter?: Character; isLoadingCharacter?: boolean; } export function AddEditCharacterModal(props: AddEditCharacterModalProps) { const { isOpen, form, accounts, onOk, onCancel, selectedCharacter, isLoadingCharacter, } = props; return ( <Modal title={ selectedCharacter ? 'Modifier un personnage' : 'Ajouter un personnage' } visible={isOpen} okText={'Valider'} cancelText={'Annuler'} onOk={onOk} onCancel={onCancel} width={'70vw'} > {isLoadingCharacter ? ( <Spinner /> ) : ( <Form labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} labelAlign={'left'} form={form} > <Form.Item label="Pseudo" name="name" rules={[{ required: true, message: 'Le pseudo est obligatoire.' }]} > <Input /> </Form.Item> <Form.Item label="Classe" name="class"> <Select showSearch placeholder="Sélectionnez la classe du personnage." options={Object.values(Classes).map((c) => ({ label: c, value: c, }))} /> </Form.Item> <Form.Item label="Rang" name="rank" rules={[{ required: true, message: 'Le rang est obligatoire.' }]} > <Select showSearch placeholder="Sélectionnez le rang du personnage." options={Object.values(Ranks).map((r) => ({ label: r, value: r, }))} /> </Form.Item> <Form.Item label="Compte" name="accountId" rules={[{ required: true, message: 'Le compte est obligatoire.' }]} > <Select showSearch optionFilterProp="label" placeholder="Sélectionnez le compte du personnage." options={accounts.map((account) => ({ label: account.name, value: account.id, }))} /> </Form.Item> <Form.Item label="Date de recrutement" name="recruitmentDate"> <DatePicker placeholder="" /> </Form.Item> </Form> )} </Modal> ); }
// // SectionDetailsPresenterTests.swift // GratitudeTests // // Created by Muhammed Rashid on 18/09/22. // @testable import Gratitude import XCTest final class SectionDetailsPresenterTests: XCTestCase { private var sut: SectionDetailsPresenter! private var view: SectionDetailsViewableMock! override func setUp() { super.setUp() view = SectionDetailsViewableMock() sut = SectionDetailsPresenter() sut.set(view: view) } override func tearDown() { defer { super.tearDown() } sut = nil view = nil } func testDisplay() { // Given let section = Section.generate() let images: [ImagePickerItem] = [ .generate(), .generate(), .generate(), .generate() ] let tableActionHandler = SectionDetailsTableActionHandlerMock() // When sut.display( section: section, images: images, tableActionHandler: tableActionHandler ) // Then XCTAssertTrue(view.renderTitleTableDataSourceCalled) let receivedArguments = view.renderTitleTableDataSourceReceivedArguments XCTAssertEqual(receivedArguments?.title, section.name) XCTAssertNotNil(receivedArguments?.tableDataSource) } }
/** * Trigger Name: BT_AT_AGD043DX_AGD_EINVOICE * Author: Kevin Evasco * Date: 08/10/2014 * Project/Requirement: SPH Integration - SF2LEG Interfaces * Description: This trigger executes the batch jobs given the Interface ID of the created Batch Run Request. * History: 09/10/2014 Kevin Evasco Created Apex Trigger * History: 09/23/2014 Renino Niefes added validation if an existing batch run request is still alive. If yes, add an error to prevent insertion. * History: 09/29/2014 Renino Niefes - added the list of interfaces that will require validation * History: 11/03/2014 Renino Niefes - added the list of interfaces that will require validation * History: 11/09/2014 Renino Niefes - added new list of interfaces that will require validation and new classes. splitted HDS039DX into two * History: 2015/03/04 Renino Niefes - D-2434 added a new layer for Delete Records in the data pool. Moved the dynamic instantiation of apex classes into that layer * 2015/03/13 Michael Francisco - added an entry for the new SMS104DX interface */ trigger BT_AT_BatchRunRequestTrigger on BT_CO_Batch_Run_Request__c (before insert) { List<BT_CO_Batch_Run_Request__c> batchRunRequestList = trigger.new; List<String> interfaceIdList = new List<String>(); for(BT_CO_Batch_Run_Request__c batchRunRequest: batchRunRequestList) { interfaceIdList.add(batchRunRequest.Interface_ID__c); } List<BT_CO_Batch_Run_Request__c> brrList = [SELECT End_Time__c,Id,Interface_ID__c FROM BT_CO_Batch_Run_Request__c WHERE Interface_ID__c IN :interfaceIdList]; /* Loop through all Batch Run Request object and put to Map those records that are still active. */ Map<String, String> brrMap = new Map<String, String>(); for (BT_CO_Batch_Run_Request__c brrRecord: brrList) { if (brrRecord.End_Time__c == null) { brrMap.put(brrRecord.Interface_ID__c,'Any value here'); } } for(BT_CO_Batch_Run_Request__c batchRunRequest: batchRunRequestList) { String interfaceId = batchRunRequest.Interface_ID__c; batchRunRequest.Start_Time__c = DateTime.now(); Set<String> interfaceSet = new Set<String>(); //Add all interfaces that will implement validation (Concurrent job validation) //Note: this will be removed later on since all batch job requests must implement concurrent job validation. interfaceSet.add('ARM063DX'); interfaceSet.add('ARM064DX'); interfaceSet.add('ARM065DX'); interfaceSet.add('ARM066DX'); interfaceSet.add('CMI087DX'); interfaceSet.add('REW031DX'); interfaceSet.add('REW040DX'); interfaceSet.add('REW041DX'); interfaceSet.add('VSS088DX'); interfaceSet.add('VSS089DX'); interfaceSet.add('VSS090DX'); interfaceSet.add('VSS093DX'); interfaceSet.add('MIRO055DX'); interfaceSet.add('DIR094DX'); interfaceSet.add('VBS103DX'); interfaceSet.add('AGD042DX'); interfaceSet.add('INET052DX'); interfaceSet.add('INET054DX'); interfaceSet.add('SAP072DX'); interfaceSet.add('HDS038DX'); interfaceSet.add('HDS036DX'); interfaceSet.add('HDS037DX'); interfaceSet.add('PPS056DX'); //START MD-54 2015/03/13 Michael Francisco - Added entry for SMS104DX interface interfaceSet.add('SMS104DX'); //END MD-54 2015/03/13 Michael Francisco //complex Tasks interfaceSet.add('HDS039DX'); interfaceSet.add('CMI101DX'); interfaceSet.add('ARM067DX'); interfaceSet.add('HDS039DX_CR'); interfaceSet.add('HDS039DX_DB'); interfaceSet.add('ARM067DX_2'); //START 25 February 2016 NCR015-5 Kevin Evasco - Packing Label CR interfaceSet.add('CMI102DX'); //END 25 February 2016 NCR015-5 Kevin Evasco - Packing Label CR //START 25 February 2016 NCR016 Kevin Evasco - Singpost Address interfaceSet.add('DIR097DX'); //END 25 February 2016 NCR016 Kevin Evasco - Singpost Address //START 11 March 2016 UD-3247 Kevin Evasco - Credit Adjustment Interface interfaceSet.add('ARM068DX'); //START 11 March 2016 UD-3247 Kevin Evasco - Credit Adjustment Interface //START 28 March 2016 UD-3207 Kevin Evasco - Added ARM105DX interfaceSet.add('ARM105DX'); interfaceSet.add('AGD106DX'); //END 28 March 2016 UD-3207 Kevin Evasco - Added ARM105DX /* Check if an existing batch run request is still active. if yes, add an error to prevent insertion. NOTE: remove this "&&batchRunRequest.Interface_ID__c=='ARM065DX'" in the condition later. this is just temporary so that other interfaces won't get affected by this change. For now, this applies to ARM065DX only... */ if (brrMap.get(batchRunRequest.Interface_ID__c)!=null && interfaceSet.contains(batchRunRequest.Interface_ID__c)) { batchRunRequest.addError('Cannot execute this batch run because it is currently active. '); } else { //[Start D-2434 Renz 2015-03-04] Added a new layer DeleteRecords class. Transferred all the execution of Apex Classes to BT_AB_DATAPOOL_DeleteRecords BT_AB_DATAPOOL_DeleteRecords delJob = new BT_AB_DATAPOOL_DeleteRecords(); delJob.setInterfaceId(interfaceId); Database.executeBatch(delJob); //[END D-2434 Renz Niefes 2015-03-04] } } }
package com.Springboot.MySql.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import lombok.RequiredArgsConstructor; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig { private final AuthenticationProvider authenticationProvider; private final JwtAuthenticationFilter jwtAuthenticationFilter; public static final String []PERMIT_URLS = { "/api/v1/auth/**","/v3/api-docs/**","/v2/api-docs/**","/swagger-resources/**","/webjars/**", "/swagger-ui/**"}; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf() .disable() .authorizeHttpRequests() .antMatchers("/api/v1/auth/**","/v3/api-docs/**","/v2/api-docs/**","/swagger-resources/**","/webjars/**", "/swagger-ui/**") .permitAll() .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authenticationProvider(authenticationProvider) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
//https://mundol-colynn.tistory.com/126 package programmers.lv2; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class 기능개발 { public static List<Integer> solution(int[] progresses, int[] speeds) { Queue<Integer> queue = new LinkedList<>(); List<Integer> answer = new ArrayList<>(); //최소 일수 계산해서 queue에 넣기 for (int i = 0; i < progresses.length; i++) { queue.add((int) Math.ceil((100.0 - progresses[i]) / speeds[i])); } while (!queue.isEmpty()) { int minDays = queue.poll(); //최소 일수 int count = 1; while (!queue.isEmpty() && queue.peek() <= minDays) { queue.poll(); count++; } answer.add(count); } return answer; } public static void main(String[] args) { System.out.println(solution(new int[]{93, 30, 55}, new int[]{1, 30, 5})); //2, 1 System.out.println(solution(new int[]{95, 90, 99, 99, 80, 99}, new int[]{1, 1, 1, 1, 1, 1})); //1, 3, 2 } }
import React from "react"; import { useEffect } from "react"; import axios from "axios"; import { useState } from "react"; const PokemonDetail = (props) => { const [count, setCount] = useState(0); const [pokemon, setPokemon] = useState([]); const [loaded, setLoaded] = useState(false); useEffect(() => { axios.get(props.url).then((res) => { setPokemon(res.data); setLoaded(true); }); }, [setPokemon, props.url]); if (!loaded) { return <div>loading</div>; } return ( <div> <div>{pokemon.name}</div> <img src={pokemon.sprites.front_default} /> <button type="button" class="btn btn-primary" onClick={() => setCount(count + 1)} > {count} </button> </div> ); }; export default PokemonDetail;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>购物车</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" type="text/css" href="css/index.css"> <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css"> </head> <body ng-app> <div class="container"> <div class="car" ng-controller="cartController"> <table class="table table-striped" ng-show="cart.length"> <thead> <tr> <th>编号</th> <th>名称</th> <th>数量</th> <th>单价</th> <th>总价</th> <th>操作</th> </tr> </thead> <tbody> <tr ng-repeat="item in cart"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td><button type="button" ng-click="reduce(item.id)" class="btn btn-info">-</button> <input type="text" value="{{item.quantity}}" ng-model="item.quantity" class="input-mini" disabled> <button type="button" ng-click="add(item.id)" class="btn btn-info">+</button> </td> <td>{{item.price}}</td> <td>{{item.quantity*item.price}}</td> <td><button type="button" class="btn btn-danger" ng-click="remove(item.id)">删除</button></td> </tr> <tr> <td>总价格:</td> <!-- 需要计算 --> <td>{{totalprice()}}</td> <td>总数量:</td> <td>{{totalquantity()}}</td> <td colspan="2"><button type="button" ng-click="cart=[]" class="btn btn-danger">清除购物车</button></td> </tr> </tbody> </table> <p ng-show="!cart.length">您的购物车已清空!</p> </div> </div> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="bootstrap/js/bootstrap.js"></script> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript" src="js/index.js"></script> </body> </html>
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:todo_app/functions/db_functions.dart'; import 'package:todo_app/presentation/screen_search&filter.dart'; import 'package:todo_app/util/app_color.dart'; import 'package:todo_app/widgets/common_widgets/common_text.dart'; import 'package:todo_app/widgets/home_widgets/screenTerms.dart'; import 'package:todo_app/widgets/home_widgets/task_bottom_section.dart'; import 'package:todo_app/widgets/home_widgets/home_eventlist.dart'; import 'package:todo_app/widgets/home_widgets/task_%20section.dart'; import 'package:todo_app/widgets/home_widgets/home_tasklist_section.dart'; import '../widgets/home_widgets/event_bottom_section.dart'; class Screen_home extends StatelessWidget { const Screen_home({super.key}); Widget tasksectiontab() { return Container( color: Colors.grey[200], child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Task_section(), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(left: 20.5), child: texts( mystring: "Today's tasks", myfontsize: 18.0, mycolor: Colors.black, fontweight: FontWeight.bold), ), Padding( padding: const EdgeInsets.only(right: 18.0, bottom: 5), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Padding( padding: const EdgeInsets.only(right: 8.0, left: 120), child: Text( DateFormat("MMM, dd yyy").format(DateTime.now()), style: const TextStyle( color: Colors.black87, fontSize: 15.0, fontWeight: FontWeight.w900), ), ), ], ), ), const SizedBox( height: 14, ) ], ), const Expanded( child: Home_tasksection(), ), Padding( padding: const EdgeInsets.only(left: 3.0), child: task_bottomsection(), ) ], ), ); } Widget iconbtnsearch(context) { // ignore: no_leading_underscores_for_local_identifiers ValueNotifier<String> _searchNotifier = ValueNotifier(''); return IconButton( icon: const Icon( Icons.search_outlined, size: 30, ), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ScreenSearch( searchNotifier: _searchNotifier, ))); }, ); } Widget eventsectiontab() { return Container( color: Colors.grey[200], child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 30), Padding( padding: const EdgeInsets.only(left: 15), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const texts( mystring: " Today events", myfontsize: 19.5, mycolor: Colors.black, fontweight: FontWeight.bold), Padding( padding: const EdgeInsets.only(right: 16.0), child: Row( children: [ const SizedBox( width: 5, ), Text( DateFormat("MMM, dd yyy").format(DateTime.now()), style: const TextStyle( color: Colors.black, fontSize: 15.5, fontWeight: FontWeight.bold), ), ], ), ), ], ), ), const SizedBox(height: 9), const Expanded( child: Home_eventsection(), ), Padding( padding: const EdgeInsets.only(left: 3.0), child: event_bottomsection(), ) ], ), ); } Widget tabevent() { return const Tab( child: Text('Event', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ); } //===Tabtask======= Widget tabtask() { return const Tab( child: Text('Task', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ); } @override Widget build(BuildContext context) { getAllTodotask(); getAllTodoEvent(); return DefaultTabController( length: 2, child: Scaffold( // key: , drawer: const ScreenTerms(), appBar: AppBar( centerTitle: true, title: const texts( mystring: "Lets do", myfontsize: 22, mycolor: Colors.white, fontweight: FontWeight.bold), bottom: TabBar( indicatorColor: Colors.white60, tabs: [tabtask(), tabevent()], ), actions: [ iconbtnsearch(context), ], backgroundColor: maincolor, ), body: TabBarView( children: [ tasksectiontab(), eventsectiontab(), ], ), ), ); } }
from django.db import models from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.core.exceptions import ObjectDoesNotExist class Subject(models.Model): title = models.CharField(max_length=200, verbose_name="Название") slug = models.SlugField(max_length=200, unique=True, verbose_name="Заголовок") class Meta: verbose_name = "Подписка" verbose_name_plural = "Подписка" ordering = ('title',) def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='courses_created', on_delete=models.CASCADE, verbose_name="Куратор") subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE, verbose_name="Подписка" ) title = models.CharField(max_length=200, verbose_name="Название") slug = models.SlugField(max_length=200, unique=True, verbose_name="Заголовок") overview = models.TextField(verbose_name="Превью") created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Курс" verbose_name_plural = "Курс" ordering = ('-created',) def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField(blank=True) def __str__(self): return self.title class Content(models.Model): module = models.ForeignKey(Module, related_name='contents', on_delete=models.CASCADE, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={'model__in': ( 'text', 'video', 'image', 'file')}) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') class BaseContent(models.Model): title = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Text(BaseContent): body = models.TextField() class ItemBase(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_related', on_delete=models.CASCADE) title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True def __str__(self): return self.title class Text(ItemBase): content = models.TextField() class File(ItemBase): file = models.FileField(upload_to='files') class Image(ItemBase): file = models.FileField(upload_to='images') class Video(ItemBase): url = models.URLField()
/* * Copyright 2018-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.hslu.msed.messagesimulator; import com.google.gson.Gson; import org.apache.kafka.clients.admin.NewTopic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.core.KafkaTemplate; @SpringBootApplication public class Application implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(Application.class); @Autowired private KafkaTemplate<Object, Object> kafkaTemplate; public static void main(String[] args) { SpringApplication.run(Application.class, args).close(); } @Bean public NewTopic topic1() { return new NewTopic("orderForExport", 1, (short) 1); } @Bean public NewTopic topic2() { return new NewTopic("orderForProcessing", 1, (short) 1); } @Override public void run(String... args) throws Exception { Thread.currentThread().join(); } @KafkaListener(id = "orders", topics = "orderCreated") public void listen(String msg) { maybeSendToExport(new Gson().fromJson(msg, Order.class)); } private void maybeSendToExport(Order order) { if (order.getCustomer().getZip() > 9000) { System.out.printf("Export order %d%n", order.getNumber()); kafkaTemplate.send("orderForExport", order); } else { System.out.printf("Process order %d%n", order.getNumber()); kafkaTemplate.send("orderForProcessing", order); } } }
<!-- album_list.html --> {% extends 'base.html' %} {% block title %}Список альбомов{% endblock %} {% block content %} <div class="container mt-5"> <h1 class="text-center mb-4">Albums</h1> <form id="filterForm" method="GET"> <div class="row mb-3"> <div class="col-md-4"> <label for="artistSelect" class="form-label">Filter by Artist:</label> <select class="form-select" id="artistSelect" name="artist"> <option value="">All</option> {% for artist in artists %} <option value="{{ artist.id }}">{{ artist.name }}</option> {% endfor %} </select> </div> <div class="col-md-4"> <label for="sortSelect" class="form-label">Sort by:</label> <select class="form-select" id="sortSelect" name="sort_by"> <option value="">None</option> <option value="title">Title</option> <option value="release_year">Release Year</option> </select> </div> <div class="col-md-4 d-flex align-items-end"> <button type="submit" class="btn btn-primary">Apply Filters</button> </div> </div> </form> <div class="row"> {% for album in albums %} <div class="col-lg-4 col-md-6 mt-4"> <div class="card album-card"> {% if album.cover_image %} <img src="{{ album.cover_image }}" class="card-img-top" alt="{{ album.title }} Cover"> {% else %} <img src="https://via.placeholder.com/200x200" class="card-img-top" alt="{{ album.title }} Cover"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ album.title }}</h5> <p class="card-text">Release Year: {{ album.release_year }}</p> <p class="card-text">Artist: {{ album.artist }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary view-album" data-toggle="modal" data-target="#albumModal" data-album="{{ album.id }}">Просмотр</button> </div> </div> </div> </div> </div> {% endfor %} </div> </div> <!-- Модальное окно для отображения информации об альбоме --> <div class="modal fade" id="albumModal" tabindex="-1" aria-labelledby="albumModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-xl"> <div class="modal-content"> <div class="modal-header bg-light"> <h5 class="modal-title" id="albumModalLabel">Album Details</h5> <button type="button" class="btn-close btn-close-white" data-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-4"> <img src="" id="albumCover" class="img-fluid" alt="Album Cover"> </div> <div class="col-md-8 text-dark"> <h2 id="albumTitle"></h2> <p id="albumReleaseYear"></p> <p id="albumArtist"></p> <p class="text-muted", id="albumBiography"></p> <!-- Добавляем треки --> <h3>Tracks</h3> <div id="albumTracks" class="row"></div> </div> </div> </div> </div> </div> </div> <!-- Подключение библиотеки Bootstrap --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.min.js"></script> <!-- Подключение jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> document.querySelectorAll('.view-album').forEach(button => { button.addEventListener('click', function() { console.log('Кнопка просмотра альбома нажата'); const albumId = this.getAttribute('data-album'); fetch(`/api/v1/albums/${albumId}/`) .then(response => { console.log('Ответ от сервера получен'); return response.json(); }) .then(album => { console.log('Данные альбома получены:', album); document.getElementById('albumTitle').textContent = album.title; document.getElementById('albumReleaseYear').textContent = `Release Year: ${album.release_year}`; document.getElementById('albumArtist').textContent = `Artist: ${album.artist}`; document.getElementById('albumBiography').textContent = album.biography ? `Biography: ${album.biography}` : ''; document.getElementById('albumCover').src = album.cover_image; // Очистить предыдущие треки const albumTracksElement = document.getElementById('albumTracks'); albumTracksElement.innerHTML = ''; // Добавить треки альбома album.tracks.forEach(track => { const trackItem = document.createElement('div'); trackItem.classList.add('col-md-6', 'mb-3'); trackItem.innerHTML = ` <div class="card track-card" style="background-color: #f8f9fa;"> <div class="card-body text-dark"> <h5 class="card-title">${track.title}</h5> <p class="card-text">Duration: ${track.duration}</p> <p class="card-text">Artist(s): ${track.artist.join(', ')}</p> </div> </div> `; albumTracksElement.appendChild(trackItem); }); $('#albumModal').modal('show'); }) .catch(error => console.error('Error:', error)); }); }); </script> {% endblock %}
<?php namespace App\Controller; use DateTime; use App\Entity\Song; use DateTimeImmutable; use App\Models\JsonError; use App\Repository\SongRepository; use App\Repository\UserRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Validator\Constraints\Image; use Symfony\Component\Validator\Validator\ValidatorInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class ApiSongController extends AbstractController { /** * @Route("/api/songs", name="api_song", methods={"GET"}) */ public function listSong(SongRepository $songRepository) : Response { return $this->json( $songRepository->findAll(), 200, [], ['groups'=> ['list_song']] ); } /** * @Route("/api/songs/[id]", name="api_song_id", methods={"GET"}) */ public function showSong(Song $song) { if ($music === null){ $error = new JsonError(Response::HTTP_NOT_FOUND, Song::class . ' non trouvé'); return $this->json($error, $error->getError()); } return $this->json( $song, Response::HTTP_OK, [], ['groups' => 'show_song'] ); } /** * Route to upload a song * @Route("/api/songs", name="api_song_create", methods={"POST"}) * @IsGranted("ROLE_ADMIN") */ public function createSong(EntityManagerInterface $entityManager, Request $request, ValidatorInterface $validator, UserRepository $userRepository) { $songEntity = new Song(); $songEntity->setTitle($request->request->get('title')); $songEntity->setDescription($request->request->get('description')); $dateObject = new DateTime(); // We change the Date to get it on this format : d/m/y $changedDate = $dateObject->createFromFormat('d/m/Y',$request->request->get('releasedate')); $songEntity->setReleaseDate($changedDate); $songEntity->setStatus(1); $songEntity->setCreatedAt(new DateTimeImmutable('now')); // To get the user uploading the song $trueUser = $userRepository->find($request->request->get('user')); $songEntity->addUser($trueUser); // files are found this way : $upload = $request->files; // As there is 2 medias (an audio file and an image file), we make a loop : foreach ($upload as $key => $uploadFile) { // We change the file name and make it finish by the extension $uploadedName = md5(uniqid()) . '.' . $uploadFile->guessExtension(); // If this is the picture file, we validate it with validator constraints if($key === 'picture'){ $errors = $validator->validate($uploadFile, new Image([])); // if errors are found, we send a Json error if (count($errors) > 0) { $myJsonError = new JsonError(Response::HTTP_UNPROCESSABLE_ENTITY, "Des erreurs de validation ont été trouvées"); $myJsonError->setValidationErrors($errors); return $this->json($myJsonError, $myJsonError->getError()); } // If this is the audio file, we validate it with validator constraints } else { // dd($validator->validate($uploadFile, new File(['mimeTypes' => 'audio/*']))); $errors = $validator->validate($uploadFile, new File(['mimeTypes' => 'audio/*'])); // if errors are found, we send a Json error if (count($errors) > 0) { $myJsonError = new JsonError(Response::HTTP_UNPROCESSABLE_ENTITY, "Des erreurs de validation ont été trouvées"); $myJsonError->setValidationErrors($errors); return $this->json($myJsonError, $myJsonError->getError()); } } // if no error is found, we move the file to the upload_directory setting on the services.yaml file $uploadFile->move( $this->getParameter('upload_directory'), $uploadedName ); // if the file is a picture, its name goes as a value for the picture property if($key === 'picture'){ $songEntity->setPicture($uploadedName); // if the file is an audio file, its name goes as a value for the file property } else { $songEntity->setFile($uploadedName); } } $entityManager->persist($songEntity); $entityManager->flush(); return $this->json( $songEntity, Response::HTTP_CREATED, [], ['groups' => ['show_song']] ); } /** * @Route("/api/songs/edit/{id}", name="api_song_edit", methods={"POST"}) * @IsGranted("ROLE_ADMIN") */ public function updateSong(EntityManagerInterface $entityManager, Song $song, Request $request,ValidatorInterface $validator) { // print_r($_FILES); // dd(ini_get('upload_max_filesize')); // dd($request); if ($request->request->get('title')!== null) { $song->setTitle($request->request->get('title')); } if ($request->request->get('description')!== null) { $song->setDescription($request->request->get('description')); } if ($request->request->get('releasedate')!== null) { $dateObject = new DateTime(); $changedDate = $dateObject->createFromFormat('d/m/Y',$request->request->get('releasedate')); $song->setReleaseDate($changedDate); } $song->setStatus(1); $song->setUpdatedAt(new DateTime('now')); // we check if there is any file given by the request if ($request->files !== null) { $upload = $request->files; // dd ($upload); foreach ($upload as $key => $uploadFile) { // We change the file name and make it finish by the extension $uploadedName = md5(uniqid()) . '.' . $uploadFile->guessExtension(); // If this is the picture file, we validate it with validator constraints if($key === 'picture') { $errors = $validator->validate($uploadFile, new Image([])); // if errors are found, we send a Json error if (count($errors) > 0) { $myJsonError = new JsonError(Response::HTTP_UNPROCESSABLE_ENTITY, "Des erreurs de validation ont été trouvées"); $myJsonError->setValidationErrors($errors); return $this->json($myJsonError, $myJsonError->getError()); } } // If this is the audio file, we validate it with validator constraints else { // dd($validator->validate($uploadFile, new File(['mimeTypes' => 'audio/*']))); $errors = $validator->validate($uploadFile, new File(['mimeTypes' => 'audio/*'])); // if errors are found, we send a Json error if (count($errors) > 0) { $myJsonError = new JsonError(Response::HTTP_UNPROCESSABLE_ENTITY, "Des erreurs de validation ont été trouvées"); $myJsonError->setValidationErrors($errors); return $this->json($myJsonError, $myJsonError->getError()); } } // if no error is found, we move the file to the upload_directory setting on the services.yaml file $uploadFile->move( $this->getParameter('upload_directory'), $uploadedName); // if the file is a picture, it goes as a value for the picture property if($key === 'picture') { $song->setPicture($uploadedName); } // if the file is an audio file, it goes as a value for the file property else { $song->setFile($uploadedName); } } } $entityManager->persist($song); $entityManager->flush(); return $this->json( $song, 201, [], ['groups' => ['show_song']] ); } /** * @Route("/api/songs/like/{id}", name="api_song_like", methods={"GET"}) */ public function likeSong(Song $song, EntityManagerInterface $entityManager) : Response { $user = $this->getUser(); if ($song->isLikedByUser($user)) { $song->removeLike($user); $entityManager->flush(); } else { $song->addLike($user); $entityManager->flush(); } return $this->json( $song, 200, [], ['groups' => ['show_song']] ); } }
/* * Copyright (C) 2005-2012 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.cmis.mapping; import java.io.Serializable; import org.alfresco.cmis.CMISAllowedActionEnum; import org.alfresco.cmis.CMISDictionaryModel; import org.alfresco.cmis.CMISInvalidArgumentException; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.AssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.apache.chemistry.abdera.ext.CMISAllowableActions; /** * This evaluator determines an action availability in accordance with collection of {@link PropertyDescriptor} and in accordance with rules of checking of the object properties. * The rules are:<br /> * - should each specific property in the list satisfy all the conditions, which are specified in appropriate {@link PropertyDescriptor} instance or at least 1 property * satisfaction is enough.<br /> * <br /> * This evaluator is generic, because it is used in the scope of {@link CompositeActionEvaluator} * * @author Dmitry Velichkevich * @see PropertyDescriptor */ public class PropertyActionEvaluator<ValidatingObjectType> extends AbstractActionEvaluator<ValidatingObjectType> { private PropertyDescriptor[] propertyIdsAndExpectedValues; private boolean allPropertiesConcur; private boolean defaultAllowing; /** * Constructor * * @param serviceRegistry - {@link ServiceRegistry} instance * @param action - {@link CMISAllowableActions} enumeration value, which determines the action to check * @param allPropertiesConcur - {@link Boolean} value, which determines: <code>true</code> - each specific object property should satisfy all the conditions of appropriate * {@link PropertyDescriptor}, <code>false</code> - at least 1 object property satisfaction is enough * @param defaultAllowing - {@link Boolean} value, which determines availability of action for several special cases (invalid object id, empty collection of the aspects etc.) * @param propertyIdsAndExpectedValues - {@link PropertyDescriptor}... collection, which specifies all the properties, which should be validated on an object */ public PropertyActionEvaluator(ServiceRegistry serviceRegistry, CMISAllowedActionEnum action, boolean allPropertiesConcur, boolean defaultAllowing, PropertyDescriptor... propertyIdsAndExpectedValues) { super(serviceRegistry, action); this.propertyIdsAndExpectedValues = propertyIdsAndExpectedValues; this.allPropertiesConcur = allPropertiesConcur; } @Override public boolean isAllowed(ValidatingObjectType object) { boolean result = defaultAllowing; if (null != propertyIdsAndExpectedValues) { for (PropertyDescriptor descriptor : propertyIdsAndExpectedValues) { if ((null != descriptor) && (null != descriptor.getPropertyId())) { Serializable left = null; try { if (object instanceof NodeRef) { left = getServiceRegistry().getCMISService().getProperty((NodeRef) object, descriptor.getPropertyId()); } else { if (object instanceof AssociationRef) { left = getServiceRegistry().getCMISService().getProperty((AssociationRef) object, descriptor.getPropertyId()); } else { return false; } } } catch (CMISInvalidArgumentException e) { throw new RuntimeException(e.toString(), e); } result = descriptor.satisfies(left); if ((allPropertiesConcur && !result) || (!allPropertiesConcur && result)) { break; } } } } return result; } /** * This class encapsulates description of object property to validate some actual object property against defined condition. This, in turn, allows determine, if some action is * allowable for an object in accordance with value or values of the property or properties.<br /> * <br /> * <b>N.B.:</b><code>null</code> expected value is supported! <br /> * The class introduces the following fields:<br /> * - property definition id (subject to reference is {@link CMISDictionaryModel}; {@link PropertyDescriptor#getPropertyId()}); - expected property value * {@link PropertyDescriptor#getPropertyValue()}; - may property be equal to <code>null</code> {@link PropertyDescriptor#isNullExpected()} * * @author Dmitry Velichkevich * @see CMISDictionaryModel */ public static class PropertyDescriptor { private String propertyId; private Serializable propertyValue; private boolean nullExpected; /** * Constructor * * @param propertyId - {@link String} value, which determines property definition id (subject to reference is {@link CMISDictionaryModel}) * @param propertyValue - {@link Serializable} instance, which specifies expected property value * @param nullExpected - {@link Boolean} value, which determines: <code>true</code> - property may be <code>null</code>, <code>false</code> - property can't be equal to * <code>null</code> (this leads to ignoring {@link PropertyDescriptor#getPropertyValue()} value) */ public PropertyDescriptor(String propertyId, Serializable propertyValue, boolean nullExpected) { this.propertyId = propertyId; this.propertyValue = propertyValue; this.nullExpected = nullExpected; } /** * Getter * * @return {@link String} value, which represents one of the {@link CMISDictionaryModel} property definition ids */ public String getPropertyId() { return propertyId; } /** * Getter * * @return {@link Serializable} instance, which specifies expected property value */ public Serializable getPropertyValue() { return propertyValue; } /** * Getter * * @return {@link Boolean} value, which determines: <code>true</code> - property may be <code>null</code>, <code>false</code> - property can't be equal to <code>null</code> * (this leads to ignoring {@link PropertyDescriptor#getPropertyValue()} value) */ public boolean isNullExpected() { return nullExpected; } /** * This method checks whether specified <code>value</code> satisfies to all the defined conditions in current instance of {@link PropertyDescriptor} * * @param value - {@link Serializable} instance, which represents actual value of some object property * @return {@link Boolean} value, which determines: <code>true</code> - specified <code>value</code> satisfies to all the defined conditions, <code>false</code> - specified * <code>value</code> doesn't satisfy to all the defined conditions */ public boolean satisfies(Serializable value) { if (!nullExpected) { return null != value; } return (null != value) ? (value.equals(propertyValue)) : (null == propertyValue); } } }
package wms_http_handlers import ( "database/sql" "encoding/json" "errors" "fmt" "log" "net/http" "strconv" "strings" grpcC "wms_microservice/wms-src/wms-communication_grpc" wmsTypes "wms_microservice/wms-src/wms-types" wmsUtils "wms_microservice/wms-src/wms-utils" ) func UpdateRulesHandler(writer http.ResponseWriter, request *http.Request) { if request.Method != http.MethodPost { wmsUtils.SetResponseMessage(writer, http.StatusMethodNotAllowed, "Method not allowed") return } if contentType := request.Header.Get("Content-Type"); !strings.Contains(contentType, "application/json") { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error: the request must be in JSON format") return } var rules wmsUtils.RulesFromPostRequest err := json.NewDecoder(request.Body).Decode(&rules) if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, fmt.Sprintf("Error in reading data: %v", err)) return } // Communication with UserManager in order to authenticate the user and retrieve user id var idUser int64 authorizationHeader := request.Header.Get("Authorization") if authorizationHeader != "" && strings.HasPrefix(authorizationHeader, "Bearer ") { idUser, err = grpcC.AuthenticateAndRetrieveUserId(authorizationHeader) if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in communication with authentication server: %v", err)) return } switch idUser { case -1: wmsUtils.SetResponseMessage(writer, http.StatusUnauthorized, "JWT Token expired: login required!") return case -2: wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, "Error in communication with DB in order to authentication: retry!") return case -3: wmsUtils.SetResponseMessage(writer, http.StatusUnauthorized, "JWT Token is not valid: login required!") return } } else { wmsUtils.SetResponseMessage(writer, http.StatusUnauthorized, "JWT Token not provided: login required!") return } triggerPeriod := rules.TriggerPeriod // inserted only because Decode function don't forbid to send body request with a json tag different from "trigger_period" // and, if user do that, the field rules.TriggerPeriod is filled with the zero value of string i.e. empty string "" if triggerPeriod == "" { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if len(rules.Location) == 0 { // if the client doesn't respect the right JSON format of the request, len(rules.Location) == 0 wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } locationName := rules.Location[0] locationLatitude := rules.Location[1] latitudeFloat, errConv := strconv.ParseFloat(locationLatitude, 64) if errConv != nil { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, fmt.Sprintf("Error during latitude conversion from string to float64: %v", errConv)) } roundedLatitude := wmsUtils.Round(latitudeFloat, 3) locationLongitude := rules.Location[2] longitudeFloat, errParse := strconv.ParseFloat(locationLongitude, 64) if errParse != nil { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, fmt.Sprintf("Error during longitude conversion from string to float64: %v", errParse)) } roundedLongitude := wmsUtils.Round(longitudeFloat, 3) countryCode := rules.Location[3] stateCode := rules.Location[4] log.SetPrefix("[INFO] ") log.Printf("LOCATION %s %s %s %s %s\n\n", locationName, locationLatitude, locationLongitude, countryCode, stateCode) var dbConn wmsTypes.DatabaseConnector _, err = dbConn.StartDBConnection(wmsUtils.DBConnString) defer func(database *wmsTypes.DatabaseConnector) { _ = database.CloseConnection() }(&dbConn) if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in connecting to database: %v", err)) return } var locationId string query := fmt.Sprintf("SELECT * FROM locations WHERE ROUND(latitude,3) = %f and ROUND(longitude,3) = %f and location_name = '%s'", roundedLatitude, roundedLongitude, locationName) _, rowsLocation, errorVar := dbConn.ExecuteQuery(query) if errorVar != nil { if errors.Is(errorVar, sql.ErrNoRows) { log.SetPrefix("[INFO] ") log.Println("There is no entry with that latitude and longitude") query = fmt.Sprintf("INSERT INTO locations (location_name, latitude, longitude, country_code, state_code) VALUES ('%s', %f, %f, '%s', '%s')", locationName, roundedLatitude, roundedLongitude, countryCode, stateCode) result, _, err := dbConn.ExecuteQuery(query) if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in database insert: %v", err)) return } locationIdInt64, _ := result.LastInsertId() locationId = strconv.FormatInt(locationIdInt64, 10) log.SetPrefix("[INFO] ") log.Println("New location correctly inserted!") } else { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in DB query select from 'location' table: %v", errorVar)) return } } else { locationId = rowsLocation[0][0] } // insert rule's values into a RulesIntoDB type variable var rulesIntoDB wmsUtils.RulesIntoDB if rules.Rules.MaxTemp != "" { rulesIntoDB.MaxTemp = rules.Rules.MaxTemp } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MinTemp != "" { rulesIntoDB.MinTemp = rules.Rules.MinTemp } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MaxHumidity != "" { rulesIntoDB.MaxHumidity = rules.Rules.MaxHumidity } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MinHumidity != "" { rulesIntoDB.MinHumidity = rules.Rules.MinHumidity } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MaxPressure != "" { rulesIntoDB.MaxPressure = rules.Rules.MaxPressure } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MinPressure != "" { rulesIntoDB.MinPressure = rules.Rules.MinPressure } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MaxWindSpeed != "" { rulesIntoDB.MaxWindSpeed = rules.Rules.MaxWindSpeed } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MinWindSpeed != "" { rulesIntoDB.MinWindSpeed = rules.Rules.MinWindSpeed } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.WindDirection != "" { rulesIntoDB.WindDirection = rules.Rules.WindDirection } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.Rain != "" { rulesIntoDB.Rain = rules.Rules.Rain } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.Snow != "" { rulesIntoDB.Snow = rules.Rules.Snow } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MaxCloud != "" { rulesIntoDB.MaxCloud = rules.Rules.MaxCloud } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } if rules.Rules.MinCloud != "" { rulesIntoDB.MinCloud = rules.Rules.MinCloud } else { wmsUtils.SetResponseMessage(writer, http.StatusBadRequest, "Error in reading data! The request must be in the correct JSON format") return } jsonRulesBytes, errMar := json.Marshal(rulesIntoDB) if errMar != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error into convert rules json into string: %v", errMar)) return } jsonRulesString := string(jsonRulesBytes) query = fmt.Sprintf("SELECT * FROM user_constraints WHERE user_id = %d and location_id = %s", idUser, locationId) _, _, er := dbConn.ExecuteQuery(query) if er != nil { if errors.Is(er, sql.ErrNoRows) { query = fmt.Sprintf("INSERT INTO user_constraints (user_id, location_id, rules, time_stamp, trigger_period) VALUES(%d, %s, '%s', CURRENT_TIMESTAMP, %s)", idUser, locationId, jsonRulesString, triggerPeriod) res, _, err := dbConn.ExecuteQuery(query) if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in database insert: %v", err)) return } // idRule is useful for the client in order to load rule in UI idRule, errorId := res.LastInsertId() if errorId != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in retrieving id of last insert item into 'user_constraints' table: %v", errorId)) return } wmsUtils.SetResponseMessage(writer, http.StatusOK, fmt.Sprintf("New user constraints correctly inserted! Id of the new constraints: %d", idRule)) return } else { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in DB query select from 'user_constraints' table: %v", er)) return } } else { // we found user constraints _, err := dbConn.BeginTransaction() if err != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in starting DB transaction: %v", err)) return } query := fmt.Sprintf("UPDATE user_constraints SET rules = '%s' WHERE user_id = %d AND location_id = %s", jsonRulesString, idUser, locationId) _, _, errQuery := dbConn.ExecIntoTransaction(query) if errQuery != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in executing query into DB transaction: %v", errQuery)) return } query = fmt.Sprintf("UPDATE user_constraints SET trigger_period = %s WHERE user_id = %d and location_id = %s", triggerPeriod, idUser, locationId) _, _, errQuery = dbConn.ExecIntoTransaction(query) if errQuery != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in executing query into DB transaction: %v", errQuery)) return } errorCommit := dbConn.CommitTransaction() if errorCommit != nil { wmsUtils.SetResponseMessage(writer, http.StatusInternalServerError, fmt.Sprintf("Error in commit DB transaction: %v", errorCommit)) return } wmsUtils.SetResponseMessage(writer, http.StatusOK, "Updated table user_constraints correctly!") return } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AddJobComponent } from './components/add-job/add-job.component'; import { DetailJobComponent } from './components/detail-job/detail-job.component'; import { HomeComponent } from './components/home/home.component'; import { LoginComponent } from './components/login/login.component'; import { SignupComponent } from './components/signup/signup.component'; import { ViewJobsComponent } from './components/view-jobs/view-jobs.component'; import { AuthGuard } from './guards/auth.guard'; const routes: Routes = [ {path:'', component: HomeComponent, pathMatch:'full'}, {path:'login', component: LoginComponent }, {path:'signup', component: SignupComponent}, {path: 'postjob', component: AddJobComponent, canActivate: [AuthGuard]}, {path: 'getjob', component: ViewJobsComponent, canActivate: [AuthGuard]}, {path: 'viewJob/:id', component: DetailJobComponent, canActivate: [AuthGuard]} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
## Terminology - **differential equation:** an equation involving unknown functions and their derivatives. - The **order** of the differential equation is the order of the highest derivative. - The simplest differential equations are the first-order equations of the form $$y' = ay$$ where $y = f(x)$ is an unkown function differentiable function to be determined. $y' = \frac{dy}{dx}$ is it's derivative and $a$ is constant. As with most differential equations, this equation has infinitely many solutions; they are the functions of the form: $$y = ce^{ax}$$ This is known as the **general solution** To find $C$ we have to know the **initial condition** this is in the form where $y(0) = 6$ or some other values besides 6. ## First-Order Linear Systems In this section we will be concerned with solving systems of differential equations of the form: $$\begin{align*} y'_1 &= a_{11}y_1 + a_{12}y_2 + \ldots + a_{1n}y_n \\ y'_2 &= a_{21}y_1 + a_{22}y_2 + \ldots + a_{2n}y_n \\ &\vdots \\ y'_n &= a_{n1}y_1 + a_{n2}y_2 + \ldots + a_{nn}y_n \end{align*} $$ where $y_1 = f_1(x)$, $y_2 = f_2(x)$,$y_3 = f_3(x)$ are functions to be determined, and the $a_{ij}$'s are constants In matrix notation it can be written as: $$\begin{bmatrix} y'_1 \\ y'_2 \\ \vdots \\ y'_n \end{bmatrix} = \begin{bmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ an1 & an2 & \ldots & ann \end{bmatrix} \begin{bmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{bmatrix} $$ or more breifly as: $$y' = \mathbf{A}y$$ ![[Pasted image 20230927154207.png]] ![[Pasted image 20230927154255.png]] ## Solution by Diagonalization ![[Pasted image 20231031141529.png]] ![[Pasted image 20231031142601.png]] ![[Pasted image 20231031142624.png]] ![[Pasted image 20231031142658.png]] ![[Pasted image 20231031142718.png]]
require 'test_helper' class DraftsControllerTest < ActionController::TestCase setup do @draft = drafts(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:drafts) end test "should get new" do get :new assert_response :success end test "should create draft" do assert_difference('Draft.count') do post :create, draft: { from_email: @draft.from_email, from_name: @draft.from_name, html_body: @draft.html_body, subject: @draft.subject, text_body: @draft.text_body, to_email: @draft.to_email } end assert_redirected_to draft_path(assigns(:draft)) end test "should show draft" do get :show, id: @draft assert_response :success end test "should get edit" do get :edit, id: @draft assert_response :success end test "should update draft" do put :update, id: @draft, draft: { from_email: @draft.from_email, from_name: @draft.from_name, html_body: @draft.html_body, subject: @draft.subject, text_body: @draft.text_body, to_email: @draft.to_email } assert_redirected_to draft_path(assigns(:draft)) end test "should destroy draft" do assert_difference('Draft.count', -1) do delete :destroy, id: @draft end assert_redirected_to drafts_path end end
import pandas as pd import pandas_datareader.data as web import matplotlib.pyplot as plt import datetime def simulate_trades(df): cash = 10000 # capital inicial shares = 0 # quantidade de ações possuídas portfolio = cash # valor total do portfólio buy_prices = [] sell_prices = [] trade_log = [] for date, row in df.iterrows(): if row['Position'] == 1: # sinal de compra if cash > 0: # só compra se tiver cash disponível shares = cash / row['Close'] cash = 0 buy_prices.append(row['Close']) trade_log.append((date, 'BUY', shares, row['Close'])) elif row['Position'] == -1: # sinal de venda if shares > 0: # só vende se tiver ações cash = shares * row['Close'] shares = 0 sell_prices.append(row['Close']) trade_log.append((date, 'SELL', shares, row['Close'])) portfolio = cash return trade_log, portfolio, buy_prices, sell_prices # Definir as datas de início e fim da análise start = datetime.datetime(2024, 3, 1) end = datetime.datetime.now() # Carregar dados de um ativo específico df = web.DataReader('AAPL', 'yahoo', start, end) # Calcular médias móveis simples de 20 e 50 dias df['SMA_20'] = df['Close'].rolling(window=20).mean() df['SMA_50'] = df['Close'].rolling(window=50).mean() # Identificar os cruzamentos de alta e de baixa df['Signal'] = 0 df['Signal'][df['SMA_20'] > df['SMA_50']] = 1 df['Signal'][df['SMA_20'] < df['SMA_50']] = -1 df['Position'] = df['Signal'].diff() # Simular trades e obter o log de trades e o resultado do portfólio trade_log, final_portfolio, buy_prices, sell_prices = simulate_trades(df) # Plotar os preços de fechamento, médias móveis e sinais de compra/venda plt.figure(figsize=(12, 6)) plt.plot(df['Close'], label='Preço de Fechamento', color='blue') plt.plot(df['SMA_20'], label='Média Móvel 20 dias', color='red') plt.plot(df['SMA_50'], label='Média Móvel 50 dias', color='green') plt.plot(df.index, buy_prices, '^', markersize=10, color='g', lw=0, label='Compra') plt.plot(df.index, sell_prices, 'v', markersize=10, color='r', lw=0, label='Venda') plt.title('Análise Técnica com Trades Simulados') plt.xlabel('Data') plt.ylabel('Preço de Fechamento') plt.legend() plt.show() # Imprimir resultados dos trades e o valor final do portfólio print("Log de Trades:", trade_log) print("Valor final do portfólio:", final_portfolio)
/* * Copyright (C) 2009-2023 Alex Smith * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * @file * @brief ARM64 ELF helper functions. * * Reference: * - ELF for the Arm 64-bit Architecture (AArch64) * https://github.com/ARM-software/abi-aa/blob/main/aaelf64/aaelf64.rst */ #include <assert.h> #include <elf.h> #include <kernel.h> #include <module.h> #include <status.h> enum { INSN_TYPE_B, INSN_TYPE_ADD, INSN_TYPE_ADR, INSN_TYPE_LDST12, }; static status_t reloc_instruction( uint32_t *P32, int64_t val, uint32_t val_shift, uint32_t val_bits, uint32_t insn_type, bool check_overflow) { if (check_overflow && (val & ((1 << val_shift) - 1))) return STATUS_OVERFLOW; val >>= val_shift; if (check_overflow && (val >= (int64_t)(1ul << (val_bits - 1)) || val < -((int64_t)(1ul << (val_bits - 1))))) { // TODO: Can support this via PLT? return STATUS_OVERFLOW; } val &= (1 << val_bits) - 1; uint32_t insn = *P32; switch (insn_type) { case INSN_TYPE_B: insn &= ~0x3ffffffu; insn |= val; break; case INSN_TYPE_ADD: case INSN_TYPE_LDST12: insn &= ~0x3ffc00u; insn |= val << 10; break; case INSN_TYPE_ADR: insn &= ~0x60ffffe0u; insn |= ((val & 0x3) << 29) | ((val >> 2) << 5); break; default: assert(false); } *P32 = insn; return STATUS_SUCCESS; } static inline uint64_t Page(uint64_t val) { return val & ~(uint64_t)0xfff; } /** Perform a RELA relocation on an ELF module. */ status_t arch_elf_module_relocate_rela(elf_image_t *image, elf_rela_t *rel, elf_shdr_t *target) { status_t ret; /* * Variable names match the relocation operation values in the Arm * documentation. */ uint64_t A = rel->r_addend; uint64_t P = target->sh_addr + rel->r_offset; uint64_t *P64 = (uint64_t *)P; uint32_t *P32 = (uint32_t *)P; /* Obtain the symbol value. */ uint64_t S; ret = elf_module_resolve(image, ELF64_R_SYM(rel->r_info), &S); if (ret != STATUS_SUCCESS) return ret; uint64_t O; /* Perform the relocation. */ ret = STATUS_SUCCESS; switch (ELF64_R_TYPE(rel->r_info)) { case ELF_R_AARCH64_NONE: break; case ELF_R_AARCH64_ABS64: O = S + A; *P64 = O; break; case ELF_R_AARCH64_ADD_ABS_LO12_NC: /* IMM field in ADD instruction. */ O = S + A; ret = reloc_instruction(P32, O, 0, 12, INSN_TYPE_ADD, false); break; case ELF_R_AARCH64_ADR_PREL_PG_HI21: O = Page(S + A) - Page(P); ret = reloc_instruction(P32, O, 12, 21, INSN_TYPE_ADR, true); break; case ELF_R_AARCH64_CALL26: case ELF_R_AARCH64_JUMP26: /* IMM field in B/BL instructions. */ O = S + A - P; ret = reloc_instruction(P32, O, 2, 26, INSN_TYPE_B, true); break; case ELF_R_AARCH64_LDST16_ABS_LO12_NC: O = S + A; ret = reloc_instruction(P32, O, 1, 11, INSN_TYPE_LDST12, false); break; case ELF_R_AARCH64_LDST32_ABS_LO12_NC: O = S + A; ret = reloc_instruction(P32, O, 2, 10, INSN_TYPE_LDST12, false); break; case ELF_R_AARCH64_LDST64_ABS_LO12_NC: O = S + A; ret = reloc_instruction(P32, O, 3, 9, INSN_TYPE_LDST12, false); break; default: kprintf(LOG_WARN, "elf: encountered unknown relocation type: %lu\n", ELF64_R_TYPE(rel->r_info)); return STATUS_MALFORMED_IMAGE; } return ret; } /** Perform a REL relocation on an ELF module. */ status_t arch_elf_module_relocate_rel(elf_image_t *image, elf_rel_t *rel, elf_shdr_t *target) { kprintf(LOG_WARN, "elf: REL relocation section unsupported\n"); return STATUS_NOT_IMPLEMENTED; }
package com.SimulationParam; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import com.SmartHomeSimulator.iHome.SimulationParams.Simulation; import com.SmartHomeSimulator.iHome.SimulationParams.SimulationRepository; import com.SmartHomeSimulator.iHome.SimulationParams.SimulationService; import com.SmartHomeSimulator.iHome.Thermostat.ThermostatService; import com.SmartHomeSimulator.iHome.User.User; import java.sql.Date; import java.time.LocalTime; import java.util.List; import java.util.Map; import org.bson.types.ObjectId; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockMultipartFile; @ExtendWith(MockitoExtension.class) public class SimulationServiceTest { @Mock private SimulationRepository simulationRepository; @Mock private ThermostatService thermostatService; @InjectMocks private SimulationService simulationService; @Captor private ArgumentCaptor<Map<String, Integer>> temperatureMapCaptor; @Test public void registerSimulation_ShouldSaveSimulation() { ObjectId houseId = new ObjectId(); Simulation expectedSimulation = new Simulation(List.of(new User()), new Date(System.currentTimeMillis()), LocalTime.now(), houseId); when(simulationRepository.save(any(Simulation.class))).thenReturn(expectedSimulation); Simulation result = simulationService.registerSimulation(List.of(new User()), new Date(System.currentTimeMillis()), LocalTime.now(), houseId); assertNotNull(result); assertEquals(houseId, result.getHouseId()); } @Test public void getSimulationTimeByHouseId_ShouldReturnCurrentTime() { LocalTime result = simulationService.getSimulationTimeByHouseId(new ObjectId()); assertNotNull(result); } }
import React, { FC, useMemo } from "react"; import { Box, Flex, HStack, IconButton, Button, useDisclosure, useColorModeValue, Stack, useColorMode, Drawer, DrawerBody, DrawerContent, DrawerHeader, DrawerOverlay, DrawerCloseButton, } from "@chakra-ui/react"; import { HamburgerIcon, CloseIcon, MoonIcon, SunIcon } from "@chakra-ui/icons"; import { NavLink } from "./NavLink"; import { useToploProvider } from "../../hooks"; import { ColorTheme, themes } from "../../providers/toplo/themes"; import { BsPaletteFill } from "react-icons/bs"; export const NavBar: FC = () => { const { isOpen: isPalOpen, onOpen: palOnOpen, onClose: palOnClose } = useDisclosure(); // const [paletteVisible, setPaletteVisible] = useState(false); const { theme, setTheme, routes } = useToploProvider(); const { toggleColorMode } = useColorMode(); const { isOpen, onOpen, onClose } = useDisclosure(); const Links = useMemo(() => Object.entries(routes), undefined); const LinksRendered = useMemo(() => Links.map(([link, info]) => ( <NavLink key={info.name} to={link} icon={info.icon}>{info.name}</NavLink> )), Links); return ( <Box bg={useColorModeValue("primary.200", "primary.900")} px={4}> <Flex h={16} alignItems={"center"} justifyContent={"space-between"}> <IconButton size={"md"} icon={isOpen ? <CloseIcon /> : <HamburgerIcon />} aria-label={"Open Menu"} display={{ md: "none" }} onClick={isOpen ? onClose : onOpen} /> <HStack spacing={8} alignItems={"center"}> <HStack as={"nav"} spacing={4} display={{ base: "none", md: "flex" }}> {LinksRendered} </HStack> </HStack> <Flex alignItems={"center"}> <Button onClick={isPalOpen ? palOnClose : palOnOpen} margin={5}> <BsPaletteFill /> </Button> <Button onClick={toggleColorMode} margin={5}> {useColorModeValue(<MoonIcon />, <SunIcon />)} </Button> </Flex> </Flex> {isOpen ? ( <Box pb={4} display={{ md: "none" }}> <Stack as={"nav"} spacing={4}> {LinksRendered} </Stack> </Box> ) : null} <Drawer placement={"top"} onClose={palOnClose} isOpen={isPalOpen}> <DrawerOverlay /> <DrawerContent> <DrawerHeader borderBottomWidth='1px' backgroundColor={useColorModeValue(`${theme}.300`, `${theme}.500`)}>Pick your theme</DrawerHeader> <DrawerCloseButton /> <DrawerBody> <Box> {Object.keys(themes).map((tt, indx) => <Button p={1} m={1} variant='outline' key={`${tt}-${indx}`} colorScheme={tt} bgColor={theme === tt ? useColorModeValue(`${tt}.300`, `${tt}.500`) : "transparent"} onClick={() => { setTheme(tt as ColorTheme); palOnClose(); }} > {tt} </Button>)} </Box > </DrawerBody> </DrawerContent> </Drawer> </Box> ); };
import 'dart:convert'; import 'package:cnattendance/data/source/datastore/preferences.dart'; import 'package:cnattendance/data/source/network/model/hollidays/HolidayResponse.dart'; import 'package:cnattendance/data/source/network/model/hollidays/Holidays.dart'; import 'package:cnattendance/model/holiday.dart'; import 'package:cnattendance/utils/constant.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; class HolidayProvider with ChangeNotifier { final List<Holiday> _holidayList = []; final List<Holiday> _holidayListFilter = []; List<Holiday> get holidayList { return _holidayListFilter; } int toggleValue = 0; void holidayListFilter() { _holidayListFilter.clear(); if (toggleValue == 0) { _holidayListFilter.addAll(_holidayList .where((element) => element.dateTime.isAfter(DateTime.now())) .toList()); } else { _holidayListFilter.addAll(_holidayList .where((element) => element.dateTime.isBefore(DateTime.now())) .toList().reversed); } notifyListeners(); } Future<HolidayResponse> getHolidays() async { var uri = Uri.parse(Constant.HOLIDAYS_API); Preferences preferences = Preferences(); String token = await preferences.getToken(); Map<String, String> headers = { 'Content-Type': 'application/json', 'Accept': 'application/json; charset=UTF-8', 'Authorization': 'Bearer $token' }; try { final response = await http.get(uri, headers: headers); final responseData = json.decode(response.body); if (response.statusCode == 200) { debugPrint(responseData.toString()); final responseJson = HolidayResponse.fromJson(responseData); makeHolidayList(responseJson.data); holidayListFilter(); return responseJson; } else { var errorMessage = responseData['message']; throw errorMessage; } } catch (error) { rethrow; } } void makeHolidayList(List<Holidays>? data) { _holidayList.clear(); for (var item in data ?? []) { DateTime tempDate = DateFormat("yyyy-MM-dd").parse(item.eventDate); print(DateFormat('MMMM').format(tempDate)); _holidayList.add(Holiday( id: item.id, day: tempDate.day.toString(), month: DateFormat('MMM').format(tempDate), title: item.event, description: item.description, dateTime: tempDate)); } notifyListeners(); } }
<template> <div class="center"> <form class="p-5 center" @submit.prevent="handleSignUp"> <h1 class="mb-4">Login</h1> <input type="email" placeholder="Email" class="mb-2 pl-2" ref="emailInput" required /> <input type="password" placeholder="Password" class="mb-2 pl-2" ref="passwordInput" required /> <button class="pr-4 pl-4 pt-1 pb-1 mb-2" @click="handleLogin"> Login </button> <p>{{ store.email }}</p> <p>{{ store.password }}</p> </form> </div> </template> <script setup> import { ref } from "vue"; import { useRouter } from "vue-router"; import { useDetailStore } from "@/stores/userStore"; const store = useDetailStore(); const emailInput = ref(null); const passwordInput = ref(null); const handleLogin = () => { const trimmedEmail = emailInput.value.value.trim(); const trimmedPassword = passwordInput.value.value.trim(); //Email Validation if (trimmedEmail === store.email) { alert("Email Matches"); // More informative message console.log("store.email:", store.email); console.log("trimmedEmail:", trimmedEmail); } else { // Implement login logic here (e.g., API call, authentication) alert("Email doesn't match"); console.log("store.email:", store.email); console.log("trimmedEmail:", trimmedEmail); } //Password Validation if (trimmedPassword === store.password) { alert("Password Matches"); // More informative message console.log("store.password:", store.password); console.log("trimmedPassword:", trimmedPassword); } else { // Implement login logic here (e.g., API call, authentication) alert("Password doesn't match"); console.log("store.password:", store.password); console.log("trimmedPassword:", trimmedPassword); } router.push("/home"); }; </script> <style scoped> * { overflow: none !important; } div { height: 100vh; } form { border: 1px dotted #333; display: flex; flex-direction: column; } input { border-radius: 3px; border: 1px solid #333; width: 25em; height: 3em; } button { background-color: #101010; color: #ffffff; border: none; border-radius: 5px; cursor: pointer; transition: all 0.3s ease; } button:hover { transform: scale(1.05); } @media (max-width: 1000px) { form { width: 100vw; border: none; } } </style>
<mat-toolbar> <span>{{ "Modify User: " + ps.form.controls['ParticipantID'].value }}</span> <span class="fill-remaining-space"></span> <button class="btn-dialog-close" mat-strocked-button (click)="onClose()" tabIndex="-1"> <mat-icon>clear</mat-icon> </button> </mat-toolbar> <form [formGroup]="ps.form" class="normal-form" (ngSubmit)="onSubmit()"> <div fxLayout="row" fxLayout.xs="column" fxLayout.sm="column" fxFlex> <div fxFlex="60%" class="controlls-container"> <input type="hidden" formControlName="ParticipantID"> <mat-form-field> <input type="text" formControlName="FullName" matInput placeholder="FullName"> <mat-error>{{ mandatoryMsg }}</mat-error> </mat-form-field> <mat-form-field> <input type="email" formControlName="Email" matInput placeholder="Email"> <mat-error>{{ mandatoryMsg }}</mat-error> </mat-form-field> <div> <label id="userRole-radio-group-label">User Role </label> <mat-radio-group class="example-radio-group" formControlName="UserRole" aria-labelledby="userRole-radio-group-label"> <mat-radio-button class="example-radio-button" *ngFor="let role of roles" [value]="role">{{ role }}</mat-radio-button> </mat-radio-group> <mat-form-field> <mat-label>Last Reset Date</mat-label> <input readonly value = "{{ ps.form.value.LastResetDate | date }}" matInput> </mat-form-field> </div> </div> <div fxFlex="40%" class="controlls-container"> <mat-form-field> <input readonly value="{{ ps.form.value.Q1Grade | percent }}" matInput placeholder="Q1 Grade"> </mat-form-field> <mat-form-field> <input readonly value="{{ ps.form.value.Q2Grade | percent }}" matInput placeholder="Q2 Grade"> </mat-form-field> <mat-form-field> <input readonly value="{{ ps.form.value.Q3Grade | percent }}" matInput placeholder="Q3 Grade"> </mat-form-field> <mat-form-field> <input readonly value="{{ ps.form.value.Q4Grade | percent }}" matInput placeholder="Q4 Grade"> </mat-form-field> <div class="button-row"> <button mat-raised-button color="primary" [disabled]="ps.form.invalid" type="submit">Submit</button> </div> </div> </div> </form>
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; //COMPONENTES import { TasksComponent } from './components/tasks/tasks.component'; import { PrivateTasksComponent } from './components/private-tasks/private-tasks.component'; import { SigninComponent } from './components/signin/signin.component'; import { SignupComponent } from './components/signup/signup.component'; import { AuthGuard } from './auth.guard'; // import { LoaderComponent } from './components/loader/loader.component'; const routes: Routes = [ { path: '', redirectTo: '/tasks', pathMatch: 'full', }, { path: 'tasks', component: TasksComponent, }, { path: 'private-tasks', canActivate: [AuthGuard], component: PrivateTasksComponent, }, { path: 'signin', component: SigninComponent, }, { path: 'signup', component: SignupComponent, }, // { // path: 'loader', // component: LoaderComponent // }, { path: '**', redirectTo: '/tasks', }, ]; @NgModule({ imports: [RouterModule.forRoot(routes, {useHash:false})], exports: [RouterModule], }) export class AppRoutingModule {}
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import PlayerPreview from './PlayerPreview'; class Battle extends Component { constructor( props ) { super( props ); this.state = { playerOneName: '', playerTwoName: '', playerOneImage: null, playerTwoImage: null, } } handleSubmit = ( id, username ) => { this.setState( _ => ({ [ id + 'Name' ]: username, [ id + 'Image' ]: `https://github.com/${ username }.png?size=200`, })); } handleReset = ( id ) => { this.setState( _ => ({ [ id + 'Name' ]: '', [ id + 'Image' ]: null, })); } render() { const { match } = this.props; const { playerOneName, playerTwoName, playerOneImage, playerTwoImage } = this.state; return ( <div> <div className="row"> { playerOneName ? <PlayerPreview id="playerOne" avatar={ playerOneImage } username= { playerOneName } onReset={ this.handleReset } > <button className="reset" onClick={ this.handleReset.bind( null, 'playerOne' ) }> Reset </button> </PlayerPreview> : <PlayerInput id="playerOne" label="Player One" onSubmit={ this.handleSubmit } /> } { playerTwoName ? <PlayerPreview id="playerTwo" avatar={ playerTwoImage } username= { playerTwoName } > <button className="reset" onClick={ this.handleReset.bind( null, 'playerTwo' ) }> Reset </button> </PlayerPreview> : <PlayerInput id="playerTwo" label="Player Two" onSubmit={ this.handleSubmit } /> } </div> { playerOneImage && playerTwoImage && <Link className="button" to={{ pathname: match.url + '/results', search: `?playerOneName=${ playerOneName }&playerTwoName=${ playerTwoName }` }}> Battle </Link> } </div> ); } } class PlayerInput extends Component { constructor( props ) { super( props ); this.state = { username: '', } } handleChange = e => { const value = e.target.value; this.setState( _ => ({ username: value, })); } handleSubmit = e => { e.preventDefault(); this.props.onSubmit( this.props.id, this.state.username ); } render() { return ( <form className="column" onSubmit={ this.handleSubmit }> <label className="header" htmlFor="username"> { this.props.label } </label> <input id="username" placeholder="github username" type="text" autoComplete="off" value={ this.state.username } onChange={ this.handleChange } /> <button className="button" type="submit" disabled={ !this.state.username } > Submit </button> </form> ); } } PlayerInput.propTypes = { id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, onSubmit: PropTypes.func.isRequired, } export default Battle;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TaskBot for Anthony Titus Fall Studio Author: Ivan Leon studiobot.glitch.me ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ module.exports = function(controller) { // listen for someone saying 'tasks' to the bot // reply with a list of current tasks loaded from the storage system // based on this user's id controller.hears(['tasks','todo', 'task list', 'list'], 'direct_message,direct_mention,mention', function(bot, message) { // load user from storage... controller.storage.users.get(message.user, function(err, user) { // user object can contain arbitary keys. we will store tasks in .tasks if (!user || !user.tasks || user.tasks.length == 0) { bot.reply(message, 'There are no tasks on your list. Say `add _task_` to add something.'); } else { var text = 'Here are your current tasks: \n' + generateTaskList(user) + 'Reply with `done _number_` to mark a task completed.'; bot.reply(message, text); } }); }); // listen for a user saying "add <something>", and then add it to the user's list // store the new list in the storage system controller.hears(['add (.*)'],'direct_message,direct_mention,mention', function(bot, message) { var newtask = message.match[1]; controller.storage.users.get(message.user, function(err, user) { if (!user) { user = {}; user.id = message.user; user.tasks = []; } user.tasks.push(newtask); controller.storage.users.save(user, function(err,saved) { if (err) { bot.reply(message, 'I experienced an error adding your task: ' + err); } else { bot.api.reactions.add({ name: 'thumbsup', channel: message.channel, timestamp: message.ts }); bot.reply(message, "I have added '" + message.match[1] + "' to your tasks list.") } }); }); }); // listen for a user saying "done <number>" and mark that item as done. controller.hears(['done (.*)'],'direct_message,direct_mention,mention', function(bot, message) { var number = message.match[1]; if (isNaN(number)) { bot.reply(message, 'Please specify a number.'); } else { // adjust for 0-based array index number = parseInt(number) - 1; var newTask = [] controller.storage.users.get(message.user, function(err, user) { if (!user) { user = {}; user.id = message.user; user.tasks = []; } if (number < 0 || number >= user.tasks.length) { bot.reply(message, 'Sorry, your input is out of range. Right now there are ' + user.tasks.length + ' items on your list.'); } else { var item = user.tasks.splice(number,1); newTask = user.tasks; // reply with a strikethrough message...1 bot.reply(message, '~' + item + '~'); if (user.tasks.length > 0) { bot.reply(message, 'Here are our remaining tasks:\n' + generateTaskList(user)); } else { bot.reply(message, 'Your list is now empty!'); } controller.storage.users.save(user, function(err,saved){ if (err) { bot.reply(message, 'I experienced an error adding your task: ' + err); } else { bot.api.reactions.add({ name: 'thumbsup', channel: message.channel, timestamp: message.ts }); bot.reply(message, "I have removed '" + item + "' to your tasks list.") } }) } }); } }); // simple function to generate the text of the task list so that // it can be used in various places function generateTaskList(user) { var text = ''; for (var t = 0; t < user.tasks.length; t++) { text = text + '> `' + (t + 1) + '`) ' + user.tasks[t] + '\n'; } return text; } }
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $updated_name = $_POST['updated_name']; $updated_email = $_POST['updated_email']; $updated_username = $_POST['updated_username']; $updated_role = $_POST['updated_role']; $updated_status = $_POST['updated_status']; // active or inactive $selected_user_id = $_POST['selected_user_id']; try { require_once "./db_handler.inc.php"; require_once "./config_session.inc.php"; require_once "../models/edit_profile.inc.php"; require_once "../models/register.inc.php"; require_once "../models/users.inc.php"; require_once "../controllers/edit_profile.inc.php"; require_once "../controllers/register.inc.php"; $current_user = get_current_user_details($pdo, $selected_user_id); // Error handlers $errors = []; // Check for empty inputs if (empty($updated_name) && empty($updated_email) && empty($updated_username)) { // make sure to use local variables here $errors["empty_input"] = "Please fill at least one field to update your profile"; } else { // Check if at least one field is different from the old one if (!is_email_new($updated_email, $current_user['email']) && !is_username_new($updated_username, $current_user['username']) && !is_name_new($updated_name, $current_user['full_name'])) { $errors["no_changes"] = "No changes were made"; } // Check if email is invalid else if (is_email_invalid($updated_email) && !empty($updated_email)) { $errors["invalid_email"] = "Please enter a valid email address"; } // Check if username is taken else if (is_username_taken($pdo, $updated_username) && !empty($updated_username)) { $errors["username_taken"] = "Username is already taken"; } // Check if email is already registered else if (is_email_registered($pdo, $updated_email) && !empty($updated_email)) { $errors["email_taken"] = "Email is already registered"; } } // the fields that are still empty should be filled with the old values if (empty($updated_name)) { $updated_name = $current_user['full_name']; } if (empty($updated_email)) { $updated_email = $current_user['email']; } if (empty($updated_username)) { $updated_username = $current_user['username']; } if ($errors) { $_SESSION["errors_admin_edit_user"] = $errors; header('Location: ../pages/admin_manage_users.php'); die(); } // update user as admin update_user_as_admin($pdo, $selected_user_id, $updated_name, $updated_email, $updated_username, $updated_role, $updated_status); header('Location: ../pages/admin_manage_users.php?user_update=success'); $pdo = null; $stmt = null; die(); } catch (PDOException $e) { die("Failed to update user as admin: " . $e->getMessage()); } } else { header('Location: ../index.php'); die(); }
import {Word} from "nlptoolkit-dictionary/dist/Dictionary/Word"; export class VocabularyWord extends Word{ private readonly count : number; private readonly code: Array<number>; private readonly point: Array<number>; public static MAX_CODE_LENGTH = 40; private codeLength: number; /** * Constructor for a {@link VocabularyWord}. The constructor gets name and count values and sets the corresponding * attributes. It also initializes the code and point arrays for this word. * @param name Lemma of the word * @param count Number of occurrences of this word in the corpus */ constructor(name: string, count: number) { super(name); this.count = count; this.code = new Array<number>(VocabularyWord.MAX_CODE_LENGTH).fill(0); this.point = new Array<number>(VocabularyWord.MAX_CODE_LENGTH).fill(0) this.codeLength = 0; } /** * Accessor for the count attribute. * @return Number of occurrences of this word. */ getCount(): number{ return this.count } /** * Mutator for codeLength attribute. * @param codeLength New value for the codeLength. */ setCodeLength(codeLength: number){ this.codeLength = codeLength } /** * Mutator for code attribute. * @param index Index of the code * @param value New value for that indexed element of code. */ setCode(index: number, value: number){ this.code[index] = value } /** * Mutator for point attribute. * @param index Index of the point * @param value New value for that indexed element of point. */ setPoint(index: number, value: number){ this.point[index] = value } /** * Accessor for the codeLength attribute. * @return Length of the Huffman code for this word. */ getCodeLength(): number{ return this.codeLength } /** * Accessor for point attribute. * @param index Index of the point. * @return Value for that indexed element of point. */ getPoint(index: number): number{ return this.point[index] } /** * Accessor for code attribute. * @param index Index of the code. * @return Value for that indexed element of code. */ getCode(index: number): number{ return this.code[index] } }
function speechScores = SSGMMSAD(s, fs, params) % Speech activity detector (SAD) presented in, % % [1] Alexey Sholokhov, Md Sahidullah and Tomi Kinnunen, "Semi-Supervised Speech % Activity Detection with an Application to Automatic Speaker Verification", % to appear in Computer Speech & Language. % [2] Tomi Kinnunen and Padmanabhan Rajan, "A practical, self-adaptive voice % activity detector for speaker verification with noisy telephone and % microphone data", in proc. of ICASSP 2013, Vancouver. % % Inputs: % % s Column vector of PCM signal samples as obtained through "audioread" % function of MATLAB. % fs Sampling rate in Hertz % params Optional struct of control parameters. These parameters are % set by "set_SSGMM_default_params" function. % % Especially the minimum energy threshold (params.min_energy) may % require some fine-tuning depending on whether you work on telephone % or microphone data. According to our experience with NIST % speaker recognition data, values in the range [-75 dB ..-55 dB] % seem to give reasonable results on "typical" NIST SRE data. % % % Outputs: % % speechScores Log-likelihood ratios % % % NOTE! This code should be otherwise self-contained, but it does % use the spectral subtraction routines from Voicebox % (http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html) % So download Voicebox and add to your Matlab path. % % (C) Copyright School of Computing (SoC), University of Eastern Finland (UEF) % Use this code completely at your own risk. % % Feedback is always welcomed! % E-mail: sholok@cs.uef.fi, sahid@cs.uef.fi, tkinnu@cs.uef.fi % Compute value from s that we will use to initialize random number % generation, to make sure we get the SAME result if we repeat this twice % for the same signal. Making the seed dependent on signal on the other % makes sure that different signals get different noises added seed = floor(max(abs(s)) * length(s) + abs(min(s))) + 1; rng(seed); % Convert framing parameters from seconds into samples, for this % samplerate. frame_len_samp = round(params.frame_len * fs); frame_shift_samp = round(params.frame_shift * fs); % Check that we don't accidentally feed in stereo data if size(s, 2) > 1 speechScores = []; return; end; % Dithering to avoid having identical vectors in our speech and nonspeech % codebooks (yes, it actually is a problem if not done!) if params.dither s = s + (1e-09).*randn(length(s), 1); end; % Optional speech cleaning to enhance energy SAD initialization if params.clean_energy % Define Wiener filter parameters pp.g = 2; pp.e = 2; pp.ne = 1; pp.am = 10; % allow aggressive oversubtraction s_cleaned = specsub(s, fs, pp); % Extract frame energy values from cleaned frames frames = enframe(s_cleaned, boxcar(frame_len_samp), frame_shift_samp); energy = 20*log10(std(frames,[],2)'+eps); else % Extract frame energy values from original (noisy) frames frames = enframe(s, boxcar(frame_len_samp), frame_shift_samp); energy = 20*log10(std(frames,[],2)'+eps); end; % Extract MFCCs either from cleaned or original (noisy) signal if params.clean_MFCCs Cep = compute_MFCCs(s_cleaned, fs, params); else Cep = compute_MFCCs(s, fs, params); end; % RASTA filtering if params.rasta Cep = rastafilt(Cep')'; end [n, dim] = size(Cep); % For numerical stability make sure that (dim+1) points are available for each mixture component if n < 2*(dim+1)*params.vq_size error('[SAD]: Not enough data! n = %i, dim = %i.', n, dim); end n_init = ceil(n * params.energy_fraction); n_init = max(dim+1, n_init); % Energy_fraction cannot be more than 50% if init is not Oracle n_init = min(n_init, floor(n/2)); if params.use_pitch % Detect pitch [~, pv01] = detect_pitch(s, fs, params, n); else pv01 = zeros(n, 1); end % Rank all frame energies and determine the lowest and highest energy frames. n_pitch = sum(pv01); n_nonpitch = length(pv01) - n_pitch; [~, frame_idx] = sort(energy); pv01_sorted = pv01(frame_idx); idx_pitch = frame_idx(pv01_sorted > 0.5); idx_nonpitch = frame_idx(pv01_sorted < 0.5); % Non-speech model if n_nonpitch >= n_init % more than required % Choose the subset with the lowest energy nonspeech_frames = idx_nonpitch(1:n_init); elseif n_nonpitch>0 % less than required % Use all nonspeech_frames = [idx_nonpitch idx_pitch(1:n_init-n_nonpitch)]; else % Use pitch with the lowest energy nonspeech_frames = idx_pitch(1:n_init); end % Speech model if n_pitch >= n_init % more than required % Choose the subset with the highest energy speech_frames = idx_pitch(end-n_init+1:end); elseif n_pitch>0 % less than required % Use all speech_frames = [idx_pitch idx_nonpitch(end-(n_init-n_pitch)+1:end)]; else % Use non-pitch with the highest energy speech_frames = idx_nonpitch(end-n_init+1:end); end %AREF % if length(speech_frames) < 30 ||... % length(nonspeech_frames) < 30 % % if length(speech_frames) < (dim+1)*params.vq_size ||... % % length(nonspeech_frames) < (dim+1)*params.vq_size % error('[SAD]: Not enough frames to train models! speech = %i, nonspeech = %i.',... % length(speech_frames), length(nonspeech_frames)); % end % Train the speech and nonspeech models from the MFCC vectors corresponding % to the highest and lowest frame energies, respectively if params.VQ [~,speech_model] = kmeans(Cep(speech_frames, :), params.vq_size); [~,nonspeech_model] = kmeans(Cep(nonspeech_frames, :), params.vq_size); % Convert these into LLR-like scores D_speech = VQ_distance(Cep, speech_model); D_nonspeech = VQ_distance(Cep, nonspeech_model); LLR = min(D_nonspeech, [], 2)' - min(D_speech, [], 2)'; else if params.semisupervised labels = zeros(n, 1); else labels = zeros(n, 1) - 1; end labels(speech_frames) = 2; labels(nonspeech_frames) = 1; if params.semisupervised % SSGMM [~, LLR, ~] = ssgmm(Cep, labels, 'initIter', 1, 'numComp', [params.vq_size params.vq_size],... 'covType', params.covtype, 'numIter', 20, 'sharedCov', params.sharedcov); else % GMM options = statset('MaxIter', 20); speech_model = gmdistribution.fit(Cep(labels==2,:), params.vq_size, 'CovType', params.covtype,... 'sharedCov', params.sharedcov, 'Regularize', 0.001, 'Options',options); nonspeech_model = gmdistribution.fit(Cep(labels==1,:), params.vq_size, 'CovType', params.covtype,... 'sharedCov', params.sharedcov, 'Regularize', 0.001, 'Options',options); D_speech = gmm_loglikelihood(speech_model, Cep); D_nonspeech = gmm_loglikelihood(nonspeech_model, Cep); LLR = D_speech - D_nonspeech; end end % Accept ONLY if the energies are also high enough energy_mask = (energy >= params.min_energy); speechScores = -inf(n,1); speechScores(energy_mask) = LLR(energy_mask);
'use client' import { Button, Form, FormControl, FormField, FormItem, FormLabel, FormMessage, Input, Separator, SocialMediaAuth } from '@/components' import { auth } from '@/services' import { Routes, credentialSchema } from '@/utils' import { zodResolver } from '@hookform/resolvers/zod' import { RotateCcwIcon } from 'lucide-react' import Link from 'next/link' import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth' import { useForm } from 'react-hook-form' import { z } from 'zod' function SignInForm() { const form = useForm<z.infer<typeof credentialSchema>>({ resolver: zodResolver(credentialSchema), defaultValues: { email: '', password: '' } }) // eslint-disable-next-line @typescript-eslint/no-unused-vars const [signInWithEmailAndPassword, user, loading, error] = useSignInWithEmailAndPassword(auth) /** * Una función que maneja el envío del formulario al iniciar sesión con el correo electrónico y contraseña proporcionados. * * @param values - Los valores obtenidos del envío del formulario. * @return Una promesa que se resuelve una vez finalizado el proceso de inicio de sesión. */ const onSubmit = async (values: z.infer<typeof credentialSchema>) => { try { await signInWithEmailAndPassword(values.email, values.password) } catch (error) { console.error(error) } } return ( <div className='mx-auto grid w-full max-w-md gap-y-4'> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className='grid gap-y-4'> <FormField control={form.control} name='email' render={({ field }) => ( <FormItem> <FormLabel>Correo electrónico</FormLabel> <FormControl> <Input placeholder='johndoe@gmail.com' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name='password' render={({ field }) => ( <FormItem> <FormLabel>Contraseña</FormLabel> <FormControl> <Input type='password' placeholder='*********' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Link className='text-right text-sm font-medium underline' href={Routes.ForgotPassword}> ¿Olvidaste tu contraseña? </Link> {!loading && <Button type='submit'>Iniciar sesión</Button>} {loading && ( <Button disabled> <RotateCcwIcon className='animate-spin' /> </Button> )} </form> </Form> {error && <p className='text-sm font-medium text-red-500'>{error.message}</p>} <Separator /> <SocialMediaAuth /> <p className='text-center text-sm'> No tienes una cuenta?{' '} <Link className='font-medium underline' href={Routes.Register}> Crea una cuenta </Link> </p> </div> ) } export { SignInForm }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layouts/layout2}"> <head> <meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> </head> <!-- 사용자 스크립트 추가 --> <th:block layout:fragment="script"> <script th:inline="javascript"> $(document).ready(function(){ $("input[name=cartChkBox]").change( function(){ getOrderTotalPrice(); }); }); function getOrderTotalPrice(){ var orderTotalPrice = 0; $("input[name=cartChkBox]:checked").each(function() { var cartItemId = $(this).val(); var price = $("#price_" + cartItemId).attr("data-price"); var count = $("#count_" + cartItemId).val(); orderTotalPrice += price*count; }); $("#orderTotalPrice").html(orderTotalPrice+'원'); } function changeCount(obj){ var count = obj.value; var cartItemId = obj.id.split('_')[1]; var price = $("#price_" + cartItemId).data("price"); var totalPrice = count*price; $("#totalPrice_" + cartItemId).html(totalPrice+"원"); getOrderTotalPrice(); updateCartItemCount(cartItemId, count); } <!-- 전체 체크박스 선택 시 하위 체크박스 모두 선택 --> function checkAll(){ if($("#checkall").prop("checked")){ $("input[name=cartChkBox]").prop("checked",true); }else{ $("input[name=cartChkBox]").prop("checked",false); } getOrderTotalPrice(); } <!-- 장바구니 상품 개수 변경 --> function updateCartItemCount(cartItemId, count){ var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); var url = "/cartItem/" + cartItemId+"?count=" + count; $.ajax({ url : url, type : "PATCH", beforeSend : function(xhr){ /* 데이터를 전송하기 전에 헤더에 csrf값을 설정 */ xhr.setRequestHeader(header, token); }, dataType : "json", cache : false, success : function(result, status){ console.log("cartItem count update success"); }, error : function(jqXHR, status, error){ if(jqXHR.status == '401'){ alert('로그인 후 이용해주세요'); location.href='/members/login'; } else{ alert(jqXHR.responseJSON.message); } } }); } <!-- 장바구니 상품 삭제 --> function deleteCartItem(obj){ var cartItemId = obj.dataset.id; var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); var url = "/cartItem/" + cartItemId; $.ajax({ url : url, type : "DELETE", beforeSend : function(xhr){ /* 데이터를 전송하기 전에 헤더에 csrf값을 설정 */ xhr.setRequestHeader(header, token); }, dataType : "json", cache : false, success : function(result, status){ location.href='/cart'; }, error : function(jqXHR, status, error){ if(jqXHR.status == '401'){ alert('로그인 후 이용해주세요'); location.href='/members/login'; } else{ alert(jqXHR.responseJSON.message); } } }); } <!-- 장바구니 상품 주문 --> function orders(){ var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); var url = "/cart/orders"; var dataList = new Array(); var paramData = new Object(); $("input[name=cartChkBox]:checked").each(function() { var cartItemId = $(this).val(); var data = new Object(); data["cartItemId"] = cartItemId; dataList.push(data); }); paramData['cartOrderDtoList'] = dataList; var param = JSON.stringify(paramData); $.ajax({ url : url, type : "POST", contentType : "application/json", data : param, beforeSend : function(xhr){ /* 데이터를 전송하기 전에 헤더에 csrf값을 설정 */ xhr.setRequestHeader(header, token); }, dataType : "json", cache : false, success : function(result, status){ location.href='/post'; }, error : function(jqXHR, status, error){ if(jqXHR.status == '401'){ alert('로그인 후 이용해주세요'); location.href='/members/login'; } else{ alert(jqXHR.responseJSON.message); } } }); } </script> </th:block> <!-- 사용자 CSS 추가 --> <th:block layout:fragment="css"> <style> h3 { text-align: center; margin : 20px 0; } .content-mg{ margin-left:25%; margin-right:25%; margin-top:2%; margin-bottom:100px; } .repImgDiv{ margin-right:15px; margin-left:15px; height:auto; } .repImg{ height:100px; width:100px; } .cartinfo td { text-align : center; } .fs18{ font-size:16px } .fs24{ font-size:22px } .cartlist { margin : 0 20%; } .mt-3 { margin : 5px 0 15px 0; } .btn-lg { display : inline-block; margin: 10px 5px 20px 5px; border-radius : 0px; background-color : #333; color : #f9f9f9; min-width : 100px; } </style> </th:block> <div layout:fragment="content" class="cartlist"> <h3>장바구니</h3> <div> <table class="table"> <colgroup> <col width="5%"/> <col width="55%"/> <col width="15%"/> <col width="10%"/> <col width="15%"/> </colgroup> <thead> <tr class="cartinfo"> <td> <input type="checkbox" id="checkall" onclick="checkAll()"> </td> <td>상품정보</td> <td>상품금액</td> <td>수량</td> <td>주문금액</td> </tr> </thead> <tbody> <tr th:each="cartItem : ${cartItems}"> <td class="text-center align-middle"> <input type="checkbox" name="cartChkBox" th:value="${cartItem.cartItemId}"> </td> <td class="d-flex"> <div class="repImgDiv align-self-center"> <img th:src="${cartItem.imgUrl}" class="rounded repImg" th:alt="${cartItem.itemNm}"> </div> <div class="align-self-center"> <span th:text="${cartItem.itemNm}" class="fs20"></span> </div> </td> <td class="text-center align-middle"> <div> <span class="input-group" style="justify-content:center;"> <span th:id="'price_' + ${cartItem.cartItemId}" th:data-price="${cartItem.price}" th:text="${cartItem.price} + '원'" class="align-self-center"> </span> </span> </div> </td> <td class="text-center align-middle"> <div class="fs18 font-weight-light"> <span class="input-group"> <input type="number" name="count" th:id="'count_' + ${cartItem.cartItemId}" th:value="${cartItem.count}" min="1" onchange="changeCount(this)" class="form-control mr-2"> <button type="button" class="close" aria-label="Close"> <span aria-hidden="true" th:data-id="${cartItem.cartItemId}" onclick="deleteCartItem(this)">X</span> </button> </span> </div> </td> <td class="text-center align-middle fs18 font-weight-light"> <span th:id="'totalPrice_' + ${cartItem.cartItemId}" name="totalPrice" th:text="${cartItem.price * cartItem.count} + '원'"> </span> </td> </tr> </tbody> </table> <h3 class="text-right"> 총 주문 금액 <span id="orderTotalPrice" class="text-info">0원</span> </h3> <div class="text-right mt-3"> <button type="button" class="btn btn-lg" onclick="orders()">주문하기</button> </div> </div> </div> </html>
import React, { useState } from "react"; import PhoneInput from "react-phone-input-2"; import "react-phone-input-2/lib/style.css"; import { useDispatch, useSelector } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import { Alert } from 'antd'; import { useEffect } from "react"; import { createTutorLogin } from "../../../redux/reducers/auth/authSlice"; const TutorLogin = () => { const dispatch = useDispatch(); const navigate = useNavigate(); const [phone, setPhone] = useState(""); const { errorMessage, isAuthenticated} = useSelector( (state) => state.user ); const [isPhoneValid, setPhoneIsValid] = useState(false); const [password, setPassword] = useState(""); const handlePasswordChange = (e) => { setPassword(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); dispatch(createTutorLogin({ phone, password })); }; useEffect(() => { if (isAuthenticated) { navigate('/tutor/profile'); } }, [navigate, isAuthenticated]); return ( <main className="flex flex-1 justify-center items-center mt-24"> <div className="w-full max-w-sm mx-auto overflow-hidden bg-white rounded-lg shadow-md dark:bg-gray-800"> <div className="px-6 py-4"> <p className="mt-10 text-start text-gray-500 dark:text-gray-400 font-mono"> Login or create account </p> <form onSubmit={handleSubmit}> <div className="w-full mt-8"> <PhoneInput country={"bd"} inputProps={{ name: "Phone", required: true, // autoFocus: true, }} isValid={(value, country) => { if (value.match(/(^(\+880|880))[1|3-9]{1}(\d){9}$/)) { setPhoneIsValid(true); return true; } else { setPhoneIsValid(false); return "Invalid Phone"; // return "Invalid value: " + value + ", " + country.name; } }} onChange={(phone) => setPhone(phone)} required /> </div> <div className="w-full mt-4"> <input className="block w-full h-12 px-4 py-2 mt-2 text-gray-700 placeholder-gray-500 bg-white border rounded-lg dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-opacity-40 focus:outline-none focus:ring focus:ring-blue-300" type="password" placeholder="Password" aria-label="Password" onChange={handlePasswordChange} required /> </div> <div className="flex items-center justify-between mt-4"> <Link to="#" className="font-mono text-sm text-gray-600 dark:text-gray-200 hover:text-gray-500" > Forget Password? </Link> <button className=" font-mono px-6 py-2 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-black rounded-lg "> Sign In </button> </div> { errorMessage ? <Alert message={errorMessage} showIcon type="error" className="mt-4" /> : null } </form> </div> <div className="flex items-center justify-center py-4 text-center bg-gray-50 dark:bg-gray-700"> <span className="text-sm text-gray-600 dark:text-gray-200 font-mono"> Don't have an account?{" "} </span> <Link to="/auth/tutor/register" className="font-mono mx-2 text-sm font-bold text-blue-500 dark:text-blue-400 hover:underline" > Create </Link> </div> </div> </main> ); }; export default TutorLogin;
import React,{useContext, useState, useEffect} from 'react'; import {ethers} from 'ethers'; import web3 from 'web3'; import {contractABI, contractAddress} from '../../utils/constants'; export const UserContext = React.createContext(); const {ethereum} = window; const getEthereumContract = () => { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const lotteryContract = new ethers.Contract(contractAddress, contractABI, signer); // console.log({ // provider, // signer, // lotteryContract // }); return lotteryContract; } const UserProvider = ({children}) => { const [currentAccount, setCurrentAccount] = useState(''); const [isUserRegistered, setIsUserRegistered] = useState(false); const [formData, setFormData] = useState(); const [isLoading, setIsLoading] = useState(false); const [lotteryList, setLotteryList] = useState([]); const checkIfWalletIsConnected = async () => { try { if(!ethereum) return alert("Please install metamask"); const accounts = await ethereum.request({method: 'eth_accounts'}); setCurrentAccount(accounts[0]); } catch (error) { console.error(error); } } const CheckIfAddressRegistered = async () => { try { if(!ethereum) return alert("Please install metamask"); const contract = getEthereumContract(); const getUserDetails = await contract.getParticipantDetails(); if(getUserDetails[0] !== ''){ setIsUserRegistered(true); } // console.log("getUserDetails",getUserDetails); } catch (error) { console.error(error); } } const userSignup = async() => { let {userName, age, mobileNo} = formData; // console.log("formData",formData); const contract = getEthereumContract(); setIsLoading(true); const contractResponse = await contract.addNewParticipant(userName, age, mobileNo); setIsLoading(false); // console.log("Response", contractResponse); } const connectWallet = async () => { try { if(!ethereum) return alert("Please install metamask"); const accounts = await ethereum.request({method:'eth_requestAccounts'}) if(accounts.length){ console.log("selected account is ", accounts[0]); } else { console.log("No account found"); } } catch (error) { console.error(error); } } const handleChange = (e,name) => { setFormData((prevData) => ({...prevData,[name]: e.target.value})); } const getDateTimeFormat = (dateTime) => { const temp = new Date(parseInt(dateTime) * 1000); const newDateTime = `${temp.getMonth()+1}/${temp.getDate()}/${temp.getFullYear()} - ${temp.getHours()}:${temp.getMinutes()}` return newDateTime; } const structureLotteryData = (data) => { const tempStringPrice = parseInt(data.ticketPrice._hex) + ""; const temp = { lotteryID: parseInt(data.lottery_ID._hex), lotteryName: data.lootName, startDateTime: getDateTimeFormat(data.startDateTime), endDateTime: getDateTimeFormat(data.endDateTime), drawDateTime: getDateTimeFormat(data.drawDateTime), ticketPrice: ethers.utils.formatEther(tempStringPrice), ticketStatus: data.status, totalCollection: parseInt(data.totalCollection) } return temp; } const getLotteryDetails = async (_id) => { try { const contract = getEthereumContract(); const lotteryDetails = await contract.allLottery(_id); return lotteryDetails; // console.log("lotteryDetails",lotteryDetails); } catch (error) { console.error(error); } } const getAllLottery = async () => { console.log("test"); try { const contract = getEthereumContract(); const response = await contract.activeTickets(1); // console.log("Lottery Details",response); } catch (error) { console.error(error); } } const structureLotteryList = (arr) => { const temp = arr.map((el,i)=> { return parseInt(el._hex); }); return temp; } const getAllOpenLottery = async () => { try{ const newLotteryList = []; const lotteryContract = getEthereumContract(); const arrList = await lotteryContract.getAllActiveLotteryArrayList(); const lotteryList = structureLotteryList(arrList); for(let i = 0; i < lotteryList.length; i++) { const lotteryData = await getLotteryDetails(lotteryList[i]); const structuredData = structureLotteryData(lotteryData); if(structuredData.ticketStatus === 1){ newLotteryList.push(structuredData); } } setLotteryList(newLotteryList); } catch(error) { console.error(error); throw new Error("No Ethereum object"); } } const buyLottery = async (lotteryID, ticketPrice) => { try { const contract = getEthereumContract(); const toString = '' + ticketPrice; const price = web3.utils.toWei(toString,"ether"); const transHash = await contract.buyLottery(lotteryID,{value:price}); console.log("trans hash", transHash); } catch (error) { console.log("Something went wrong"); } } useEffect(()=>{ if(currentAccount !== ''){ CheckIfAddressRegistered(); } },[currentAccount]); useEffect(()=>{ if(isUserRegistered){ //getAllLottery(); } },[isUserRegistered]); useEffect(()=>{ checkIfWalletIsConnected(); getAllOpenLottery(); },[]) return(<UserContext.Provider value={{isUserRegistered, userSignup, currentAccount, connectWallet, handleChange, isLoading, formData, lotteryList, buyLottery}}> {children} </UserContext.Provider>); }; export default UserProvider;
import { Location } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { IGovernarate } from '../../models/igovernarate'; import { Ripple, Input, initTE } from 'tw-elements'; import { GovernorateService } from '../../services/governorate.service'; import { AngularMateralService } from '../../services/angular-materal.service'; @Component({ selector: 'app-add-governarate', templateUrl: './add-governarate.component.html', styleUrls: ['./add-governarate.component.css'], }) export class AddGovernarateComponent implements OnInit { governateForm: FormGroup; UpdateOrDelete: boolean; currentCode: number=0; formTitle: string; constructor( private fb: FormBuilder, private router: Router, private locationService: Location, private activateRoute: ActivatedRoute, private govService: GovernorateService, private angularMaterailaServ: AngularMateralService ) { this.UpdateOrDelete = true; (this.formTitle = 'Add New Governorate'), (this.governateForm = fb.group({ code: ['', [Validators.required]], name: ['', [Validators.required, Validators.maxLength(50)]], })); } ngOnInit(): void { initTE({ Ripple, Input }); this.activateRoute.paramMap.subscribe((param) => { this.currentCode = Number(param.get('code')); if (this.currentCode) { this.UpdateOrDelete = false; this.formTitle = 'Update Governorate'; this.govService.GetById(this.currentCode).subscribe((gov) => { this.governateForm.setValue({ code: gov.code, name: gov.name, }); }); } }); } //get name get name() { return this.governateForm.get('name'); } //get code get code() { return this.governateForm.get('code'); } //backToGovList backToGovList() { this.locationService.back(); } //add governate AddGovernarate() { let newGov:IGovernarate = this.governateForm.value as IGovernarate; this.govService.Add(newGov).subscribe({ next:(resp)=> { this.angularMaterailaServ.addAndUpdateSuccess("Governorate Added Successfully"); this.governateForm.reset(); }, error:(e)=>{ this.angularMaterailaServ.addAndUpdateSuccess("'An Error Occured Try Again Later'"); } }) } //update governorate updateGov(){ let governarate:IGovernarate = this.governateForm.value as IGovernarate; this.govService.Update(governarate.code,governarate).subscribe({ next:(resp)=>{ this.router.navigate(['/Governorates']); this.angularMaterailaServ.addAndUpdateSuccess("Governorate Updated Successfully") }, error:(e)=>{ this.angularMaterailaServ.addAndUpdateSuccess("'An Error Occured Try Again Later'"); } }) } }
function flag = checkForWorker(obj,checkMode) % CHECKFORWORKER Checks for worker to determine if this is being run on % local machine or remote server. Also uses the settings in % nigeLab.defaults.Queue as a heuristic if no input % arguments are provided. % % flag = nigeLab.utils.checkForWorker(); Return true if on REMOTE % % flag = nigeLab.utils.checkForWorker(nigelObj); % % flag = nigeLab.utils.checkForWorker('config'); % --> Runs procedurally generated configuration script, configW % % flag = nigeLab.utils.checkForWorker(nigelObj,'config'); % --> Does less checks based on nigelObj.UseParallel property flag % % See Also: % NIGELAB.LIBS.DASHBOARD/QOPERATIONS, NIGELAB.DEFAULTS.QUEUE %% If no inputs, use struct directly from nigeLab.defaults.Queue if nargin < 1 flag = false; qParams = nigeLab.defaults.Queue; if ~qParams.UseParallel && ~qParams.UseRemote flag = false; return; end if qParams.UseParallel... check user preference && license('test','Distrib_Computing_Toolbox')... check if toolbox is licensed && ~isempty(ver('distcomp'))... and check if it's installed job = getCurrentJob; % if job is empty, we are running locally. % Or at least not on a worker. flag = ~isempty(job); elseif (~license('test','Distrib_Computing_Toolbox')... || isempty(ver('distcomp')))... && qParams.UseParallel % Prompt the user to install the correct toolboxes nigeLab.utils.cprintf('SystemCommands',obj.Verbose,'Parallel computing toolbox might be uninstalled or unlicensed on this machine.\n'); nigeLab.utils.cprintf('Comments',obj.Verbose,'But no worries: your code will still be executed serially.\n'); nigeLab.utils.cprintf('Comments',obj.Verbose,'However, depending on recording size, this can take substantially longer.\n'); end return; end %% If more than one input is given switch class(obj) case 'char' checkMode = obj; if strcmpi(checkMode,'config') % nargin > 0 %% in config mode checkForWorker and run the config script flag = false; if nigeLab.utils.checkForWorker() configW; % run the programmatically generated configuration script; this is generated in qOperations flag = true; end end case {'nigeLab.Block','nigeLab.Animal','nigeLab.Tank','nigeLab.nigelObj'} if obj.OnRemote flag = true; return; end if ~isempty(obj.UseParallel) compat_flag = obj.UseParallel; else compat_flag = obj.checkParallelCompatibility(); end config_flag = obj.Pars.Queue.UseParallel || ... obj.Pars.Queue.UseRemote; if compat_flag ~= config_flag nigeLab.utils.cprintf('SystemCommands',obj.Verbose,... ['Mismatch between parsed '... 'parallel configuration and default parameters. \n']); if obj.Verbose str = nigeLab.utils.getNigeLink(class(obj),... 'checkParallelCompatibility'); fprintf(1,'Consider re-running %s\n',str); objName = inputname(1); fprintf(1,['\t-->\t<a href="matlab:%s.checkParallelCompatibility();"' ... '(Click here re-run check)</a> <--\n\n'],objName); end end if compat_flag job = getCurrentJob; % if job is empty, we are running locally. % Or at least not on a worker. flag = ~isempty(job); else flag = false; end if nargin > 1 switch lower(checkMode) case 'config' if flag configW; end otherwise end end otherwise end end
import React from 'react'; import PropTypes from 'prop-types'; /** * wrapper for fontawesome icons * @returns {JSX.Element} * @constructor */ export default function Icon(props) { const { type, spin = false, color = 'inherit', style } = props; const additionalClasses = []; if (spin) { additionalClasses.push('fa-spin'); } return ( <span style={{ color, ...style }}> <i className={`fa fa-${type} ${additionalClasses.join(' ')}`} /> </span> ); } Icon.propTypes = { type: PropTypes.string.isRequired, spin: PropTypes.bool, color: PropTypes.string, };
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; class AlbumSearch extends React.Component { constructor() { super(); this.state = { artistId: '', artistName: '', collectionId: '', collectionName: '', artworkUrl100: '', }; } componentDidMount() { const { artistId, artistName, collectionId, collectionName, artworkUrl100, } = this.props; this.setState({ artistId, artistName, collectionId, collectionName, artworkUrl100, }); } render() { const { artistId, artistName, collectionId, collectionName, artworkUrl100, } = this.state; return ( <li key={ artistId }> <img src={ artworkUrl100 } alt={ artistName } /> <p>{ collectionName }</p> <p>{ artistName }</p> <Link to={ `/album/${collectionId}` } data-testid={ `link-to-album-${collectionId}` } > Escutar </Link> </li> ); } } AlbumSearch.propTypes = { artistId: PropTypes.string.isRequired, artistName: PropTypes.string.isRequired, collectionId: PropTypes.string.isRequired, collectionName: PropTypes.string.isRequired, artworkUrl100: PropTypes.string.isRequired, }; export default AlbumSearch;
<script setup lang="ts"> import { useSwiper } from 'swiper/vue' import type { CSSProperties, PropType } from 'vue' import titlebg from '~/assets/common/title-bg.png' const props = defineProps({ bg: String, h5bg: String, title: String, align: String, contentStyle: Object as PropType<CSSProperties>, titleStyle: Object as PropType<CSSProperties>, showHeader: { type: Boolean, default: false }, showFooter: { type: Boolean, default: false }, }) const isShowFooter = ref(false) const footerEl = ref<HTMLDivElement | null>() const swiper = useSwiper() // if (swiper.value) // swiper.value.allowTouchMove = false // swiperEvent() function handleMousewheel(e: WheelEvent) { if (!props.showFooter) return const wheelDelta = (e as any).wheelDelta as number ?? e.detail if (wheelDelta > 0 && isShowFooter.value) { // 当鼠标滚轮向上滚动时 e.stopPropagation() isShowFooter.value = false } if (wheelDelta < 0) { // 当鼠标滚轮向下滚动时 isShowFooter.value = true } } // const scrolling = ref(false) function handleContentWheel(e: WheelEvent) { const target = e.currentTarget as HTMLDivElement console.log('wheel') if (!target) return const { scrollHeight, clientHeight, scrollTop } = target if (scrollHeight > clientHeight) { const wheelDelta = (e as any).wheelDelta as number ?? e.detail if (wheelDelta > 0) { // 当鼠标滚轮向上滚动时 if (scrollTop > 0) e.stopPropagation() } if (wheelDelta < 0) { // 当鼠标滚轮向下滚动时 if (scrollTop >= 0 && (scrollTop + clientHeight) < scrollHeight) e.stopPropagation() } } } function handleContentScroll() { } const { handleTouchStart, handleTouchMove } = (() => { let startX = 0 let startY = 0 let moveEndX = 0 let moveEndY = 0 let X let Y let timer = 0 function handleTouchStart(e: TouchEvent) { e.preventDefault() return startX = e.touches[0].pageX startY = e.touches[0].pageY } function handleTouchMove(e: TouchEvent) { // swiper.value.allowTouchMove = true e.preventDefault() return const target = e.currentTarget as HTMLDivElement // console.dir(target) if (!target) return const { scrollHeight, clientHeight, scrollTop } = target // e.preventDefault() moveEndX = e.changedTouches[0].pageX moveEndY = e.changedTouches[0].pageY X = moveEndX - startX Y = moveEndY - startY if (Math.abs(X) > Math.abs(Y) && X > 0) { // alert('向右') } else if (Math.abs(X) > Math.abs(Y) && X < 0) { // alert('向左') } else if (Math.abs(Y) > Math.abs(X) && Y > 0) { console.log('向下') clearTimeout(timer) timer = setTimeout(() => { if (scrollHeight > clientHeight) { if (scrollTop > 0 && (scrollTop + clientHeight) < scrollHeight) e.stopPropagation() // e.stopImmediatePropagation() // e.preventDefault() // swiper.value.allowTouchMove = false else swiper.value.slidePrev() } else { swiper.value.slidePrev() } }) } else if (Math.abs(Y) > Math.abs(X) && Y < 0) { console.log('向上') if (scrollHeight > clientHeight) { if (scrollTop > 0) e.stopPropagation() // e.stopImmediatePropagation() // e.preventDefault() // swiper.value.allowTouchMove = false else swiper.value.slideNext() // swiper.value.allowTouchMove = true } else { swiper.value.slideNext() } } else { // swiper.value.allowTouchMove = true } // else // alert('没滑动') } return { handleTouchMove, handleTouchStart } })() </script> <template> <div class="page-item" h="full" bg="no-repeat center cover" relative flex="~ col items-center justify-center" :style="{ '--page-item-bg': `url(${bg})`, '--page-item-h5-bg': `url(${h5bg ?? bg})`, 'marginTop': isShowFooter ? `-${footerEl?.clientHeight}px` : 0, 'justifyContent': props.align, 'backgroundPositionY': showHeader ? `var(--app-header-height)` : '', }" transition="margin duration-500" overflow="hidden" @wheel="handleMousewheel" > <TheHeader v-if="showHeader" /> <!-- <img :src="bg" h-full w-full absolute="~ inset-0" object="center cover"> --> <div v-if="title" relative="~" text="28px" font="bold" flex="~ justify-center items-center" px="8em" m="t-4 b-8 " lt-lg="mt-6vw text-16px" :style="titleStyle"> <span relative z="2">{{ title }}</span> <img absolute="~ inset-0" :src="titlebg" alt=""> </div> <div w-full overflow-auto px="1/10" :style="contentStyle" class="" @wheel="handleContentWheel" @scroll="handleContentScroll" @touchmove="handleTouchMove" @touchstart="handleTouchStart"> <slot /> </div> </div> <div v-if="showFooter" ref="footerEl" w-full> <TheFooter /> </div> </template> <style scoped> .page-item { background-image: var(--page-item-bg); } @screen lt-lg { .page-item { background-image: var(--page-item-h5-bg); } } </style>
# frozen_string_literal: true class DateFormatValidator class MinDateError < StandardError; end include ActiveModel::Validations MAX_DATE = "3000-12-31 23:59:59".freeze ISO_ERROR_MSG = "supplied value is invalid, expected ISO 8601 format".freeze MIN_DATE_ERROR_MSG = "must be greater than or equal to".freeze def initialize(param_name:, param_value:, min_date: Time.zone.today, require_iso8601: true) @param_name = param_name @param_value = param_value @min_date = min_date @require_iso8601 = require_iso8601 @errors = ActiveModel::Errors.new(self) end def call begin validate_with_iso8601 validate_with_dry_schema validate_min_date rescue StandardError => e errors.add(param_name, "#{param_name.to_s.humanize}: #{e.message}") end self end def self.validate(...) new(...).call end def success? errors.blank? end attr_reader :param_name, :param_value, :min_date, :require_iso8601, :errors private def validate_with_dry_schema result = dry_schema.call({ param_name => param_value }) raise ArgumentError, result.errors[param_name][0] if result.failure? end def dry_schema param = param_name Dry::Schema.Params do config.messages.namespace = :api_errors optional(param).filled(:date_time, lteq?: MAX_DATE) end end def validate_with_iso8601 return if !require_iso8601 DateTime.iso8601(param_value) rescue Date::Error, TypeError => e raise e, ISO_ERROR_MSG end # As we want to be sure that there will be no zone issues, # we need to have the correct date provided explicitly. def validate_min_date return if min_date.nil? result = Date.parse(param_value.to_s) >= Date.parse(min_date.to_s) return if result raise MinDateError, "#{MIN_DATE_ERROR_MSG} #{min_date.to_date}" end end
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common'; import { Request, Response } from 'express'; @Catch() export class ErrorFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const request = ctx.getRequest<Request>(); const status = exception?.status ?? 500; const message = exception?.message ?? 'Internal server error'; response.status(status).json({ success: false, statusCode: status, timestamp: new Date().toISOString(), path: request.url, message: message, }); } }
package com.ruoyi.core.domain; import java.math.BigDecimal; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * A 模块成绩对象 a_module_score * * @author heye * @date 2024-04-28 */ public class AModuleScore extends BaseEntity { private static final long serialVersionUID = 1L; /** A模块成绩主键 */ private Long modscoId; /** 总分ID */ @Excel(name = "总分ID") private Long tsId; /** 线上学习 */ @Excel(name = "线上学习") private BigDecimal onlineCourse; /** 知识测试 */ @Excel(name = "知识测试") private BigDecimal knowledgeTests; /** 技能练习1 */ @Excel(name = "技能练习1") private BigDecimal skillTests1; /** 课堂表现 */ @Excel(name = "课堂表现") private BigDecimal classroomPerformance; /** 思政教育 */ @Excel(name = "思政教育") private BigDecimal ideologicalPolitical; /** 学生互评 */ @Excel(name = "学生互评") private BigDecimal peerAssessment; /** 助教评价 */ @Excel(name = "助教评价") private BigDecimal teachingAssistant; /** 教师评价 */ @Excel(name = "教师评价") private BigDecimal teacherEvaluation; /** 技能测试2 */ @Excel(name = "技能测试2") private BigDecimal skillTests2; /** 体能测试2 */ @Excel(name = "体能测试2") private BigDecimal fitnessTests2; /** 技术练习3 */ @Excel(name = "技术练习3") private BigDecimal skillTests3; /** 体能练习3 */ @Excel(name = "体能练习3") private BigDecimal fitnessTests3; public void IAModuleScore() { this.onlineCourse = BigDecimal.ZERO; this.knowledgeTests = BigDecimal.ZERO; this.skillTests1 = BigDecimal.ZERO; this.classroomPerformance = BigDecimal.ZERO; this.ideologicalPolitical = BigDecimal.ZERO; this.peerAssessment = BigDecimal.ZERO; this.teachingAssistant = BigDecimal.ZERO; this.skillTests2 = BigDecimal.ZERO; this.fitnessTests2 = BigDecimal.ZERO; this.skillTests3 = BigDecimal.ZERO; this.fitnessTests3 = BigDecimal.ZERO; this.teacherEvaluation = BigDecimal.ZERO; } public BigDecimal addAll() { BigDecimal stuScore = BigDecimal.ZERO; // 初始化总分为0 // 对每个字段进行非空检查,如果为null则视为BigDecimal.ZERO stuScore = stuScore.add(this.skillTests1 != null ? this.skillTests1 : BigDecimal.ZERO); stuScore = stuScore.add(this.knowledgeTests != null ? this.knowledgeTests : BigDecimal.ZERO); stuScore = stuScore.add(this.classroomPerformance != null ? this.classroomPerformance : BigDecimal.ZERO); stuScore = stuScore.add(this.ideologicalPolitical != null ? this.ideologicalPolitical : BigDecimal.ZERO); stuScore = stuScore.add(this.peerAssessment != null ? this.peerAssessment : BigDecimal.ZERO); stuScore = stuScore.add(this.onlineCourse != null ? this.onlineCourse : BigDecimal.ZERO); stuScore = stuScore.add(this.teacherEvaluation != null ? this.teacherEvaluation : BigDecimal.ZERO); stuScore = stuScore.add(this.teachingAssistant != null ? this.teachingAssistant : BigDecimal.ZERO); stuScore = stuScore.add(this.skillTests2 != null ? this.skillTests2 : BigDecimal.ZERO); stuScore = stuScore.add(this.fitnessTests2 != null ? this.fitnessTests2 : BigDecimal.ZERO); stuScore = stuScore.add(this.fitnessTests3 != null ? this.fitnessTests3 : BigDecimal.ZERO); stuScore = stuScore.add(this.skillTests3 != null ? this.skillTests3 : BigDecimal.ZERO); return stuScore; // 返回计算后的总分 } public void setModscoId(Long modscoId) { this.modscoId = modscoId; } public Long getModscoId() { return modscoId; } public void setTsId(Long tsId) { this.tsId = tsId; } public Long getTsId() { return tsId; } public void setOnlineCourse(BigDecimal onlineCourse) { this.onlineCourse = onlineCourse; } public BigDecimal getOnlineCourse() { return onlineCourse; } public void setKnowledgeTests(BigDecimal knowledgeTests) { this.knowledgeTests = knowledgeTests; } public BigDecimal getKnowledgeTests() { return knowledgeTests; } public void setSkillTests1(BigDecimal skillTests1) { this.skillTests1 = skillTests1; } public BigDecimal getSkillTests1() { return skillTests1; } public void setClassroomPerformance(BigDecimal classroomPerformance) { this.classroomPerformance = classroomPerformance; } public BigDecimal getClassroomPerformance() { return classroomPerformance; } public void setIdeologicalPolitical(BigDecimal ideologicalPolitical) { this.ideologicalPolitical = ideologicalPolitical; } public BigDecimal getTeacherEvaluation() { return teacherEvaluation; } public void setTeacherEvaluation(BigDecimal teacherEvaluation) { this.teacherEvaluation = teacherEvaluation; } public BigDecimal getIdeologicalPolitical() { return ideologicalPolitical; } public void setPeerAssessment(BigDecimal peerAssessment) { this.peerAssessment = peerAssessment; } public BigDecimal getPeerAssessment() { return peerAssessment; } public void setTeachingAssistant(BigDecimal teachingAssistant) { this.teachingAssistant = teachingAssistant; } public BigDecimal getTeachingAssistant() { return teachingAssistant; } public void setSkillTests2(BigDecimal skillTests2) { this.skillTests2 = skillTests2; } public BigDecimal getSkillTests2() { return skillTests2; } public void setFitnessTests2(BigDecimal fitnessTests2) { this.fitnessTests2 = fitnessTests2; } public BigDecimal getFitnessTests2() { return fitnessTests2; } public void setSkillTests3(BigDecimal skillTests3) { this.skillTests3 = skillTests3; } public BigDecimal getSkillTests3() { return skillTests3; } public void setFitnessTests3(BigDecimal fitnessTests3) { this.fitnessTests3 = fitnessTests3; } public BigDecimal getFitnessTests3() { return fitnessTests3; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("modscoId", getModscoId()) .append("tsId", getTsId()) .append("onlineCourse", getOnlineCourse()) .append("knowledgeTests", getKnowledgeTests()) .append("skillTests1", getSkillTests1()) .append("classroomPerformance", getClassroomPerformance()) .append("ideologicalPolitical", getIdeologicalPolitical()) .append("peerAssessment", getPeerAssessment()) .append("teachingAssistant", getTeachingAssistant()) .append("skillTests2", getSkillTests2()) .append("fitnessTests2", getFitnessTests2()) .append("teacherEvaluation", getTeacherEvaluation()) .append("skillTests3", getSkillTests3()) .append("fitnessTests3", getFitnessTests3()) .toString(); } }
#include "lists.h" /** *add_dnodeint - add node at beginning of list *@head: pointer to head pointer *@n: data in node *Return: pointer to new node */ dlistint_t *add_dnodeint(dlistint_t **head, const int n) { dlistint_t *new_node; new_node = (dlistint_t *)malloc(sizeof(dlistint_t)); if (new_node == NULL) { return (NULL); } new_node->n = n; new_node->next = *head; new_node->prev = NULL; if (*head != NULL) { (*head)->prev = new_node; } *head = new_node; return (new_node); }
#include <iostream> #include <string> using namespace std; struct Node { string nama; int usia; Node* next; }; class LinkedList { private: Node* head; public: LinkedList() { head = nullptr; } void tambahDepan(string nama, int usia) { Node* newNode = new Node(); newNode->nama = nama; newNode->usia = usia; newNode->next = head; head = newNode; } void tambahBelakang(string nama, int usia) { Node* newNode = new Node(); newNode->nama = nama; newNode->usia = usia; newNode->next = nullptr; if (head == nullptr) { head = newNode; return; } Node* lastNode = head; while (lastNode->next != nullptr) { lastNode = lastNode->next; } lastNode->next = newNode; } void tambahTengah(string nama, int usia, int posisi) { if (posisi < 0) { cout << "Posisi harus lebih besar dari 0" << endl; return; } if (posisi == 0) { tambahDepan(nama, usia); return; } Node* newNode = new Node(); newNode->nama = nama; newNode->usia = usia; Node* current = head; for (int i = 0; i < posisi - 1; ++i) { if (current == nullptr) { cout << "Posisi melebihi panjang linked list" << endl; return; } current = current->next; } newNode->next = current->next; current->next = newNode; } void hapusData(string nama) { Node* current = head; Node* prev = nullptr; if (current != nullptr && current->nama == nama) { head = current->next; delete current; return; } while (current != nullptr && current->nama != nama) { prev = current; current = current->next; } if (current == nullptr) { cout << nama << " tidak ditemukan dalam linked list" << endl; return; } prev->next = current->next; delete current; } void editData(string namaLama, string namaBaru, int usiaBaru) { Node* current = head; while (current != nullptr) { if (current->nama == namaLama) { current->nama = namaBaru; current->usia = usiaBaru; return; } current = current->next; } cout << namaLama << " tidak ditemukan dalam linked list" << endl; } void tampilkan() { Node* current = head; while (current != nullptr) { cout << current->nama << "\t" << current->usia << endl; current = current->next; } } }; int main() { LinkedList linkedList; string nama; int usia; int pilihan; int posisi; string namaLama; string namaBaru; int usiaBaru; // Memasukkan data pertama cout << "Masukkan nama Anda: "; cin >> nama; cout << "Masukkan usia Anda: "; cin >> usia; linkedList.tambahDepan(nama, usia); // Memasukkan data sesuai dengan urutan yang diminta do { cout << "\nPilihan Menu:\n"; cout << "1. Tambahkan data di awal\n"; cout << "2. Tambahkan data di belakang\n"; cout << "3. Tambahkan data di tengah\n"; cout << "4. Edit data\n"; cout << "5. Hapus data\n"; cout << "6. Tampilkan data\n"; cout << "7. Selesai\n"; cout << "Pilihan Anda: "; cin >> pilihan; switch (pilihan) { case 1: cout << "Masukkan nama mahasiswa: "; cin >> nama; cout << "Masukkan usia mahasiswa: "; cin >> usia; linkedList.tambahDepan(nama, usia); break; case 2: cout << "Masukkan nama mahasiswa: "; cin >> nama; cout << "Masukkan usia mahasiswa: "; cin >> usia; linkedList.tambahBelakang(nama, usia); break; case 3: cout << "Masukkan nama mahasiswa: "; cin >> nama; cout << "Masukkan usia mahasiswa: "; cin >> usia; cout << "Masukkan posisi: "; cin >> posisi; linkedList.tambahTengah(nama, usia, posisi); break; case 4: cout << "Masukkan nama mahasiswa yang ingin diubah: "; cin >> namaLama; cout << "Masukkan nama baru mahasiswa: "; cin >> namaBaru; cout << "Masukkan usia baru mahasiswa: "; cin >> usiaBaru; linkedList.editData(namaLama, namaBaru, usiaBaru); break; case 5: cout << "Masukkan nama mahasiswa yang ingin dihapus: "; cin >> nama; linkedList.hapusData(nama); break; case 6: cout << "\nData Mahasiswa:\n"; linkedList.tampilkan(); break; case 7: cout << "Terima kasih!\n"; break; default: cout << "Pilihan tidak valid!\n"; } } while (pilihan != 7); return 0; }
import type TupleConsistentType from 'fup-tuple-consistent-type'; import type TupleGainType from 'fup-tuple-gain-type'; import type TupleReverseType from 'fup-tuple-reverse-type'; import type CurryLimitResultType from 'fup-curry-limit-result-type'; export type CurryLimitReverseCore< ExpectedParameters extends readonly unknown[] = unknown[], ExpectedResult extends unknown = unknown, ExpectedLimit extends number = number, > = < Limit extends ExpectedLimit, Parameters extends ExpectedParameters, Result extends ExpectedResult, Arguments extends TupleConsistentType<TupleGainType<Limit, TupleReverseType<Parameters>>> > (limit: Limit, executor: (...parameters: Parameters) => Result, ...arguments: Arguments) => CurryLimitResultType< Limit, Arguments, TupleReverseType<Parameters>, Result >; /** * @example * const sum = (...numbers) => numbers * .reduce((added, num) => added + num, 0); * const sum2 = curryLimitReverseCore(2, sum); // (y, x) => y + x | y => x => y + x * const add1 = sum2(1); // (x) => 1 + x * const result = add1(2); // 3 * const x = sum2(10, 20); // 30 */ declare const curryLimitReverseCore: CurryLimitReverseCore; export default curryLimitReverseCore;
import { Injectable } from '@angular/core'; import * as d3 from "d3"; import { jsPanel } from 'node_modules/jspanel4/es6module/jspanel.min.js'; import { InterfacesService } from './interfaces.service'; import * as $ from "jquery"; var interfaces: Object = {}; @Injectable({ providedIn: 'root' }) export class NodePanelService { constructor( private _interfaces: InterfacesService) { this._interfaces.getInterfacesInfo().subscribe(data => interfaces = data); } getNodePanel(nodes, links, width, height) { function newMethod(arg, arg1) { console.log(arg1); jsPanel.create({ headerTitle: arg.name, content: `<div id = "node_interfaces"></div> <table class="table table-striped table-hover"> <thead> <tr> <th scope="col">Ifindex</th> <th scope="col">Name</th> <th scope="col">Status</th> <th scope="col">Description</th> </tr> </thead> <tbody id= 'table_body'> </tbody> </table>`, contentSize: { width: 600 , height: 400}, position: 'center', theme: 'primary', callback : function() { console.log(arg1['ports']); var node_interfaces = d3.select('#node_interfaces') .attr('align', "center") .append('svg') .attr('width', 490) .attr('height', 80) .style('border','1px solid black'); node_interfaces.append('g') .attr('class', 'node_interfaces') .selectAll('rect') .data(arg1['ports']) .enter().append('rect') .attr('width', function(d, i) { return d['coords'].w }) .attr('height', function(d, i) { return d['coords'].h } ) .attr('x', function(d, i) { return d['coords'].x } ) .attr('y', function(d, i) { return d['coords'].y} ) .attr('fill', function(d) { if(d.status === 'online') { return 'green' } if(d.status === 'offline') { return 'red' } if(d.status === 'testing') { return 'orange' } }); var tbody = $('#table_body'); $.each(arg1['ports'], function (i, item) { $('<tr>').append( $('<td>').text(item.ifindex), $('<td>').text(item.name), $('<td>').text(item.status), $('<td>').text(item.description)).appendTo(tbody); }); } }); } function getNeighbors(node) { return links.reduce(function (neighbors, link) { console.log('Link :', link.target['name']); if (link.target['name'] === node.name){ neighbors.push(link.source['name']); } else if (link.source['name'] === node.name) { neighbors.push(link.target['name']) } return neighbors }, [node.name] ) } function isNeighborLink(node, link) { return link.target.id === node.id || link.source.id === node.id } function getNeighborColor(node, neighbors) { if (Array.isArray(neighbors) && neighbors.indexOf(node.name) > -1) { return 'black' } } function getLinkColor(node, link) { console.log(link); return isNeighborLink(node, link) ? 'green' : '#E5E5E5' } function getTextColor(node, neighbors) { return Array.isArray(neighbors) && neighbors.indexOf(node.name) > -1 ? 'green' : 'black' } function getNodeColor(node) { if (node.status === 'online') { return 'green' } else if (node.status === 'offline') { return 'red' } else return 'orange' } function selectNode (selectedNode) { var neighbors = getNeighbors(selectedNode); console.log(neighbors); nodeElements.attr('stroke', function (node) { return getNeighborColor(node, neighbors) }) textElements.attr('fill', function (node) { return getTextColor(node, neighbors) }) linkElements.attr('stroke', function (d) { return getLinkColor(selectedNode, d) }) } var div = d3.select('#container').append('div') .attr('class', 'tooltip') .style('opacity', 0); var svg = d3.select('#container').append('svg') .attr('width', width) .attr('height', height) .style('border','1px solid black') .call(d3.zoom() .scaleExtent([1, 5]) .translateExtent([[-100, -100], [width + 90, height + 100]]) .on("zoom", function () { svg.attr("transform", d3.event.transform) })) .on('dblclick.zoom', null) .append("g"); var linkForce = d3 .forceLink() .id( function (link) { return link.name }) .strength( function () { return 0.1 }) .distance( 150 ); var simulation = d3 .forceSimulation() .force('link', linkForce) .force('charge', d3.forceManyBody().strength(-120)) .force('center', d3.forceCenter( width / 2, height / 2)); var dragDrop = d3.drag().on('start', function (node) { node.fx = node.x node.fy = node.y }).on('drag', function (node) { simulation.alphaTarget(0.7).restart() node.fx = d3.event.x node.fy = d3.event.y fix_nodes(node); }).on('end', function (node) { if (!d3.event.active) { simulation.alphaTarget(0) } node.fx = node.x node.fy = node.y }) function fix_nodes(this_node) { nodeElements.each(function(d) { if (this_node != d) { d.fx = d.x; d.fy = d.y; } }); } var linkElements = svg.append("g") .attr("class", "links") .selectAll("line") .data(links) .enter().append("line") .attr("stroke-width", 3) .attr("stroke", "darkgrey") .on('contextmenu', function(d) { d3.event.preventDefault(); if(d3.event.button == 2) { // tooltip to show neighbors info console.log(d.target.id); alert('hi'); } }); var nodeElements = svg.append('g') .attr('class', 'nodes') .selectAll('rect') .data(nodes) .enter().append('rect') .attr('width', 20) .attr('height', 20) .attr('fill', getNodeColor) .call(dragDrop) .on('dblclick', function(d) { newMethod(d, interfaces[d.id - 1]); }) .on('click', selectNode) .on('mouseover', function(d) { div.transition() .duration(200) .style('opacity', 0.9); div.html(`Name : ${d.name} <br> Status : ${d.status} <br> IP : ${d.ip_address} <br>` ) .style('left', d3.event.pageX + 'px') .style('top', d3.event.pageY + 'px') }) .on('mouseout', function() { div.transition() .duration(200) .style('opacity', 0); }); var textElements = svg.append('g') .attr('class', 'texts') .selectAll('text') .data(nodes) .enter().append('text') .text(function (node) { return node.name}) .attr('font-size', 15) .attr('dx', 25) .attr('dy', 15); simulation.nodes(nodes).on('tick', () => { nodeElements .attr('x', function(node) { return node.x}) .attr('y', function(node) { return node.y}) textElements .attr('x', function(node) { return node.x}) .attr('y', function(node) { return node.y}) linkElements .attr('x1', function(link) { return link.source.x + 10 }) .attr('y1', function(link) { return link.source.y + 10 }) .attr('x2', function(link) { return link.target.x + 10 }) .attr('y2', function(link) { return link.target.y + 10 }) }); simulation.force('link').links(links) } }
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:http/http.dart'; import 'package:login_task/auth_service.dart'; import 'package:login_task/screens/logged_in_screen.dart'; import 'package:login_task/screens/password_recovery_screen.dart'; import '../ui/custom_app_bar.dart'; import '../ui/resend_code.dart'; import '../ui/verification_code_input.dart'; enum VerficationType { signUp, passwordRecovery } class VerificationScreen extends StatefulWidget { final String email; final VerficationType type; const VerificationScreen(this.email, this.type, {super.key}); @override State<VerificationScreen> createState() => _VerificationScreenState(); } class _VerificationScreenState extends State<VerificationScreen> { List<FocusNode> focusNodes = []; bool _isVerified = false; bool _isSuccessful = false; bool _isResendCode = true; String? _code; @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: _isResendCode ? FutureBuilder( builder: (context, snapshot) { _isResendCode = false; if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator( color: Theme.of(context).secondaryHeaderColor, )); } else if (snapshot.hasError) { print(snapshot.error); return const Center( child: Text('Something went wrong. \nTry again later')); } else { return buildVerificationData(); } }, future: AuthService.sendVerificationCode(widget.email), ) : buildVerificationData(), )); } Column buildVerificationData() { return Column( key: GlobalKey(), children: [ const SizedBox( height: 14, ), const CustomAppBar('Verify Your Account'), const SizedBox( height: 23.65, ), const Padding( padding: EdgeInsets.symmetric(horizontal: 39.5), child: Text( 'Please enter the 4 - digit verification code we\n sent via mail:', textAlign: TextAlign.center, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w400), ), ), const SizedBox( height: 30, ), VerificationCodeInput( onVerificationCodeComplete: (code) => { AuthService.verifyVerificationCode(widget.email, code) .then((Response value) { setState(() { _code = code; _isVerified = true; if (jsonDecode(value.body)['data'] != null) { _isSuccessful = true; Future.delayed( const Duration(seconds: 1), () => { if (widget.type == VerficationType.passwordRecovery) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const PasswordRecoveryScreen(), ), ) } else { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const LoggedInScreen()), (Route<dynamic> route) => false, // Stop removing when reaching the MainScreen ) } }); } else { _isSuccessful = false; } }); }), }, isSuccessful: _isVerified ? _isSuccessful : null, initialValue: _code, ), if (_isVerified && !_isSuccessful) ...[ const SizedBox(height: 15), const Padding( padding: EdgeInsets.symmetric(horizontal: 23.65), child: Text( 'Incorrect Code', style: TextStyle(color: Color(0xFFD31510), fontSize: 15), ), ), ], const SizedBox(height: 30), ResendCode( onResend: () { setState(() { _isResendCode = true; }); }, ) ], ); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: brook <brook@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/02/13 21:57:26 by brook #+# #+# */ /* Updated: 2023/02/13 21:57:26 by brook ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FIXED_HPP #define FIXED_HPP #include <iostream> class Fixed { private: int _fp; static const int _fractionalBits; public: Fixed(); Fixed(const int num); Fixed(const float num); Fixed(const Fixed &fixed); Fixed &operator=(const Fixed &fixed); ~Fixed(); int getRawBits(void) const; void setRawBits(int const raw); float toFloat(void) const; int toInt(void) const; }; std::ostream &operator<<(std::ostream &output, const Fixed &f); #endif
package com.uservault.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.uservault.dto.user.AdminAuditDTO; import com.uservault.dto.user.AdminStatisticsDetailsDTO; import com.uservault.dto.user.AuditDetailDTO; import com.uservault.dto.user.UserAuditDTO; import com.uservault.dto.user.UserAuditDetailsDTO; import com.uservault.model.Action; import com.uservault.service.UserAuditService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.time.LocalDateTime; import java.util.List; import java.util.UUID; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; @SpringBootTest @AutoConfigureMockMvc public class AuditControllerTest { @InjectMocks private AuditController auditController; @Mock private UserAuditService userAuditService; @Mock private ObjectMapper objectMapper; private MockMvc mockMvc; @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); mockMvc = standaloneSetup(auditController).build(); } @Test @WithMockUser(roles = "ADMIN") public void shouldGetUserAudit() throws Exception { UUID uuid = UUID.randomUUID(); List<UserAuditDTO> userAuditDTOList = List.of(buildUserAuditDTO(uuid)); when(userAuditService.getUserAudit("email@email", uuid)).thenReturn(userAuditDTOList); mockMvc.perform(MockMvcRequestBuilders.get("/audit/users") .accept(MediaType.APPLICATION_JSON_VALUE) .param("email", "email@email") .param("user_id", String.valueOf(uuid)) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); verify(userAuditService, times(1)).getUserAudit("email@email", uuid); } @Test @WithMockUser(roles = "ADMIN") public void shouldGetAdminAudit() throws Exception { UUID uuid = UUID.randomUUID(); AdminAuditDTO adminAuditDTO = buildAdminAuditDTO(); when(userAuditService.getAdminAuditByEmailOrId("email@email", uuid)).thenReturn(adminAuditDTO); mockMvc.perform(MockMvcRequestBuilders.get("/audit/admin") .accept(MediaType.APPLICATION_JSON_VALUE) .param("email", "email@email") .param("user_id", String.valueOf(uuid)) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); verify(userAuditService, times(1)).getAdminAuditByEmailOrId("email@email", uuid); } private UserAuditDTO buildUserAuditDTO(UUID uuid) { try { JsonNode previous = objectMapper.readTree("{\"name\": \"user\"}"); JsonNode current = objectMapper.readTree("{\"name\": \"new user name\"}"); AuditDetailDTO details = new AuditDetailDTO(previous, current, null); UserAuditDetailsDTO userPerformedAction = new UserAuditDetailsDTO(UUID.randomUUID(),"user", "user@email"); UserAuditDetailsDTO userRelated = new UserAuditDetailsDTO(UUID.randomUUID(),"user", "user@email"); return new UserAuditDTO(UUID.randomUUID(), Action.INSERTED, LocalDateTime.now(), details, userPerformedAction, userRelated); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } private AdminAuditDTO buildAdminAuditDTO() { UserAuditDetailsDTO userAuditDetailsDTO = new UserAuditDetailsDTO(UUID.randomUUID(), "name", "email@email"); AdminStatisticsDetailsDTO adminStatisticsDetailsDTO = new AdminStatisticsDetailsDTO(Action.INSERTED, anyInt(), List.of(userAuditDetailsDTO)); return new AdminAuditDTO(UUID.randomUUID(), "admin", anyInt(), List.of(adminStatisticsDetailsDTO)); } }